// Global
var colormap = new Array();


function debug(s){
    if (console != undefined){
        console.log(s);
    }
}

function wordToUpper(strSentence) {
    return strSentence.toLowerCase().replace(/\b[a-z]/g, convertToUpper);

    function convertToUpper() {
        return arguments[0].toUpperCase();
    }
}


function updateSidebarColors(data){
    if (data['exterior']['swatch'] != null)
        $('#style-ext-swatch').attr('src', data['exterior']['swatch']);
        $('#colors-ext-swatch').attr('src', data['exterior']['swatch']);
        $('#options-ext-swatch').attr('src', data['exterior']['swatch']);
        $('#summary-ext-swatch').attr('src', data['exterior']['swatch']);
        $('#photos-ext-swatch').attr('src', data['exterior']['swatch']);

    $("#style-ext-color").html(data['exterior']['name']);
    $("#style-int-color").html(data['interior']['name'] + " Interior");
    $("#style-color-link-text").html("Change");
    $("#colors-ext-color").html(data['exterior']['name']);
    $("#colors-int-color").html(data['interior']['name'] + " Interior");
    $("#colors-color-link-text").html("Change");
    $("#options-ext-color").html(data['exterior']['name']);
    $("#options-int-color").html(data['interior']['name'] + " Interior");
    $("#options-color-link-text").html("Change");
    $("#summary-ext-color").html(data['exterior']['name']);
    $("#summary-int-color").html(data['interior']['name'] + " Interior");
    $("#summary-color-link-text").html("Change");
    $("#photos-ext-color").html(data['exterior']['name']);
    $("#photos-int-color").html(data['interior']['name'] + " Interior");
    $("#photos-color-link-text").html("Change");

    // set the set option:
    // set the seat option in the options list:
    if ($("#" + data['interior']['id'] + "-I"))
        $("#" + data['interior']['id'] + "-I").click();
    if ($("#" + data['interior']['id']))
        $("#" + data['interior']['id']).click();


}

function updateSidebarIntColor(color){
    $("#style-int-color").html(color + " Interior");
    $("#colors-int-color").html(color + " Interior");
    $("#options-int-color").html(color + " Interior");
    $("#summary-int-color").html(color + " Interior");
    $("#photos-int-color").html(color + " Interior");
}


function getColorId(data){
    // The 'colorId' we're fetching here is a code that represents a combination of the exterior and interior colors.
    // First we get the colors that are selected by code
    //var intcode = $('#tab-colors input:checked[name=intcolor]').val();
    var extcode = $('#tab-colors input:checked[name=extcolor]').val();

    // now since two exterior colors can be called 'Black' but have different
    // codes depending on their corresponding interior colors, we fetch the
    // color name so we can see if there is a pair for the currently selected
    // colors
    //var intname = $("#intColorDiv-" + intcode).html();
    var extname = $('.colorrow-' + extcode + ' .last').html();

    /*
    for(i in data['colors']){
        if(data['colors'][i]['exterior']['name'] == extname){
            if(intname == undefined || data['colors'][i]['interior']['code'] == intcode){
                return data['colors'][i]['id'];
            }
        }
    }
    */

    // If we've made it here, there is no matching pair so just return the first ext match
    for(i in data['colors']){
        if(data['colors'][i]['exterior']['name'] == extname){
            return data['colors'][i]['id'];
        }
    }
    return '';
}


