﻿$(document).ready(function() {
    $("#selMakes").bind("change", onChangeManufacturer);
    $("#selModels").bind("change", onChangeModel);
    $("#selVariants").bind("change", onChangeVariant);
    $("#btnWC_Close").bind("click", function() { WhatCarPanel.hide(); return false; });
    $("#btnWC_Open").bind("click", function() { onChangeVariant(); return false; });
    WhatCarPanel.hide();
    $(document).keyup(function(e) {
    if (e.keyCode == 27) { WhatCarPanel.hide(); }
    });
});

WhatCarPanel =
{
    show: function(variant) {
        $(document).showMask();
        var rep = $('#whatCarReport');
        rep.show();
        rep.formcenter();   
    },

    hide: function() {
        var rep = $('#whatCarReport');
        rep.hide();
        $(document).hideMask();
    }
}

// populate the models dropdown combo based on the currently selected manufacturer
function populateModels() {
    var sel = $("#selMakes");
    selMakeId = sel.find(":selected").val();

    $("#selModels option:not(:first)").remove();
    $("#selModels").children().text("-- No models available --");

    if (parseInt(selMakeId, 10) > 0) {
        showProcessing(true);
        SalesAndMarketingSite.Services.TaxCalculator.GetModels(selMakeId, onCompletedGetModels, onFailed);
    }

    $("#selModels").removeAttr("disabled");
}


// populate the variants dropdown combo based on the currently selected model
function populateVariants() {

    selMakeId = $("#selMakes").find(":selected").val();
    selModelId = $("#selModels").find(":selected").val();

    if (isNaN(parseInt(selModelId, 10)) || parseInt(selModelId, 10) == 0)
        selModelId = parseInt($("#selModels").attr("defaultVal"));

    $("#selVariants option:not(:first)").remove();
    $("#selVariants").children().text("-- No variants available --");

    if (parseInt(selMakeId, 10) > 0 && parseInt(selModelId, 10) > 0) {
        showProcessing(true);
        SalesAndMarketingSite.Services.TaxCalculator.GetVariants(parseInt(selMakeId, 10), parseInt(selModelId, 10), onCompletedGetVariants, onFailed);
    }

    $("#selVariants").removeAttr("disabled");
    
}

// show details of a particular variant
function getSelectedVariant() {

    selMakeId = $("#selMakes").find(":selected").val();
    selModelId = $("#selModels").find(":selected").val();
    selVariantId = $("#selVariants").find(":selected").val();

    if (!isNaN(parseInt(selMakeId, 10)) && !isNaN(parseInt(selModelId, 10)) && !isNaN(parseInt(selVariantId, 10))) {

        //        SalesAndMarketingSite.Services.TaxCalculator.GetVariantDetails(parseInt(selMakeId, 10), parseInt(selModelId, 10), parseInt(selVariantId, 10), onCompletedGetVariant, onFailedGetVariant);
        SalesAndMarketingSite.Services.WhatCarService.GetVariant(parseInt(selMakeId, 10), parseInt(selModelId, 10), parseInt(selVariantId, 10), onCompletedGetVariant, onFailedGetVariant);
    }
}




// load details of a line vehicle
function loadVehicleDetails(mkId, mdId, vrId, lineNo, isValid, isNew) {

    // proceed only if make Id is available
    if (!$("#selMakes option[value*='" + mkId + "']").length) {
        stopLoadingThisVehicle();
    }
    else {


        showProcessing(true);
        if (selLine != lineNo)
            clearCurrentVariant();

        isNewLine = Boolean(isNew);
//        isCalculated = true;
//        isEditted = false;
//        isValidLine = Boolean(isValid);
//        currentLineNo = lineNo;
//        currentPointId = Boolean(isNew) ? 1 : 3;

        $("#infoPanel").html("");

        LexAutolease.Services.Quote.GetQuoteLine(parseInt(lineNo, 10), onCompletedGetQuoteLine, onFailed, true);
    }
}



//function onClickTab(obj) {
//    var variantText = $("[id*=txtVariant]").val();
//    lastAccessedTab = obj.className;

//    $("#divPanels div.panel").not("." + obj.className).hide();
//    $(".tabs li a").not("." + obj.className).removeClass("selectedTab");

//    $("#divPanels div.panel").filter("." + obj.className).show();
//    $(".tabs li a").filter("." + obj.className).addClass("selectedTab");
//    lazyLoad(obj);
//}



var selLine = '-1';

///////////////////////////////////////////////////////
// EVENT HANDLERS: service callback
///////////////////////////////////////////////////////

function onCompletedGetModels(models) {

    //var selModels = $get("selModels");
    var selModels = $("#selModels");

    $("#selModels option:not(:first)").remove();
    //$("#selModels").children().text("-- Select model --");
    $("#selModels option:first").remove();

    for (i = 0; i < models.length; i++) {
        addOption(selModels, models[i].value, models[i].key);
    }

    // set default model value
    if (parseInt($("#selModels").attr("defaultVal")) > 0) {
        var defaultModelId = $("#selModels").attr("defaultVal");

        // proceed only if model Id is available
        if (!$("#selModels option[value*='" + defaultModelId + "']").length) {
            stopLoadingThisVehicle();
        }
        else {
            $("#selModels").val(defaultModelId);
            populateVariants();
        }
    }

    showProcessing(false);
}

