function update_partnumber()
{   // keep the global var 'kit' changing with each selection
    var carrier = 'DB';
    
    var display   = ( $('#Select_LCD').val() === null ? '???' : $('#Select_LCD').val() );
    var overlay   = ( $('#SelectOverlay').val() === null ? '??' : $('#SelectOverlay').val() );

    clear_pricing();
    
    var tmp = overlay.match(/([A-Z]+)\d/);
    if(tmp && tmp.length) 
    {
        overlay = tmp[1];
        carrier = 'DS';
    }

    var color     = ( $('#DisplayColor').val() === null ? '???' : $('#DisplayColor').val() );
    var interface = ( $('#SelectInterface').val() === null ? '???' : $('#SelectInterface').val() );

    var bracket = display + overlay;

    // kit = carrier + bracket;
    kit = carrier + display + '-' + overlay;
    
    if(bracket.search(/\?/) == -1 && color == '???' && interface == '???')
        $('#PartNumber').text(kit);
    else
    {
        // kit = kit + '-' + overlay + color + '-' + interface;
        kit = kit + color + '-' + interface;
    }
    // if(window.console) console.log('update_partnumber: kit='+ kit);
    $('#PartNumber').text(kit);
}

function make_display_menu(selected_display)
{ // make all the display options and maybe preselect one
    var match = '???';

    // if(window.console) console.log(selected_display);

    for(var i=0; i<aModules.length; i++)
    {                                   // value, label
        $('#Select_LCD').addOption(aModules[i][0][0], aModules[i][0][1]);

        // set LCD type based pn 
        if(aModules[i][0][0] == selected_display)
        {
            make_dependent_menus(i); 
            match = selected_display;
        }        
    }
    $("#Select_LCD").selectOptions(match, true); // otherwise firefox tends to make last option added the selected
    // or could have done:
    //     $("#Select_LCD option").removeAttr('selected');
    //     $("#Select_LCD option[value="+ LCD +"]").attr('selected', 'true');
}

function display_to_index(selected_value)
{ // given selected value '631' from Display menu, what is its index in the aModules array?
    
    for(var i=0; i<aModules.length; i++)
    {
        if(aModules[i][0][0] == selected_value) return i;
    }
    return -1;    
}

function make_dependent_menus(display_index)
{
    // display_index is the index of which Module has been chosen from the Display menu. -1 if none, 0 if first, 1 second, etc.
    $("#DisplayColor, #SelectOverlay, #SelectInterface").removeOption(/./);

    clear_pricing();

    $("#SelectOverlay_imgs, #DisplayColor_imgs, #SelectInterface_imgs").html('');
     
    if(display_index == -1)
    {
        $("#DisplayColor, #SelectOverlay, #SelectInterface").addOption('???', 'Please Select a Display First'); 
    }
    else
    {
        make_overlay_menu(display_index);
        make_color_menu(display_index);
        make_interface_menu(display_index);
    }
    update_partnumber(); 
}

function make_overlay_menu(display_index)
{   // make the overlay menu that goes with a specific display value
    // make_dependent_menus() already removed all options and cleared all thumbs, so its a blank slate
    
    $("#SelectOverlay").addOption('???', 'Please Select LCD Overlay Color');

    var match = '???';
    
    for(var i=0; i<aModules[display_index][1][0].length; i++)
    {
        $("#SelectOverlay").addOption(aModules[display_index][1][0][i], aModules[display_index][1][1][i]);   // value, label

        if((aModules[display_index][1][0][i] == kit.substring(5,7) && kit.substring(0,2) != 'DS') ||
           (aModules[display_index][1][0][i] == kit.substring(5,7)+"2" && kit.substring(0,2) == 'DS') )
        {
            //set Overlay type based on pn  
            match = aModules[display_index][1][0][i];
            make_overlay_img(aModules[display_index], i);
        }
    }
    $("#SelectOverlay").selectOptions(match, true);
}

function make_overlay_img(arr, which_img)
{   // arr is the module array in aModules, like aModules[1]
    // which_img is the position of the img src in another array

    var myregexp = /product[s]?\/([^\./?]+)/i;    
    var mymatch = myregexp.exec(arr[1][3][which_img]);

    var html = "<a target='_new' href='"+ arr[1][3][which_img] +
               "'><img src='"+ arr[1][2][which_img] +"' ";
    
    if(mymatch.length > 0)
    {
        // console.log(mymatch[1]);
        html += "alt='"+ mymatch[1] +"' title='"+ mymatch[1] +"' ";
    }

    html += "/></a> ";

    $('#SelectOverlay_imgs').html(html);

}

function make_color_menu(display_index)
{
    $("#DisplayColor").addOption('???', 'Please Select a Display Color');
    
    var match = '???';
    
    for(var i=0; i<aModules[display_index][2][0].length; i++)
    {
        $("#DisplayColor").addOption(aModules[display_index][2][0][i], aModules[display_index][2][1][i]); // value, label
            
        if(aModules[display_index][2][0][i] == kit.substring(7, 10))
        {
            //set DisplayColor type based on pn 
            match = aModules[display_index][2][0][i];
            make_color_img(aModules[display_index], i);
        }
    }
    $("#DisplayColor").selectOptions(match, true);
}

function make_color_img(arr, which_img)
{   // arr is the module array in aModules, like aModules[1]
    // which_img is the position of the img src in another array


//    console.log(arr[2][3][which_img]);

    var myregexp = /product[s]?\/([^\./]+)/i;    
    var mymatch = myregexp.exec(arr[2][3][which_img]);

    var html = "<a target='_new' href='"+ arr[2][3][which_img] +
               "'><img src='"+ arr[2][2][which_img] +"' ";
    
    if(mymatch.length > 0)
    {
        // console.log(mymatch[1]);
        html += "alt='"+ mymatch[1] +"' title='"+ mymatch[1] +"' ";
    }

    html += "/></a> ";

    $('#DisplayColor_imgs').html(html);
}