/*
function updateInteriorColors(data, extname){
    var intcolors = '';
    for(i in data['colors']){
        if(data['colors'][i]['exterior']['name'] == extname){
            var intcode = data['colors'][i]['interior']['code'];
            // check to see if the interior color is checked, if it is, we need
            // to also select the seat trim for that interior color
            if (data['colors'][i]['checked'].indexOf("\"checked\"") >= 0)
            {
                $('#' + intcode).attr("checked", "checked");
            }
            //alert(data['colors'][i]['interior']['condition'])
            // the colorrow- class is used to lookup this row and fetch the color name based on the code
            intcolors += "<tr class='colorrow-" + data['colors'][i]['interior']['code'] + "'>";
            intcolors += "<td style='width: 20px;'><input type='radio' class='color" + data['colors'][i]['condition'] + "' name='intcolor' value='" + data['colors'][i]['condition'] + "' " + data['colors'][i]['disabled'] + " " + data['colors'][i]['checked'] +"/>";
            intcolors += "</td>";
            // The 'last' class is relied upon here, it's used to lookup the color name in places
            if (data['colors'][i]['interior']['code'] != null)
                intcolors += "<td colspan='2' class='last' style='text-transform:capitalize'><div style='display:none;' id='intColorDiv" + data['colors'][i]['condition'] + "'>" + data['colors'][i]['condition'] + "</div><span id='intColor" + data['colors'][i]['condition'] + "'>" + data['colors'][i]['interior']['name'] + ' Cloth</span></td>';
            else
                intcolors += "<td colspan='2' class='last' style='text-transform:capitalize'><div style='display:none;' id='intColorDiv" + data['colors'][i]['condition'] + "'>" + data['colors'][i]['condition'] + "</div><span id='intColor" + data['colors'][i]['condition'] + "'>" + data['colors'][i]['interior']['name'] + ' Leather</span></td>';

            intcolors += "</tr>";
        }
    }
    return intcolors;
}
*/

function createInteriorColorsTable(heading, rows){
    var intcolors = '';
    $.each(rows, function(){
        //alert(wordToUpper(this['description']['primary']));
        intcolors += "<tr>";
        intcolors += "<td style='width: 20px;'><input type='radio' id='intcolor" + this['id'] + "' name='intcolor' value='" + this['id'] + "~" + wordToUpper(this['description']['primary']) + "' " + this['checked'] +"/>";
        intcolors += "</td>";
        // The 'last' class is relied upon here, it's used to lookup the color name in places
        intcolors += "<td colspan='2'>" + wordToUpper(this['description']['primary']) + "</td>";
        intcolors += "</tr>";
    });

    $("#interior-colors").html(intcolors);

    // setup the onclick
    $('#tab-colors input[name=intcolor]').click(function(){
            var intcode = $(this).val().split("~")[0];
            $('#' + intcode).click();
            updateSidebarIntColor($(this).val().split("~")[1]);
            /*
            var url = '/vehicles/json/select_color/' + data['style'] + '/color/' + cid + '/';
            $.ajax({
              url: url,
              cache: false,
              dataType: "json",
              success: function(data) {
                updateConfigData(data);
                if ($("#intColor" + intcode).html().indexOf(",") > 0)
                {
                    var tempcolor = $("#intColor" + intcode).html().substr(0, $("#intColor" + intcode).html().indexOf(","));
                    $(".color-" + intcode).attr("checked", "checked");
                    updateSidebarIntColor(tempcolor);
                }
                else
                {
                    $(".color" + intcode).attr("checked", "checked");
                    updateSidebarIntColor($("#intColor" + intcode).html());
                }
                // set the seat option in the options list:
                if ($("#" + intcode))
                    $("#" + intcode).click();
            }});
            */
        });


}


function addOptionsTable(heading, rows, type){
    var t = '<h3>' + heading + '</h3>';
    t += '<table cellpadding="0" cellspacing="1" class="dataTable smaller optionsTable" id="options-' + heading + '">';
    t += '<thead>';
    t += '<tr><th width="10"><span>&nbsp;</span></th>';
    t += '<th width="100"><span>&nbsp;</span></th>';
    t += '<th width="50"><span>MSRP</span></th>';
    t += '<th width="50"><span>Invoice</span></th>';
    t += '</tr></thead>';
    t += '<tbody>';

    var isColor = false;
    if (heading == 'Seat Type')
        isColor = true;

    $.each(rows, function(){
        t += addOptionRow(this, type, isColor);
    });

    t += '</tbody>';
    t += '</table>';

    return t;
}