function onCompletedGetVariants(results) {

    var selVariants = $("#selVariants");
    //var selVariants = $get("selVariants");
    $("#selVariants option:not(:first)").remove();
    //$("#selVariants").children().text("-- Select variant --");
    $("#selVariants option:first").remove();

    for (i = 0; i < results.length; i++) {
        addOption(selVariants, results[i].value, results[i].key);
    }

    // set default
    if (parseInt($("#selVariants").attr("defaultVal")) > 0) {


        // proceed only if make Id is available
        var defaultVariant = $("#selVariants").attr("defaultVal");
        if (!$("#selVariants option[value*='" + defaultVariant + "']").length) {
            stopLoadingThisVehicle();
        }
        else {

            $("#selVariants").val($("#selVariants").attr("defaultVal"));
            $("#selVariants").attr('defaultVal', 0);
            getSelectedVariant();
        }
    }

    showProcessing(false);
}


function onFailedGetVariant(a, b, c) {

    $("#imgCar").hide();

    var url = "/images/no-car-photo.gif";
    $("#imgCar").attr("src", url);
    $("#imgCar").show();
    $("#carPanel").show();

    $(".overlay").hide();
    //onFailed(a, b, c);

}



//function onCompletedGetVariant(variant) {
//    getReport(variant.CapCode);
//}



function onCompletedGetVariant(variant) {
  
    /*
    var url = $("#imgCar").attr("src");
    if (selLine != currentLineNo) {
        url = "/images/no-car-photo.gif";
        $("#imgCar").attr("src", url);
    }
    */

    if (variant) {
 
        if (variant.CapCode) {
            if (variant.CapCode != "" /* && selLine != currentLineNo */) {

                reportLoaded = false;
                WhatCarPanel.show(variant);
                getReport(variant.CapCode);

                /*
                url = String.format("__ImageGrabber.axd?capCode={0}&size=medium", escape(variant.CapCode));
                selectedCapCode = variant.CapCode;

                $("#imgCar").attr("src", url);
                $("#imgCar").show();
                */
            }
        }

        $('#hVariant').html(String.format('{0} {1}', variant.Manufacturer, variant.Description));
    }


    // default to what car tab
//    $("#divPanels div.panel").not(".showReport").hide();
//    $(".tabs li a").not(".showReport").removeClass("selectedTab");
//    $("#divPanels div.panel").filter(".showReport").show();
//    $(".tabs li a").filter(".showReport").addClass("selectedTab");

    showProcessing(false);
  
}





///////////////////////////////////////////////////////
// EVENT HANDLERS: dropdown boxes
///////////////////////////////////////////////////////

function onChangeManufacturer() {
    clearDropdownDefaults();
    populateModels();
    $('#selVariants').empty().append('<option>-- N/A --</option>');
    $('#selVariants').attr("disabled", "disabled");
}

function onChangeModel() {
    clearDropdownDefaults();
    populateVariants();
}

function onChangeVariant() {
    clearDropdownDefaults();
    getSelectedVariant();
}


function getReport(capCode) {
    if (!reportLoaded) {

        // hide the report division
        $('#divRep').hide();

        // show the please wait animation
        //var divWait = $get('divWCWait');
        var divWait = $('#divWCWait');
        showWaiting(divWait);

        SalesAndMarketingSite.Services.WhatCarService.GetFullWhatCarReview(capCode, onCompletedGetFullWhatCarReview, onFailed);
    }
}