function make_interface_menu(display_index)
{
    $("#SelectInterface").addOption('???', 'Please Select LCD Interface and Cables');

    var match = '???';
    
    for(var i=0; i<aModules[display_index][3][0].length; i++)
    {
        $("#SelectInterface").addOption(aModules[display_index][3][0][i], aModules[display_index][3][1][i]); // value, label

        if(aModules[display_index][3][0][i] == kit.substring(10, kit.length))
        {
            //set Interface type based on pn  
            match = aModules[display_index][3][0][i]; 
            make_interface_imgs(aModules[display_index], i);     
        }
    }
    $("#SelectInterface").selectOptions(match, true);
}

function make_interface_imgs(arr, which_img)
{
    var myregexp = /product[s]?\/([^\./]+)/i;    

    if(arr[3][2][which_img].length)
    {
        var j;
        for(j=0; j<arr[3][2][which_img].length; j++)
        {

            // console.log(arr[3][3][which_img][j]);
            var mymatch = myregexp.exec(arr[3][3][which_img][j]);

            var html = "<a target='_new' href='"+ arr[3][3][which_img][j] +
               "'><img src='"+ arr[3][2][which_img][j] +"' ";
    
            if(mymatch.length > 0)
            {
                // console.log(mymatch[1]);
                html += "alt='"+ mymatch[1] +"' title='"+ mymatch[1] +"' ";
            }

            html += "/></a> ";

            $('#SelectInterface_imgs').html($('#SelectInterface_imgs').html() + html); 
        }
    }    
}







function clear_pricing()
{
    //Default pricing fields to empty
    $('#prices').hide();
    $('#SinglePrice').text('');
    $('#TotalPrice').text('');
    $('#backordered').hide();
    $('#backordered-date').text('');    
    $('#pricebreaks').hide();
    $('.pricebreak').remove(); // price breaks chart
    $('#quantity').val('');
}

function show_pricing()
{ // for global var kit
    var pdata_index = find_position_by_partnumber(kit);

    // console.log(kit + pdata_index);

    if(pdata_index > -1)
    {
        //get pid for part number
        var pid = pdata[pdata_index][0][0];

        if (pdata[pdata_index][0][2] != 0)
        {
            //item is backordered, display warning
            $("#backordered").show();
            $("#backordered-date").text(pdata[pdata_index][0][2]);
        }

        $('.pricebreak').remove(); // clear before appending new ones        
        
        var qty_td, price_td;
        for (var i = 0; i < pdata[pdata_index][1].length; i++)
        {
            qty_td = '<td class="pricebreak">' + pdata[pdata_index][1][i][0] + '+';
            if(parseInt(pdata[pdata_index][1][i][0]) >= 50) qty_td = qty_td + ' *';
            qty_td = qty_td + '</td>';
            price_td = '<td class="pricebreak">$' + round(pdata[pdata_index][1][i][1]) + '</td>';
            $('#qtyrow').append(qty_td);
            $('#pricerow').append(price_td);
        }
        
        var qty = Math.abs(parseInt($('#quantity').val()));
        
        if(isNaN(qty))
        {
            $('#quantity').val('');
        }
        else
        {
            $('#quantity').val(qty); // in case it changed?
        
            // ajax request adds item to your cart, or deletes from cart if qty < 1
            $.getJSON("/cart/kitconfig_pricing_ajax.php", { qty: qty, pid: pid, json: 1 }, function(data) {
                // console.log(data);
                $('#SinglePrice').text('$' + data.single);
                $('#TotalPrice').text('$' + data.total);
            });
        
            // doing the below does not put the item in the cart. Ajax request will
            //    var single = round(LookupPrice(kit,qty));
            //    $('#SinglePrice').text('$'+ single);
            //    $('#TotalPrice').text('$'+ round(qty * parseFloat(single)));       
        } // quantity they wanted was a number

        $('#prices').show();       
        $('#pricebreaks').show();       
        return pid;
    } // end 'kit' was a valid part number
    else 
    {
        clear_pricing();
        return 0;
    }
}

function round(value)
{
    value = parseFloat(value) * 100.0;

    if(value - parseInt(value) > 0.5) value++;

    var cents = parseInt(value % 100);
    if(cents <= 9) cents = "0"+cents;
    
    var dollars = parseFloat(value/100);
    if(dollars < 1) dollars = 0;
    else dollars = parseInt(value/100);
    
    return dollars + '.' + cents;
}

function LookupPriceByPdataPosition(pdata_index, qt)
{
    var price = pdata[pdata_index][1][0][1];
    for (var i = 0; i < pdata[pdata_index][1].length; i++)
    {
        if (parseFloat(qt) >= parseFloat(pdata[pdata_index][1][i][0]))
        {
            price = pdata[pdata_index][1][i][1];
        }
    }
    return price;
}

function LookupPrice(part_number, qt)
{
    var pnum = find_position_by_partnumber(part_number);
    if (pnum == -1) return "0.00";

    return LookupPriceByPdataPosition(pnum, qt);    
}

function find_position_by_partnumber(item)
{
    var hash;
    var ritem;

    item = item.replace(/-/g, '');

    if (item.indexOf("#") != -1)
    {
        //has multiples #, remove it
        var aitem = item.split("#");
        ritem = aitem[0];
    }
    else
        ritem = item;

    for (var p=0; p < pdata.length; p++)
        if (pdata[p][0][1] == ritem)
            return p;
    return -1;
}