function addOptionRow(data, type, isColor){
    var s = '';
    s += '<tr id="option-row-' + data['id'] + '">';
    //s += '<td><input type="'+ type +'" id="' + data['id'] + '" title="' + wordToUpper(data['description']['primary']) + ", " +  data['header'] + ' ' + data['kind'] + ", " + data['id'] + ": " + data['invoice']  + '" name="option" class="option-' + data['id'] + '" value="' + data['id'] + '" ' + data['checked'] +' ' + data['disabled'] + '/></td>';
    if (isColor)
        s += '<td><input type="'+ type +'" id="' + data['id'] + '" title="' + wordToUpper(data['description']['primary']) + ", " +  data['header'] + ' ' + data['kind'] + ", " + data['id'] + ": " + data['invoice']  + '" name="option-color" class="option-' + data['id'] + '" value="' + data['id'] + '" ' + data['checked'] + '/></td>';
    else
        s += '<td><input type="'+ type +'" id="' + data['id'] + '" title="' + wordToUpper(data['description']['primary']) + ", " +  data['header'] + ' ' + data['kind'] + ", " + data['id'] + ": " + data['invoice']  + '" name="option" class="option-' + data['id'] + '" value="' + data['id'] + '" ' + data['checked'] + '/></td>';
    s += '<td>';
    // Wrap description text in span so we can fetch it from the summary page
    s += "<span id='" + data['id'] + "description' class='description'>" + wordToUpper(data['description']['primary']) + "</span><br/>" + wordToUpper(data['description']['ext']);
    if (data['description']['warning'] != ''){

        s += "<div class='option-warning'>" + data['description']['warning'] + "</div>";
    }
    if (data['description']['notice'] != ''){
        s += "<div class='option-notice'>" + data['description']['notice'] + "</div>";
    }
    s += '<div class="discreet" style="color: #FD0000;" id="' + data['id'] + 'required"></div>';
    s += '<div class="discreet">' + data['header'] + ' - ' + data['kind'] + " - " + data['id'] + "</div>";
    s += "</td>";

    // option-msrp and option-invoice used in summary tab
    s += "<td class='option-msrp'><span>" + data['msrp'] + "</span></td>";
    s += "<td class='option-invoice'><span>" + data['invoice'] + "</span></td>";
    s += "</tr>";

    return s;
}

function getOptionText(id, data){
    var result = '';
    $.each(data,
        function(group,options){
            $.each(options, function(){
                if (this['id'] == id){
                    result += group + ": " + this['description']['primary'];
                    return result;
                }
            });
        });
    return result; // In case we get this far...
}

function setGarageStatus(in_garage){
    if(in_garage){
        $('a#toggle-saved').removeClass('save');
        $('a#toggle-saved').addClass('remove');
        $('a#toggle-saved').html('Remove |');
    } else {
        $('a#toggle-saved').removeClass('remove');
        $('a#toggle-saved').addClass('save');
        $('a#toggle-saved').html('Save |');
    }
}