function onCompletedGetFullWhatCarReview(report) {
    //hide($get('divWCWait'));
    hide($('#divWCWait'));

    if (!report) {
        $('#pNoReview').html('WhatCar review not available for this vehicle.');
        $('#pNoReview').show();
    }
    else {
        $('#pNoReview').hide();

        $('#h3Overall').html(String.format("<img src='/images/page_headings/whatcar_overallrating.gif' alt='Overall rating' /> <img src='/images/wc_small_{0}.gif' style='margin-bottom:5px;'>", report.OverallBlob));
        $('#pFor').html(report.VerdictFor);
        $('#pAgainst').html(report.VerdictAgainst);

        $('#h3Performance').html(String.format("<img src='/images/wc_small_{0}.gif' alt=\"{1}\">", (report.PerformanceBlob == null ? "0" : report.PerformanceBlob), report.PerformanceTitle));
        $('#pPerformance').html(report.PerformanceCopy);

        $('#h3Handling').html(String.format("<img src='/images/wc_small_{0}.gif' alt=\"{1}\">", (report.HandlingBlob == null ? "0" : report.HandlingBlob), report.HandlingTitle));
        $('#pHandling').html(report.HandlingCopy);

        $('#h3Refinement').html(String.format("<img src='/images/wc_small_{0}.gif' alt=\"{1}\">", (report.RefinementBlob == null ? "0" : report.RefinementBlob), report.RefinementTitle));
        $('#pRefinement').html(report.RefinementCopy);

        $('#h3Buying').html(String.format("<img src='/images/wc_small_{0}.gif' alt=\"{1}\">", (report.BuyingBlob == null ? "0" : report.BuyingBlob), report.BuyingTitle));
        $('#pBuying').html(report.BuyingCopy);

        $('#h3Quality').html(String.format("<img src='/images/wc_small_{0}.gif' alt=\"{1}\">", (report.QualityBlob == null ? "0" : report.QualityBlob), report.QualityTitle));
        $('#pQuality').html(report.QualityCopy);

        $('#h3Safety').html(String.format("<img src='/images/wc_small_{0}.gif' alt=\"{1}\">", (report.SafetySecurityBlob == null ? "0" : report.SafetySecurityBlob), report.SafetySecurityTitle));
        $('#pSafety').html(report.SafetySecurityCopy);

        $('#h3BehindWheel').html(String.format("<img src='/images/wc_small_{0}.gif' alt=\"{1}\">", (report.BehindTheWheelBlob == null ? "0" : report.BehindTheWheelBlob), report.BehindTheWheelTitle));
        $('#pBehindWheel').html(report.BehindTheWheelCopy);

        $('#h3Space').html(String.format("<img src='/images/wc_small_{0}.gif' alt=\"{1}\">", (report.SpaceAndPracticalityBlob == null ? "0" : report.SpaceAndPracticalityBlob), report.SpaceAndPracticalityTitle));
        $('#pSpace').html(report.SpaceAndPracticalityCopy);

        $('#h3Equipment').html(String.format("<img src='/images/wc_small_{0}.gif' alt=\"{1}\">", (report.EquipmentBlob == null ? "0" : report.EquipmentBlob), report.EquipmentTitle));
        $('#pEquipment').html(report.EquipmentCopy);

        var divImages = $('#divImages');
        var divLarge = $('#divImgLarge img');
        var buff = new StringBuffer();

        if (report.PhotoGallery.length > 0) {

            for (i = 0; i < report.PhotoGallery.length; i++) {
                if (i == 0)
                    divLarge.attr("src", report.PhotoGallery[i].Url);

                buff.append(String.format("<a href=\"javascript:showLargeGalleryItem('{0}')\"><img width='87px' src='{1}'></a>", report.PhotoGallery[i].Url, report.PhotoGallery[i].Url));
            }

            divImages.html(buff.toString());
            
            $('#divImgLarge').show();
            divImages.show();
            $('#divImgDisclaimer').show();
            
        } else {
            $('#divImgLarge').hide();
            divImages.hide();
            $('#divImgDisclaimer').hide();
        }

        $('#divRep').show();
        $('#divRep1').show();
        $('#divRep2').show();
        $('#divRep3').show();
        
        $("#whatCarReport").focus();
        
    }

    reportLoaded = true;

}


///////////////////////////////////////////////////////////////
// general functions
///////////////////////////////////////////////////////////////

// notify
function stopLoadingThisVehicle() {

    // clear the screen
    onClickSelectNewCar();

    alert("This particular vehicle cannot be viewed on the web. Please contact your Customer Service Representative.");
}


// clears the default values set into the dropdowns by the user clicking on a vehicle line
function clearDropdownDefaults() {

    $("#selMakes").attr("defaultVal", 0);
    $("#selModels").attr("defaultVal", 0);
    isCalculated = false;
}

function showLargeGalleryItem(img) {
    var imgLarge = $('#imgLarge');
    imgLarge.hide();
    imgLarge.attr("src", img);

    $('#imgLarge').fadeIn("normal");
}

function closeLargeImage() {
    $('#divImgLarge').fadeOut(100);
}

// clears the current vehicle [or variant] details off the page
function clearCurrentVariant() {

    $("#pRentalDisplay").html('');

    var url = "/images/no-car-photo.gif";
    $("#imgCar").attr("src", url);

    $('#lblCO2').html('');
    $('#hLineNo').html('');
    $('#hVariant').html('');
    $('#lblInsGrp').html('');
    $('#lblCO2Band').html('');
    $('#lblCombined').html('');
    $('#lblTrans').html('');
    $('#lblFuelType').html('');
    $('#lblBodyStyle').html('');
    $('#lblBIKLowerRate').html('');
    $('#lblBIKLowerRate').html('');
    $('#lblTaxableListPrice').html('');

//    $("#liShowExtras").hide();
//    $("#liShowFinancials").hide();

    $("div.showStrOptions span").html('');
    $("div.showExtras span").html('');
    $("div.showVehDet span").html('');
}

function showProcessing(isProcessing) {

    //var divWait = $get('divWait');
    var divWait = $('#divWait');
    if (isProcessing)
        showWaiting(divWait);
    else
        hide(divWait);
}