function updateColorData(data){
    var extcolors = '';
    var intcolors = '';
    var added = new Array();
    // blank out the sidebar colors
    // reset all existing:
    $('#style-ext-swatch').attr('src','');
    $("#style-ext-color").html('');
    $("#style-int-color").html('');
    $('#colors-ext-swatch').attr('src','');
    $("#colors-ext-color").html('');
    $("#colors-int-color").html('');
    $('#options-ext-swatch').attr('src','');
    $("#options-ext-color").html('');
    $("#options-int-color").html('');
    $('#summary-ext-swatch').attr('src','');
    $("#summary-ext-color").html('');
    $("#summary-int-color").html('');
    $('#photos-ext-swatch').attr('src','');
    $("#photos-ext-color").html('');
    $("#photos-int-color").html('');

    var selected_ext_name = ''
    $.each(data['colors'], function(){
        if(this['checked']){
            // we need to get this value for later determining which color was selected.
            selected_ext_name = this['exterior']['name'].replace(/ /g,'-');
            // Display color in left sidebar
            updateSidebarColors(this);

            // Update summary
            if (this['exterior']['swatch'] != null)
                $('#summary-wrapper .extcolor').html('<img width="12" height="12" src="' + this['exterior']['swatch'] + '"/> ' + this['exterior']['name']);
            else
                $('#summary-wrapper .extcolor').html(this['exterior']['name']);
            //$('#summary-wrapper .intcolor').html(this['interior']['name']);

            //intcolors = updateInteriorColors(data, this['exterior']['name']);
            $('div.pic img').attr('width', '270');

            var url = '/chrome/colormap/' + data['style'] + '/' + this['exterior']['code'] + '/';
            $.ajax({
              url: url,
              cache: false,
              dataType: "json",
              success: function(data) {
                $('div.pic img').attr('src', 'http://media.save100bucks.com/img/chrome-image-gallery/ColorMatched/Transparent/320/' + data['path']);
                $('.photos').prepend("<a class='vehicle-photo' rel='group' href='http://media.save100bucks.com/img/chrome-image-gallery/ColorMatched/Transparent/320/" + data['path'] + "' title='Configured color'><img width='200px' src='http://media.save100bucks.com/img/chrome-image-gallery/ColorMatched/Transparent/320/" + data['path'] + "' /></a>");
                $("a.vehicle-photo").fancybox({
                    'overlayShow': true,
                    'overlayOpacity': .5,
                    'padding': 0
                });

            }});
        }
        if(added[this['exterior']['name']] == undefined){
            var id_val = "color-" + this['exterior']['name'].replace(/ /g,'-');
            extcolors += "<tr class='colorrow-" + this['exterior']['code'] + "'>";
            extcolors += "<td style='width: 20px;'><input type='radio' id='" + id_val + "' class='color-" + this['exterior']['name'] + "' name='extcolor' value='" + this['exterior']['code'] + "' " + this['checked'] +"/>";

            extcolors += "</td>";
            if (this['exterior']['swatch']  != null)
                extcolors += "<td style='width: 20px;'><img width='20' height='20' src='" + this['exterior']['swatch'] + "'/></td>";
            else
                extcolors += "<td style='width: 20px;'>&nbsp;</td>";
            extcolors += "<td class='last'>" + this['exterior']['name'] + '</td>';
            extcolors += "</tr>";

            added[this['exterior']['name']] = 1;
        }
    });

    $('#exterior-colors').html(extcolors);

    // Only want these if there is a color selected
    /*
    if(intcolors != ''){
        $('#choose-interior-color').show();
        $('#interior-colors').html(intcolors);
    }

    $('#tab-colors input[name=intcolor]').click(function(){
            var intcode = $(this).val();
            var cid = getColorId(data);
            $('#' + intcode).click();
            var url = '/vehicles/json/select_color/' + data['style'] + '/color/' + cid + '/';
            $.ajax({
              url: url,
              cache: false,
              dataType: "json",
              success: function(data) {
                updateConfigData(data);
                if ($("#intColor" + intcode).html().indexOf(",") > 0)
                {
                    var tempcolor = $("#intColor" + intcode).html().substr(0, $("#intColor" + intcode).html().indexOf(","));
                    $(".color-" + intcode).attr("checked", "checked");
                    updateSidebarIntColor(tempcolor);
                }
                else
                {
                    $(".color" + intcode).attr("checked", "checked");
                    updateSidebarIntColor($("#intColor" + intcode).html());
                }
                // set the seat option in the options list:
                if ($("#" + intcode))
                    $("#" + intcode).click();
            }});
        });
    */

    $('#tab-colors input[name=extcolor]').click(function(){
            var extcode = $(this).val();
            var cid = getColorId(data);
            var url = '/vehicles/json/select_color/' + data['style'] + '/color/' + cid + '/';
            $.ajax({
              url: url,
              cache: false,
              dataType: "json",
              success: function(data) {
                if ( !$('#tab-colors input:checked[name=intcolor]').val() && ! $('#tab-colors input:checked[name=extcolor]').val() ){
                    $('div.pic img').attr('width', '270');
                    // we are caching the images locally, so convert the photo url to the server
                    var photo_url = data['photo_url'].replace("http://media.carbook.com/autoBuilderData", "http://media.save100bucks.com/img");
                    $('#style-pic').attr('src', photo_url);
                    $('#colors-pic').attr('src',photo_url);
                    $('#options-pic').attr('src', photo_url);
                    $('#photos-pic').attr('src', photo_url);
                    $('#summary-pic').attr('src', photo_url);
                }

                updateConfigData(data);
                updateColorData(data);
            }});
        });

    // make sure the exterior color gets checked.
    $("#color-" + selected_ext_name).attr("checked", "checked");

    $('#exterior-colors tbody tr:last').addClass('lastRow');
    $('#interior-colors tbody tr:last').addClass('lastRow');

}


function updateSummaryOptions(){
    // blank out the summary tab options listing table

    $('#summary-selected-options tbody').html('');
    // List each checked option here along with price
    $('#option-tables input:checked').each(function(){
        var name = $('#option-row-' + $(this).val() + ' span.description').html();
        var msrp = $('#option-row-' + $(this).val() + ' td.option-msrp').html();
        var invoice = $('#option-row-' + $(this).val() + ' td.option-invoice').html();

        var s = '';
        s += '<tr>';
        s += '<td width="200">' + name + '</td>';
        s += '<td style="text-align: right;"><strong>' + msrp + '</strong></td>';
        s += '<td style="text-align: right;"><strong>' + invoice + '</strong></td>';
        s += '</tr>';

        $('#summary-selected-options  tbody').append(s);
    });
}



function updateOptionData(data){
    $.each(data['options'], function(heading, rows){
        $.each(rows, function(){
            if(this['checked'] != ''){
                $('input[value=' + this['id'] + ']').attr('checked', 'checked');
                if (this['disabled'])
                    $('#' + this['id'] + 'required').html("This option was required as a result of another option you selected.");
            } else {
                $('input[value=' + this['id'] + ']').attr('checked', '');
                $('#' + this['id'] + 'required').html("");
            }
        });
    });

    $('#option-tables tr').removeClass('active');
    $('#option-tables tr:has(input:checked)').addClass('active');
    // Update summary tab
    updateSummaryOptions();
}

function updateConfigData(data){
    // Only update with the stock photo if no color is selected

    // style tab
    $('#style-base-msrp').html(data['base_msrp']);
    $('#style-base-invoice').html(data['base_invoice']);
    $('#style-options-msrp').html(data['options_msrp']);
    $('#style-options-invoice').html(data['options_invoice']);
    $('#style-total-msrp').html(data['total_msrp']);
    $('#style-total-invoice').html(data['total_invoice']);
    $('#style-destination-msrp').html(data['destination']);
    $('#style-destination-invoice').html(data['destination']);
    // colors tab
    $('#colors-base-msrp').html(data['base_msrp']);
    $('#colors-base-invoice').html(data['base_invoice']);
    $('#colors-options-msrp').html(data['options_msrp']);
    $('#colors-options-invoice').html(data['options_invoice']);
    $('#colors-total-msrp').html(data['total_msrp']);
    $('#colors-total-invoice').html(data['total_invoice']);
    $('#colors-destination-msrp').html(data['destination']);
    $('#colors-destination-invoice').html(data['destination']);
    // options tab
    $('#options-base-msrp').html(data['base_msrp']);
    $('#options-base-invoice').html(data['base_invoice']);
    $('#options-options-msrp').html(data['options_msrp']);
    $('#options-options-invoice').html(data['options_invoice']);
    $('#options-total-msrp').html(data['total_msrp']);
    $('#options-total-invoice').html(data['total_invoice']);
    $('#options-destination-msrp').html(data['destination']);
    $('#options-destination-invoice').html(data['destination']);
    // photos tab
    $('#photos-base-msrp').html(data['base_msrp']);
    $('#photos-base-invoice').html(data['base_invoice']);
    $('#photos-options-msrp').html(data['options_msrp']);
    $('#photos-options-invoice').html(data['options_invoice']);
    $('#photos-total-msrp').html(data['total_msrp']);
    $('#photos-total-invoice').html(data['total_invoice']);
    $('#photos-destination-msrp').html(data['destination']);
    $('#photos-destination-invoice').html(data['destination']);
    // summary tab
    $('#summary-base-msrp').html(data['base_msrp']);
    $('#summary-base-invoice').html(data['base_invoice']);
    $('#summary-options-msrp').html(data['options_msrp']);
    $('#summary-options-invoice').html(data['options_invoice']);
    $('#summary-total-msrp').html(data['total_msrp']);
    $('#summary-total-invoice').html(data['total_invoice']);
    $('#summary-destination-msrp').html(data['destination']);
    $('#summary-destination-invoice').html(data['destination']);
    // Update summary tab right side contents
    $('#summary-wrapper td.trim').html('<span>' + data['name'] + ' Trim</span>');
    $('#summary-wrapper td.price').html(data['total_msrp']);

    // Update summary tab
    updateSummaryOptions();
}

function setupLeftConfigData(data){
    // style tab


    $('#style-base-msrp').html(data['base_msrp']);
    $('#style-base-invoice').html(data['base_invoice']);
    $('#style-options-msrp').html(data['options_msrp']);
    $('#style-options-invoice').html(data['options_invoice']);
    $('#style-total-msrp').html(data['total_msrp']);
    $('#style-total-invoice').html(data['total_invoice']);
    $('#style-destination-msrp').html(data['destination']);
    $('#style-destination-invoice').html(data['destination']);

    // colors tab
    $('#colors-base-msrp').html(data['base_msrp']);
    $('#colors-base-invoice').html(data['base_invoice']);
    $('#colors-options-msrp').html(data['options_msrp']);
    $('#colors-options-invoice').html(data['options_invoice']);
    $('#colors-total-msrp').html(data['total_msrp']);
    $('#colors-total-invoice').html(data['total_invoice']);
    $('#colors-destination-msrp').html(data['destination']);
    $('#colors-destination-invoice').html(data['destination']);

    // options tab
    $('#options-base-msrp').html(data['base_msrp']);
    $('#options-base-invoice').html(data['base_invoice']);
    $('#options-options-msrp').html(data['options_msrp']);
    $('#options-options-invoice').html(data['options_invoice']);
    $('#options-total-msrp').html(data['total_msrp']);
    $('#options-total-invoice').html(data['total_invoice']);
    $('#options-destination-msrp').html(data['destination']);
    $('#options-destination-invoice').html(data['destination']);

    // photos tab
    $('#photos-base-msrp').html(data['base_msrp']);
    $('#photos-base-invoice').html(data['base_invoice']);
    $('#photos-options-msrp').html(data['options_msrp']);
    $('#photos-options-invoice').html(data['options_invoice']);
    $('#photos-total-msrp').html(data['total_msrp']);
    $('#photos-total-invoice').html(data['total_invoice']);
    $('#photos-destination-msrp').html(data['destination']);
    $('#photos-destination-invoice').html(data['destination']);

    // summary tab
    $('#summary-base-msrp').html(data['base_msrp']);
    $('#summary-base-invoice').html(data['base_invoice']);
    $('#summary-options-msrp').html(data['options_msrp']);
    $('#summary-options-invoice').html(data['options_invoice']);
    $('#summary-total-msrp').html(data['total_msrp']);
    $('#summary-total-invoice').html(data['total_invoice']);
    $('#summary-destination-msrp').html(data['destination']);
    $('#summary-destination-invoice').html(data['destination']);

}


function setupAdditionalPhotos(data){
    // put the additional photos in the additional photos tab
    var additionalImagesHtml = ''
    for (var i=0; i<data['additional_images'].length; i++) {
        var image640 = data['additional_images'][i].replace(/320/g, "640");
        additionalImagesHtml += "<a class='vehicle-photo' rel='group' href='" + image640 + "' title=''><img width='200px' src='" +
                                data['additional_images'][i] + "' alt='' /></a>";
    }
    $('#photos').html(additionalImagesHtml);
    // and add a fancy box to the images
    $("a.vehicle-photo").fancybox({
        'overlayShow': true,
        'overlayOpacity': .5,
        'padding': 0
    });
}

function buildAndPopulateOptionsTable(data){
    // Build option tables
    var options = '';
    if (data['options']['Quick-Order Package']){
        options += addOptionsTable('Quick-Order Packages', data['options']['Quick-Order Package'], 'radio');
    }
    // here is where the options get popuplated.
    $.each(data['options'],
        function(heading, rows){
            if (heading == 'Seat Type')
            {
               createInteriorColorsTable(heading, rows);
            }
            if (heading != 'Quick-Order Package'){
                options += addOptionsTable(heading, rows, 'checkbox');
            } else if (heading == 'Engine'){
                options += addOptionsTable(heading, rows, 'radio');
            }
        }
    );
    // add the option table to the appropriate div
    $('#option-tables').html(options);
    // remove all the 'active' rows
    $('#option-tables tr').removeClass('active');
    // update the table rows to highlight which options have been checked
    $('#option-tables tr:has(input:checked)').addClass('active');

}

function setupConfigData(data){

    // setup the additional photos in the additional photos tab
    setupAdditionalPhotos(data);

    $("#style-selected-style").html($("#style option:selected").text());
    $("#colrs-selected-style").html($("#style option:selected").text());
    $("#options-selected-style").html($("#style option:selected").text());
    $("#photos-selected-style").html($("#style option:selected").text());
    $("#summary-selected-style").html($("#style option:selected").text());

    // update the Select Style right-hand side data
    $("#style-transmission").html(data['transmission']);
    $("#style-engine").html(data['engine']);
    $("#style-mpg").html(data['mpg']);
    $("#style-drivetrain").html(data['drivetrain']);
    $("#style-body").html(data['body']);

    // update the summary tab data
    $("#summary-transmission").html(data['transmission']);
    $("#summary-engine").html(data['engine']);
    $("#summary-mpg").html(data['mpg']);
    $("#summary-drivetrain").html(data['drivetrain']);
    $("#summary-body").html(data['body']);


    $("#style-selected-drivetrain").html(data['drivetrain']);
    $("#style-selected-body").html(data['body']);
    $("#colors-selected-drivetrain").html(data['drivetrain']);
    $("#colors-selected-body").html(data['body']);
    $("#options-selected-drivetrain").html(data['drivetrain']);
    $("#options-selected-body").html(data['body']);
    $("#photos-selected-drivetrain").html(data['drivetrain']);
    $("#photos-selected-body").html(data['body']);
    $("#summary-selected-drivetrain").html(data['drivetrain']);
    $("#summary-selected-body").html(data['body']);

    updateColorData(data);

    // set all the left side text box options:
    setupLeftConfigData(data);

    if(data['summary'] != ''){
        $('#details-dialog').html('<div id="textWrap">' + data['summary'] + '</div>');
    }

    // Update summary
    $('#summary-wrapper td.trim').html('<span>' + data['name'] + ' Trim</span>');
    $('#summary-wrapper td.price').html(data['total_msrp']);

    // check to see if the user has saved this vehicle in their garage
    if(data['extra']){
        setGarageStatus(data['extra']['in_garage']);
    }


    // Update Quote link
    $('a.getQuote').attr('href', '/vehicles/build/quote/' + data['style'] + '/');
    $('a.emailConfiguration').attr('href', '/vehicles/ajax/emailconfig/' + data['style'] + '/');

    // build and populate the options table
    buildAndPopulateOptionsTable(data);


    updateOptionActions(data['style']);
    updateSummaryOptions();

    var id = $("#style").val();
}


function pause(numberMillis)
{
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}

function alertForUserInteraction(data)
{
    if (data['status'] == "UserConfirmationNeeded"){

        var content = '';
        content += "<p>To continue with the selected choice, the following ";

        var need_and = false
        if(data['removed_option'].length > 0){
            content += "selected options will be disabled:</p>";
            content += "<ul>";
            $.each(data['removed_option'], function(){
                content += '<li>' + getOptionText(this, data['options']) + '</li>';
            });
            content += '</ul>';
            need_and = true
        }

        if(data['added_option'].length > 0){

            if (need_and == true){
                content += " and the following";
            }

            content += ' options will be enabled:</p>';
            content += '<ul>';
            $.each(data['added_option'], function(){
                content += '<li>' + getOptionText(this, data['options']) + '</li>';
            });
            content += '</ul></p>';
        }
        $('#dialog').html(content);

        $('#dialog').dialog({
            bgiframe: true,
            width: 350,
            resizable: false,
            modal: true,
            overlay: {
                backgroundColor: '#000',
                opacity: 0.75
            },
            buttons: {
                'Cancel changes': function() {
                    var url = '/vehicles/json/toggle_option/' + data['style'] + '/option/' + data['originating_option'] + '/';
                    $.ajax({
                      url: url,
                      cache: false,
                      dataType: "json",
                      success: function(data) {
                          $('#' + data['originating_option']).attr('checked', true);
                          $('#' + data['originating_option']).addClass('active');
                    }});
                    var latest_data = [];
                    var removed_options = data['removed_option'];
                    pause(1200);
                    $.each(removed_options, function(i, item)
                    {
                        var url = '/vehicles/json/toggle_option/' + data['style'] + '/option/' + item + '/';
                        $.ajax({
                          url: url,
                          cache: false,
                          dataType: "json",
                          success: function(new_data) {
                              updateConfigData(new_data);
                              //alert(new_data['options_invoice']);
                            //if(i == (removed_options.length - 1)){
                            //    $("#" + item).attr('checked', 'checked');
                            //    $("#option-row-" + item).addClass('active');
                            //}
                        }});
                    });
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                    $(this).html('');


                },
                'OK': function() {
                    updateConfigData(data);
                    updateOptionData(data);
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                    $(this).html('');
                }
            }
        });

    } else if(data['status'] == "UserChoiceNeeded"){
        var content = '';
        content += '<p>The option you have selected requires additional choices.  Please select from the following:<br/>';
        $.each(data['resolving_options'], function(){
                if (document.getElementById(this) != null)
                    content += '<label><input name="conflictButton" type="radio" class="dialog-option-choice" value="' + this + '"/>' + document.getElementById(this).title + '</label><br/>';
                else
                    content += '<label><input name="conflictButton" type="radio" class="dialog-option-choice" value="' + this + '"/>Option ' + this + '</label><br/>';
        });
        content += '</p>';

        $('#dialog').html(content);
        $('input.dialog-option-choice:first').attr('checked', 'checked');

        $('#dialog').dialog({
                    bgiframe: true,
                    width: 350,
                    resizable: false,
                    modal: true,
                    overlay: {
                        backgroundColor: '#000',
                        opacity: 0.75
                    },
                    buttons: {
                        'Cancel': function() {
                            var url = '/vehicles/json/toggle_option/' + data['style'] + '/option/' + data['originating_option'] + '/';
                            //alert(data['originating_option']);
                            $.ajax({
                              url: url,
                              cache: false,
                              dataType: "json",
                              success: function(data) {
                                  $('#' + data['originating_option']).attr('checked', false);
                                  $('#' + data['originating_option']).addClass('active');
                            }});
                            var removed_options = data['removed_option'];
                            pause(1200);
                            updateConfigData(data);
                            $(this).dialog('close');
                            $(this).dialog('destroy');
                            $(this).html('');


                        },
                        'Continue': function() {

                            var choice = $('input.dialog-option-choice:checked').val();

                            var url = '/vehicles/json/toggle_option/' + data['style'] + '/option/' + choice + '/';
                            $.ajax({
                              url: url,
                              cache: false,
                              dataType: "json",
                              success: function(data) {
                                updateConfigData(data);
                                updateOptionData(data);
                            }});
                            $(this).dialog('close');
                            $(this).dialog('destroy');
                            $(this).html('');
                        }
                    }
                });
        $('#dialog').dialog('open');
    }
}

// changed from the "Select Style -> Select Trim select box option changing
function changeStyle(model, id)
{
    $('#style_id').val(id);
    // first get the stock image so it doesn't take forever for it to show on the page:
    var url = "/vehicles/json/get_stock_photo/" + model + '/' + id + '/';
    $.ajax({
      url: url,
      cache: false,
      dataType: "json",
      success: function(data) {
        var photo_url = data['stock_image'].replace("http://media.carbook.com/autoBuilderData", "http://media.save100bucks.com/img");
        $('#style-pic').attr('src', photo_url);
        $('#colors-pic').attr('src', photo_url);
        $('#options-pic').attr('src', photo_url);
        $('#photos-pic').attr('src', photo_url);
        $('#summary-pic').attr('src', photo_url);
    }});


    var url = "/vehicles/json/set_style/" + model + '/' + id + '/';
    $.ajax({
      url: url,
      cache: false,
      dataType: "json",
      success: function(data) {
        setupConfigData(data);
    }});
}

function updateOptionActions(style){
    $('input[name=option]').click(
        function(){
            var optid = $(this).val();
            var url = '/vehicles/json/toggle_option/' + style + '/option/' + optid + '/';
            $.ajax({
              url: url,
              cache: false,
              dataType: "json",
              success: function(data) {
                // if the data['status'] is set, alert the user appropriately.
                if (data['status'] == "UserConfirmationNeeded" || data['status'] == "UserChoiceNeeded")
                {
                    alertForUserInteraction(data);
                }
                else
                {
                    updateConfigData(data);
                    updateOptionData(data);
                }
            }});
        }
    );
    $('input[name=option-color]').click(
        function(){
            var optid = $(this).val();
            var url = '/vehicles/json/toggle_option/' + style + '/option/' + optid + '/';
            $.ajax({
              url: url,
              cache: false,
              dataType: "json",
              success: function(data) {
                // if the data['status'] is set, alert the user appropriately.
                if (data['status'] == "UserConfirmationNeeded" || data['status'] == "UserChoiceNeeded")
                {
                    alertForUserInteraction(data);
                }
                else
                {
                    updateConfigData(data);
                    updateOptionData(data);
                }
            }});
            updateSidebarIntColor($("#" + optid + "description").html());
        }
    );


}
