﻿function SaveGA(element) {
    if (element == null)
        return;
    if (element.length == undefined)
        element = $(element);
    if (element.length <= 0)
        return;

    var trueRegex = new RegExp('^true$', 'i');
    if (trueRegex.test($('div.useGA').text()) == true) {
        var quoteSaved = false;
        var contactDealer = false;
        var prefix = '/pageview/buildAndPrice/';
        var pageName;
        var id = element.attr('id');
        
        if (id == 'findDealer' || id == 'save_quote' || id == 'contactArea_submit')
            prefix = '/pageview/submittodealer/';
        if (id == 'findDealer')
            pageName = 'findDealer';
        else if (id == 'save_quote')
            pageName = 'dealerSelected';
        else if (id == 'contactArea_submit') {
            pageName = 'contactFormSubmitted';
            contactDealer = true;
        }
        
        if (id == 'save_quote_link') {
            pageName = 'saveMyQuote';
            if (trueRegex.test($('div #hiddenLoggedIn').text()) == true)
                quoteSaved = true;
        }
        else if (id == 'login_save_button') {
            pageName = 'saveSessionQuote';
            quoteSaved = true;
        }
        else if (id == 'login_submit') {
            pageName = 'login';
            quoteSaved = true;
        }
        else if (id == 'login_create_button')
            pageName = 'createAccount';
        else if (id == 'create_submit_button') {
            pageName = 'accountCreated';
            quoteSaved = true;
        }
        
        _gaq.push(['_trackPageview', prefix + pageName]);
        if (quoteSaved)
            _gaq.push(['_trackPageview', prefix + 'quoteSaved']);
        if (contactDealer)
            _gaq.push(['_trackPageview', prefix + 'quoteSentToDealer']);
    }
}
function PreselectPayment()
{
    var deposit = parseInt($('#hiddenDeposit').text());
    if (deposit > 0)
        $('#downpayment').val(deposit);
    var type = $('#hiddenSelectPurchaseTerm').text();
    if (type != '') {
        if (type.match(/Cash/i))
        {
            $('#input_lease_finance').removeAttr("checked");
            $('#input_cash').attr("checked", "checked");
            $('#input_cash').click();
        }
        else
        {
            $('#input_lease_finance').attr("checked", "checked");
            $('#input_cash').removeAttr("checked");
            $('#input_lease_finance').click();
        }
    }
    else if ($('#input_cash').attr("checked"))
        $('#input_cash').click();
}
function IsValidDigit(event) {
    if (event == null)
        return false;
    var code = (event.keyCode ? event.keyCode : event.which);
    if (code > 47 && code < 58)
        return true;
    
    return false;
}
function IsFrench() {
    return $("#" + $('#pricingPrefix').val() + "_" + "hiddenLanguage").text() == "fr-ca";
}
function UpdateAnotherQuote() {
    var prefix = '#' + $('#pricingPrefix').val() + "_";
    
    var url = $('#hiddenAnotherQuote').text();
    
    var range = $(prefix + 'hiddenPreSelRange').text();
    if (range == '') {
        url = url.replace(/\&[amp\;]*Range=[^&]*/i, '');
    }                                                        
    else {
        if (url.match(/\&[amp\;]*Range=/i))
            url = url.replace(/(\&[amp\;]*Range=)[^&]*/i, '$1' + range);
        else
            url += '&Range=' + range;
    }
    
    var year = $(prefix + 'hiddenPreSelYear').text();
    if (year == '') {
        url = url.replace(/\&[amp\;]*ModelYear=[^&]*/i, '');
    }                                                        
    else {
        if (url.match(/\&[amp\;]*ModelYear=/i))
            url = url.replace(/(\&[amp\;]*ModelYear=)[^&]*/i, '$1' + year);
        else
            url += '&ModelYear=' + year;
    }

    var colourID = $(prefix + 'hiddenPreSelColourID').text();
    if (colourID == '') {
        url = url.replace(/\&[amp\;]*Colou*rID=\d+/i, '');
    }
    else {
        if (url.match(/\&[amp\;]*Colou*rID=/i))
            url = url.replace(/(\&[amp\;]*Colou*rID=)[^&]*/i, '$1' + colourID);
        else
            url += '&ColourID=' + colourID;
    }
            
    var carID = $("#hiddenSelectedCarID").text();
    if (carID == '')
    {
        url = url.replace(/\&[amp\;]*CarID=[^&]*/i, '');
        url = url.replace(/\&[amp\;]*Colou*rID=[^&]*/i, '');        
    }
    else {
        if (url.match(/\&[amp\;]*CarID=/i))
            url = url.replace(/(\&[amp\;]*CarID=)[^&]*/i, '$1' + carID);
        else
            url += '&CarID=' + carID;
    }

    $('#hiddenAnotherQuote').text(url);
}

$(document).ready(function() {
    var map = null;
    var xmlDom = null;
    var colon = null;
    var markers = null;
    var dealer = null;
    var index = null;
    var rawdata = null;
    var languageCode = null;
    var timerID = null;
    var subaruModelsXML = null;
    var modelXML = "";
    var accXML = "";
    var paymentXML = "";
    var prefix = document.getElementById('pricingPrefix').value + "_";
    var trackedTransmission = false;
    var trackedColour = false;
    var trackedAccessory = false;
    var trackedPayment = false;

    getModels();

    GetMap();

    //On Click Events

    $("#dropdownProvince").click(function() {
        $(".dropdown_select").not("#selectionProvince").hide();
        if ($("#selectionProvince").is(":visible")) {
            $("#selectionProvince").hide();
        }
        else {
            $("#selectionProvince").show();
        }
    });

    $("#dropdownModel").click(function() {
        $(".dropdown_select").not("#selectionModel").hide();
        if ($("#selectionModel").is(":visible") || $('#dropdownModelTitle').is('.dropdown_title_disabled')) {
            $("#selectionModel").hide();
        }
        else {
            $("#selectionModel").show();
        }
    });

    $("#dropdownYear").click(function() {
        $(".dropdown_select").not("#selectionYear").hide();
        if ($("#selectionYear").is(":visible") || $('#dropdownYearTitle').is('.dropdown_title_disabled')) {
            $("#selectionYear").hide();
        }
        else {
            $("#selectionYear").show();
        }
    });

    $("#dropdownTrim").click(function() {
        $(".dropdown_select").not("#selectionTrim").hide();
        if ($("#selectionTrim").height() < $("#trim_popout").height()) {
            $("#selectionTrim").height($("#trim_popout").height())
        }
        else {
            $("#trim_popout").height($("#selectionTrim").height())
        }
        if ($("#selectionTrim").is(":visible") || $('#dropdownTrimTitle').is('.dropdown_title_disabled')) {
            $("#selectionTrim").hide();
        }
        else {
            $("#selectionTrim").show();
        }
    });

    $("#dropdownTransmission").click(function() {
        if (!$("#dropdownTransmissionTitle").hasClass("dropdown_title_disabled")) {
            $(".dropdown_select").not("#selectionTransmission").hide();
            if ($("#selectionTransmission").is(":visible") || $('#dropdownTransmissionTitle').is('.dropdown_title_disabled')) {
                $("#selectionTransmission").hide();
            }
            else {
                $("#selectionTransmission").show();
            }
        }
    });

    $("#dropdownColour").click(function() {
        if (!$("#dropdownColourTitle").hasClass("dropdown_title_disabled")) {
            $(".dropdown_select").not("#selectionColour").hide();
            $("#hiddenColourSelected").text("N");
            if ($("#selectionColour").is(":visible") || $('#dropdownColourTitle').is('.dropdown_title_disabled')) {
                $("#selectionColour").hide();
            }
            else {
                $("#selectionColour").show();
            }
        }
    });

    $(".dropdown_selection").hover(function() {
        if ($(this).find('.dropdown_title').is('.dropdown_title_disabled'))
            return;
        
        //change Arrow background
        $(this).find(".dropdown_Arrow").css("background-image", "url('/content/7907/media/General/Pricing/ddlArrowOn.gif')");
        $(this).find(".dropdown_ArrowBorder").css("border", "solid 1px #336699");                 
    },
            function() {
        if ($(this).find('.dropdown_title').is('.dropdown_title_disabled'))
            return;
        
                $(this).find(".dropdown_Arrow").css("background-image", "url('/content/7907/media/General/Pricing/ddlArrowOff.gif')");
                /*
                $(this).find(".dropdown_ArrowBorder").css("border-top", "solid 1px #9999CC")
                .css("border-bottom", "solid 1px #CCFFFF")
                .css("border-right", "solid 1px #CCCCFF")
                .css("border-left", "none");
                */
            });

    $("#input_cash").click(function() {
        if ($(this).attr("checked")) {
            //Update Quote Name
            var quote_translate = $(subaruModelsXML).find("#quote").text();
            var quoteCount = parseInt($("#" + prefix + "hiddenQuoteCount").text()) + 1;
            $("#quote_name").attr("value", quote_translate + " " + quoteCount.toString());

            if (!trackedPayment)
                TrackPageView('/virtualpv/buildprice/select/payment');
            trackedPayment = true;
            if ($('div#hiddenSelectedPurchaseType').text() != 'C')
                TrackEvent('Payment', 'Cash', 'Cash', 1);
            
            
            $("#dealerSearchForm").show();
            $("#hiddenSelectedPurchaseType").text("C");
            $('#hiddenSelectedPurchaseIndex').text("0");
            $("#Lease_Finance").hide();
            $("#Finance_payment").hide();
            $("#Lease_payment").hide();
            $("#purchasing_details").show();
            $("#Cash_payment").show();
            loadPurchaseDetails("Cash");
            
            resizeCol();
        }
    });

    $("#input_lease_finance").click(function() {
        if ($(this).attr("checked")) {
            $("#Lease_Finance").show();
            $("#Finance_payment").hide();
            $("#Lease_payment").hide();
            $("#purchasing_details").hide();
            $("#Cash_payment").hide();

            //Show Selected
            if ($("#hiddenSelectPurchaseTerm").text() != "") {
                var purchaseType = $("#hiddenSelectPurchaseTerm").text().split("_");
                $("#purchasing_details").show();
                $("#" + purchaseType[0] + "_payment").show();
                
                var type = purchaseType[0].substring(0,1).toUpperCase();
                var existingIndex = $('div#hiddenSelectedPurchaseIndex').text();
                var existingType = $('div#hiddenSelectedPurchaseType').text();

                // Ignore, already set
                if (existingIndex == purchaseType[2] &&
                    existingType == type)
                    return;
                
                $('div#hiddenSelectedPurchaseType').text(type);
                $('div#hiddenSelectedPurchaseIndex').text(purchaseType[2]);
                TrackEvent('Payment', purchaseType[0], purchaseType[1] + 'mos', 1);
            }
            
            resizeCol();
        }
    });

    $("#downpayment").keypress(function(event) {
        var code = (event.keyCode ? event.keyCode : event.which);
        if (code == 13) {
            checkDeposit();
            //reload pricing
            getFinanceDetails($("#hiddenSelectedCarID").text());
        }
        else {
            if (IsValidDigit(event) == false) {
//                alert("invalid digit");
                if (code > 57 && (code < 112 || code > 123))
                    event.preventDefault();
            }
        }
    });
    $("#downpayment").change(function(event) {
            checkDeposit();
            //reload pricing
            getFinanceDetails($("#hiddenSelectedCarID").text());
    });

    $("#downpayment_update").click(function() {
        checkDeposit();
        //reload pricing
        getFinanceDetails($("#hiddenSelectedCarID").text());
    });

    function checkDeposit() {
        //check that deposit is valid
        //Cannot be more that 70% of msrp
        if ($("#downpayment").attr("value") != "") {
            var msrp = parseInt($("#hiddenVehiclePrice").text());
            var depositMax = (msrp * 70) / 100;
            var depositNew = parseInt($("#downpayment").attr("value"));
            if (depositNew < depositMax) {
                $("#hiddenDeposit").text($("#downpayment").attr("value"));
            }
            else {
                //find translation
                alert($(subaruModelsXML).find("#deposit_too_high").text());
                $("#downpayment").attr("value", $("#hiddenDeposit").text());
            }
        }
    }

    $("#dealer_locator_section").click(function() {
        if ($("#locatorDiv").is(':visible')) {
            displayDealerLocator("hide", false);
        }
        else {
            displayDealerLocator("show", false);
        }
        resizeCol();
    });

    $("#mapControlContainer").mouseover(function() {
        RollOverControls();
    });

    $("#mapControlContainer").mouseout(function() {
        RollOutControls();
    });

    $("#" + prefix + "dealer_search_input").focus(function() {
        this.select();
    });


    $("#" + prefix + "dealer_search_input").keypress(function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            TrackPageView('/virtualpv/buildprice/dealerlocate');
            getDealerLocation();
            return false;
        }
    });

    $("div #findDealer").click(function() {
        TrackPageView('/virtualpv/buildprice/dealerlocate');
        SaveGA($(this));
        getDealerLocation();
        //Wait until lat and lng are loaded..
        //timerID = setInterval(SetupIE, 1333);
    });
    
    $('a#dealerLink').click(function() {
        TrackEvent('Outlink', 'Dealer', $('div#dealerHeader').text(), 3);
    });

    function getDealerLocation() {
        if ($("#" + prefix + "dealer_search_input").attr("value") != "") {
            displayDealerLocator("show", true);

            if ($("#" + prefix + "dealer_search_input").val() == $("#" + prefix + "initialDealerInput").val())
                return;
                
            //getUserLocation();
            LoadInitialDealer();
        }
        else {
            alert($(subaruModelsXML).find("#dealer_search_input").text());
        }
    }

    $("div #save_quote").click(function() {
        //display contact form
        SaveGA($(this));
        TrackPageView('/virtualpv/buildprice/quote/contactform');
        
        if (IsFrench())
            $('#contact_time_title').addClass('pricingContactTitleFR');
        $('.PricingQMDiv').show();
        $("#contactArea").show();
        //Select Province
        $("#" + prefix + "contact_province").val($("#" + prefix + "hiddenPriceProvince").attr("value"));
    });

    $("#contact_close").click(function() {
        $("#contactArea").hide();
        $('.PricingQMDiv').hide();
    });

    $("#thank_you_another").click(function() {
//        ResetTrims();
        var url = $('#hiddenAnotherQuote').text();
        var accIDs = returnSelectedAccessoryIDs();
        if (accIDs != '')
            url += '&accessoryID=' + accIDs;

        url += '&financeCategory=' + $('#hiddenSelectedPurchaseType').text() +
                '&paymentIndex=' + $('#hiddenSelectedPurchaseIndex').text() +
                '&deposit=' + $("#hiddenDeposit").text();
        if (url.match(/ColourID/i))
            url = url.replace(/ColourID=\d+/i, 'ColourID=' + $("#" + prefix + "hiddenPreSelColourID").text());
        else
            url += '&ColourID=' + $("#" + prefix + "hiddenPreSelColourID").text();
        url += '&provinceCode=' + $('#' + prefix + 'hiddenPriceProvince').val();
        
        window.location = url;
    });

    $("#thank_you_model").click(function() {
//        ResetModel();
        var url = $('#hiddenAnotherModel').text();
        window.location = url;
    });

    function ResetTrims() {
        ResetQuotes();
        $("#steps_title").text($("#dropdownModelTitle").text());
        //Update Trim Title
        $("#dropdownTrimTitle").text($(subaruModelsXML).find("#dropdownTrimTitle").text());
        $('#' + prefix + 'hiddenPreSelRange').text($('#dropdownModelTitle').text());
        //Display Thumbnails
        $("#VehicleThumbnails").show();
    }

    function ResetTrim() {
        ResetQuotes();
        $('#' + prefix + 'hiddenPreSelRange').text($('#dropdownModelTitle').text());
        $('#' + prefix + 'hiddenPreSelYear').text($('#dropdownYearTitle').text());
        //Update MSRP to 0 allow the UpdateTransmission to set MSRP
        var msrpFmt = formatCurrency("0", $("#" + prefix + "hiddenLanguage").text());
        $("#price_view_total").text(msrpFmt);
        $("#price_view_price").text(msrpFmt);
        //Show Colour
        $("#colours").show();
        $("#price_view").hide();
        $("#colour_view").show();
    }

    function ResetModel(ignoreShowingSteps) {
        ResetQuotes();
        //clear Trim
        clearDropdown("Trim");
        disableDropdown("Trim");
        //Clear Year
        clearDropdown("Year");
        disableDropdown("Year");
        //Clear Model Title
        $("#dropdownModelTitle").text($(subaruModelsXML).find("#dropdownModelTitle").text());
        //Show steps
        $("#steps_title").text($(subaruModelsXML).find("#steps_title").text());
        $('#' + prefix + 'hiddenPreSelRange').text('');
        if (ignoreShowingSteps == undefined)
        $("#steps_text").show();
    }

    function ResetQuotes() {
        $("#thank_you_form").hide();
        $("#Pricing_access").hide();
        $("#dealerSearchForm").hide();
        $("#Payments").hide();
        $("#view_spec_insurance").hide();
        displayDealerLocator("hide", true);
        $("#colours").hide();
        //Clear Transmission
        clearDropdown("Transmission");
        disableDropdown("Transmission");
        //Clear Colour
        clearDropdown("Colour");
        disableDropdown("Colour");
        //clear Hidden Fields
        resetPricing();
        $("#hiddenSelectedColourIndex").text("");
        $("#hiddenSelectedPurchaseType").text("");
        $("#hiddenSelectedPurchaseIndex").text("");
        $("#hiddenSelectedCarID").text("");
        $("#hiddenAccTotal").text("0.00");
        $("#hiddenSelectPurchaseTerm").text("");
        $("#hiddenColourSelected").text("N");
        $("#interior_swatch1").hide();
        $("#interior_swatch2").hide();
        $("#pricing_select_accessories").empty();
        $("#Accessories_Detail").hide();
        $("#purchasing_details").hide();
        $('#hiddenDeposit').text('');
        $('#hiddenAccessoryIDs').text('');
        
        $('#CcalcDiscountTitle').hide();
        $('#CcalcDiscountValue').hide();
        //Clear Accessories

        $("#pricing_select_accessories").empty();
        $("#pricing_accessory_total").text(formatCurrency("0", $("#" + prefix + "hiddenLanguage").text()));
        $("#price_view_acc").text(formatCurrency("0", $("#" + prefix + "hiddenLanguage").text()));
        $("#accessory_total_price").text($("#accessories_vehicle_price").text());
        $("#price_view_total").text($("#accessories_vehicle_price").text());
        $("#Accessories_Detail").hide();
    }
/*
    $("#thank_you_close").click(function() {
        $("#thank_you_form").hide();
    });
*/
    $("#create_close").click(function() {
        $("#signupArea").hide();
        $('.PricingQMDiv').hide();
    });

    $("#login_close").click(function() {
        $("#loginArea").hide();
        $('.PricingQMDiv').hide();
    });

    $("div#login_create_button").click(function() {
            SaveGA($(this));
        
        TrackPageView('/virtualpv/account/create');
        
        $("div#loginArea").hide();
        $("div#signupArea").show();
        $("select#" + prefix + "create_province").val($("#" + prefix + "hiddenPriceProvince").attr("value"));
    });

    $('input#login_password').keypress(function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            e.preventDefault();
            CheckMyQuoteLogIn();
        }
    });
    
    $("#login_submit").click(function() {
        //Check login details..
        CheckMyQuoteLogIn();
    });

    $("#login_forgotten").click(function() {
            if (!validateEmail('login_email')) {
                alert($(subaruModelsXML).find("#contact_email_error").text());
                return;
            }
        //Check login details..
        ForgottenMyQuoteLogIn();
    });

    $("#quote_name").keypress(function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            displayDealerLocator("hide", false);
            $("#dealer_locator_content").show();
            $("#loginArea").show();
            resizeCol();
            return false;
        }
    });

    $("div #save_quote_link").click(function() {
//        displayDealerLocator("hide", false);
//        $("#dealer_locator_content").show();
            SaveGA($(this));
            if ($('div #hiddenLoggedIn').text() == 'True') {
                TrackPageView('/virtualpv/login/quote/save');
                LoggedInSaveQuote();
            }
            else {
                $('div.PricingQMDiv').show();
                $("div #loginArea").show();
            }
        resizeCol();
    });

    $("div #login_save_button").click(function() {
        //Allow user to save Session Quotes
        var accIDs = returnSelectedAccessoryIDs();

        var queryString = "SaveSession=Y" +
                "&LanguageCode=" + $("#" + prefix + "hiddenLanguage").text() +
                "&ProvinceCode=" + $("#" + prefix + "hiddenPriceProvince").attr("value") +
                "&WebSiteID=" + getWebSiteID() +
                "&QuoteName=" + $("#quote_name").attr("value") +
                "&carID=" + $("#hiddenSelectedCarID").text() +
                "&ownerID=" + $("#dealerID").attr("value") +
                "&colourIndex=" + $("#hiddenSelectedColourIndex").text() +
                "&accessoryID=" + accIDs +
                "&financeCategory=" + $("#hiddenSelectedPurchaseType").text() +
                "&paymentIndex=" + $("#hiddenSelectedPurchaseIndex").text() +
                "&deposit=" + $("#hiddenDeposit").text() +
                "&webPageID=" + getWebPageID();

        //$.post("PricingConfig/SaveContact.aspx", queryString);
        $.ajax({
            type: 'POST',
            url: "PricingConfig/MyQuote.aspx",
            data: queryString,
            dataType: "xml",
            success: saveSessionQuote
        });

        TrackPageView('/virtualpv/buildprice/quote/save');
    });

    function saveSessionQuote(xml) {
        if ($(xml).find("message").text() != "") {
            alert($(xml).find("message").text());
        }
        else {
            SaveGA($('div #login_save_button'));
            
            //Add one to QuoteCount
            var QuoteCount = parseInt($("#" + prefix + "hiddenQuoteCount").text()) + 1;
            $("#" + prefix + "hiddenQuoteCount").text(QuoteCount.toString());
            //Display Thank you page with Thank you for saving your Quote
            $("#loginArea").hide();
            $('.PricingQMDiv').show();
            $("#thank_you_submit").text($(subaruModelsXML).find("#save_quote_thanks").text());
            $('div#thank_you_text').hide();
            //$('#thank_you_text').text($(subaruModelsXML).find('#thank_you_text').text().replace('<model>', $('#dropdownModelTitle').text()));
            if (IsFrench()) {            
                $('#thank_you_another').addClass('find_dlr_button_fr');
                $('#thank_you_model').addClass('find_dlr_button_fr');
            }
            $("#thank_you_form").show();
        }

    }

    $("#view_specs_link").click(function() {
        //Open new window with specs
        //find specLink
        var webSiteID = getWebSiteID();
        $(modelXML).find("trim").each(function() {
            if ($(this).attr("carID") == $("#hiddenCarID").text()) {
                var specWebPageID = $(this).find("specLink").text();
                var specLink = "SubaruData.aspx?WebPageID=" + specWebPageID + "&WebSiteID=" + webSiteID + "&CompareType=S&CarIds=" + $("#hiddenCarID").text() + "&Category=AllSpecCategory" +
                            '&Range=' + $("#" + prefix + "hiddenPreSelRange").text() +
                            '&ModelYear=' + $("#" + prefix + "hiddenPreSelYear").text();
                window.open("http://" + location.host + "/" + specLink, "Specifications");
            }
        });
    });

    $("#insurance_quote_link").click(function() {
        //open new window to insurance link
        var insuranceLink = "http://www.smartcoverage.ca/homepage_" + $("#" + prefix + "hiddenLanguage").text().substr(0, 2);

        if ($("#" + prefix + "hiddenPriceProvince").attr("value") == "AB" && $("#" + prefix + "hiddenLanguage").attr("value") == "fr-ca") {
            insuranceLink += "2";
        }
        insuranceLink += ".aspx?p=";
        insuranceLink += getProvinceNameString();
        insuranceLink += "&s=subaru";
        //alert(insuranceLink);
        window.open(insuranceLink, "InsuranceQuote");
    });

    $("#prevDealer").click(function() {
        PrevDealer();
    });

    $("#nextDealer").click(function() {
        NextDealer();
    });

    $("#summary_link").click(function() {
        $.ajax({
            type: "POST",
            url: $('div #hostURL').text() + "/PricingConfig/StorePrintSummary.aspx?carID=" + $("#hiddenSelectedCarID").text() + 
            '&WebSiteID=' + getWebSiteID() + 
            '&ColourID=' + $("#" + prefix + "hiddenPreSelColourID").text(),
            dataType: "xml"
        });
        
        TrackPageView('/virtualpv/buildprice/quote/summary');
        
        var summaryLink = "SubaruData.aspx?WebPageID=" + getWebPageID() +
            "&WebSiteID=" + getWebSiteID() +
            "&ProvinceCode=" + $("#" + prefix + "hiddenPriceProvince").attr("value") +
            "&CarID=" + $("#hiddenSelectedCarID").text() +
            "&ColourID=" + $("#" + prefix + "hiddenPreSelColourID").text() +
            "&Deposit=" + $("#hiddenDeposit").text() +
            "&FinanceCategory=" + $("#hiddenSelectedPurchaseType").text() +
            "&PaymentIndex=" + $("#hiddenSelectedPurchaseIndex").text() +
            "&AccSelect=" + returnSelectedAccessoryIDs() +
            '&Range=' + $("#" + prefix + "hiddenPreSelRange").text() +
            '&ModelYear=' + $("#" + prefix + "hiddenPreSelYear").text();
        window.open("http://" + location.host + "/" + summaryLink, "summary");
    });

    $("#create_submit_button").click(function() {
        //Validate form
        var errField = "";
        var validEmail = true;
        if ($("#create_email").attr("value") == "") {
            errField = $(subaruModelsXML).find("#create_email_title").text().replace(":", "") + "\r\n";
        }
        else {
            validEmail = validateEmail("create_email");
            if (!validEmail) {
                alert($(subaruModelsXML).find("#contact_email_error").text());
                return;
            }
        }
        if ($("#create_password").attr("value") == "") {
            errField += $(subaruModelsXML).find("#create_password_title").text().replace(":", "") + "\r\n";
        }
        if ($("#create_reenter").attr("value") == "") {
            errField += $(subaruModelsXML).find("#create_reenter_title").text().replace(":", "") + "\r\n";
        }
        if (errField != "") {
            alert($(subaruModelsXML).find("#signin_form_error").text() + ":\r\n" + errField);
        }
        if ($("#create_password").attr("value") != "" && $("#create_reenter").attr("value") != "") {
            if ($("#create_password").attr("value").toLowerCase() != $("#create_reenter").attr("value").toLowerCase()) {
                alert($(subaruModelsXML).find("#signin_form_password").text());
                validEmail = false;
            }
        }
        if (errField == "" && validEmail) {
            //Save Form
            var queryString = "Register=Y" +
                "&LanguageCode=" + $("#" + prefix + "hiddenLanguage").text() +
                "&WebSiteID=" + getWebSiteID() +
                "&QuoteName=" + $("#quote_name").attr("value") +
                "&Username=" + $("#create_email").attr("value") +
                "&Password=" + $("#create_password").attr("value") +
                "&Repassword=" + $("#create_reenter").attr("value") +
                "&Name=" + $("#create_name").attr("value") +
                "&Company=" + $("#create_company").attr("value") +
                "&Address=" + $("#create_address").attr("value") +
                "&City=" + $("#create_city").attr("value") +
                "&ProvinceCode=" + $("#" + prefix + "create_province").val() +
                "&PostalCode=" + $("#create_postal").attr("value") +
                "&Phone=" + $("#create_phone").attr("value") +
                "&emailContact=" + $('#contactCheckbox').val() +
                "&phoneType=" + $("#create_select_contact").val();
            if ($("#create_contact_email").attr("Checked")) {
                queryString += "&ContactBy=email";
            }
            else {
                queryString += "&ContactBy=phone";
            }
            if ($("#create_contact_day").attr("checked")) {
                queryString += "&ContactTime=Day";
            }
            if ($("#create_contact_evening").attr("checked")) {
                queryString += "&ContactTime=Evening";
            }
            if ($("#create_contact_anytime").attr("checked")) {
                queryString += "&ContactTime=Anytime";
            }

            var accIDs = returnSelectedAccessoryIDs();

            queryString += "&carID=" + $("#hiddenSelectedCarID").text() +
                            "&ownerID=" + $("#dealerID").attr("value") +
                            "&colourIndex=" + $("#hiddenSelectedColourIndex").text() +
                            "&accessoryID=" + accIDs +
                            "&financeCategory=" + $("#hiddenSelectedPurchaseType").text() +
                            "&paymentIndex=" + $("#hiddenSelectedPurchaseIndex").text() +
                            "&deposit=" + $("#hiddenDeposit").text() +
                            "&webPageID=" + getWebPageID() +
                            '&ColourID=' + $("#" + prefix + "hiddenPreSelColourID").text();


            //$.post("PricingConfig/SaveContact.aspx", queryString);
            $.ajax({
                type: 'POST',
                url: "PricingConfig/MyQuote.aspx",
                data: queryString,
                dataType: "xml",
                success: checkContactRegister
            });

            if ($('input#contactCheckbox').attr('checked'))
                TrackPageView('/virtualpv/account/submit/contactYes');
            else
                TrackPageView('/virtualpv/account/submit/contactNo');
        }
    });

    function checkContactRegister(xml) {
        //alert("Got here");
        var message = $(xml).find("message").text();
        if (message != "") {
            alert(message);
        }
        else {
            /*
            //redirect to Compare Quotes page
            var webSiteID = $(xml).find("webSiteID").text();
            var webPageID = $(xml).find("webPageID").text();
            location.href("http://" + location.host + "/webPage.aspx?WebSiteID=" + webSiteID + "&webpageID=" + webPageID);
            */
            SaveGA($('div #create_submit_button'));
            $('.PricingQMDiv').show();
            $("#thank_you_submit").text($(subaruModelsXML).find("#save_quote_thanks").text());
            $('div#thank_you_text').hide();
//            $('#thank_you_text').text($(subaruModelsXML).find('#thank_you_text').text().replace('<model>', $('#dropdownModelTitle').text()));
            if (IsFrench()) {            
                $('#thank_you_another').addClass('find_dlr_button_fr');
                $('#thank_you_model').addClass('find_dlr_button_fr');
            }
            $("#thank_you_form").show();
            $("#signupArea").hide();            
        }
    }

    $("div #contactArea_submit").click(function() {
        //Validate form
        var err = "";
        var validEmail = false;
        if ($("#contact_name").attr("value") == "") {
            err = $(subaruModelsXML).find("#contact_name_error").text();
            alert(err);
            return;
        }
        if ($("#contact_email").attr("value") == "") {
            err = $(subaruModelsXML).find("#contact_email_error1").text();
            alert(err);
            return;
        }
        else {
            validEmail = validateEmail("contact_email");
            if (!validEmail) {
                alert($(subaruModelsXML).find("#contact_email_error").text());
                return;
            }
        }
        if (err == "" && validEmail) {
            //Submit Form
            var queryString = "LanguageCode=" + $("#" + prefix + "hiddenLanguage").text() +
                "&DaxDealerID=" + $("#" + prefix + "hiddenDaxDealerID").text() +
                "&LeadID=" + $("#" + prefix + "hiddenLeadID").text() +
                "&QuoteID=" + $("#" + prefix + "hiddenQuoteID").text() +
//                "&provinceCode=" + $("#" + prefix + "hiddenPriceProvince").attr("value") +
                "&email=" + $("#contact_email").attr("value") +
                "&name=" + $("#contact_name").attr("value") +
                "&company=" + $("#contact_company").attr("value") +
                "&address=" + $("#contact_address").attr("value") +
                "&city=" + $("#contact_city").attr("value") +
                "&provinceCode=" + $("#" + prefix + "contact_province").val() +
                "&postal=" + $("#contact_postal").attr("value") +
                "&phone=" + $("#contact_phone").attr("value") +
                "&phoneContact=" + $("#contact_phone_type option:selected").val() +
                "&contact=";
            if ($("#contact_contact_phone").attr("checked")) {
                queryString += "phone";
            }
            else if ($("#contact_contact_email").attr("checked")) {
                queryString += "email";
            }

            queryString += "&contactTime=";
            if ($("contact_time_day").attr("checked")) {
                queryString += "day";
            }
            if ($("contact_time_evening").attr("checked")) {
                queryString += "eveining";
            }
            if ($("contact_time_anytime").attr("checked")) {
                queryString += "anytime";
            }

            queryString += "&comments=" + $('#contactComments').val();
            queryString += "&copyEmail=";
            if ($("#copy_email").attr("Checked")) {
                queryString += "Y";
            }
            else {
                queryString += "N";
            }

            var accIDs = returnSelectedAccessoryIDs();

            queryString += "&carID=" + $("#hiddenSelectedCarID").text() +
                            "&preferredDealer=" + $("#dealerID").attr("value") +
                            "&colourIndex=" + $("#hiddenSelectedColourIndex").text() +
                            '&ColourID=' + $("#" + prefix + "hiddenPreSelColourID").text() +
                            "&accessoryID=" + accIDs +
                            "&financeCategory=" + $("#hiddenSelectedPurchaseType").text() +
                            "&paymentIndex=" + $("#hiddenSelectedPurchaseIndex").text() +
                            "&deposit=" + $("#hiddenDeposit").text() +
                            "&webSiteID=" + getWebSiteID() +
                            "&webPageID=" + getWebPageID() +
                            "&range=" + $("#dropdownModelTitle").text() +
                            "&trim=" + $("#dropdownTrimTitle").text();

            //alert(queryString);

            //$.post("PricingConfig/SaveContact.aspx", queryString);

            TrackPageView('/virtualpv/buildprice/quote/submit');
            
            $.ajax({
                type: 'POST',
                url: "PricingConfig/SaveContact.aspx",
                data: queryString,
                dataType: "xml",
                success: checkContactSave
            });
        }

    });

    function checkContactSave(xml) {
        $("div #contactArea").hide();
        $('div.PricingQMDiv').show();
        
        if ($(xml).find("error").text() != '') {
            $("div #thank_you_text").text($(xml).find("error").text());
            $('div #thank_you_submit').hide();
        }
        else {
            SaveGA($('div #contactArea_submit'));
//          $("#thank_you_text").text($(xml).find("ContactSave").text());
            if (IsFrench()) {            
                $('div #thank_you_another').addClass('find_dlr_button_fr');
                $('div #thank_you_model').addClass('find_dlr_button_fr');
            }
            $("div #thank_you_submit").text($(subaruModelsXML).find("#thank_you_submit").text());
            $('div#thank_you_text').hide();
//            $('div #thank_you_text').text($(subaruModelsXML).find('#thank_you_text').text().replace('<model>', $('#dropdownModelTitle').text()));
            $('div #thank_you_submit').show();
        }
        
        $("#thank_you_form").show();
    }

    var bindColourSelectImage = function(scope) {

        $(scope).bind("mouseover", function() {
            $(this).css("color", "#0232FF");
            var dropdown = this.id.split("_");
            if (dropdown[0] == "colour") {
                var carID = $("#hiddenCarID").html();
                //$("#model_colour_image").attr("src", "http://www.subaru.ca/Content/7907/Media/General/Thumbnail/" + carID + "_" + dropdown[1] + ".jpg");
                SetColour(carID, dropdown[1]);
            }
            if (dropdown[0] == "trim") {
                $("#trim_popout").show();
                //Update trim_popout
                //Image
                $("#trim_popout_image").attr("src", "http://www.subaru.ca/Content/7907/Media/General/Thumbnail/" + dropdown[1] + "_large.jpg");

                $(modelXML).find("trim").each(function() {
                    if ($(this).attr("carID") == dropdown[1]) {
                        //Starting At
                        //$("#trim_popout_price").html(formatCurrency($(this).find("startingAt").text(), $("#NewPricing_hiddenLanguage").text()));
                        $("#trim_popout_price").html(formatCurrency($(this).find("startingAt").text(), $("#" + prefix + "hiddenLanguage").text()));
                        //Get specs
                        $("#trim_popout_specs").empty();
                        var listText = "";
                        $(this).find("spec").each(function() {
                            listText += "<li>" + $(this).text() + "</li>";
                        });
                        if (listText != "")
                            $("#trim_popout_specs").append("<ul>" + listText + "</ul>");
                    }
                });
            }
        });

        $(scope).bind("mouseout", function() {
            //$(this).css("color", "#666666");
            $(this).removeAttr('style');
            //Change colour back to grey
            var dropdown = this.id.split("_");
            if (dropdown[0] == "colour") {
                var carID = $("#hiddenSelectedCarID").html();
                var prevColourID = $('#' + prefix + 'hiddenPreSelColourID').text();
                if (prevColourID != '') {
                    SetColour(carID, prevColourID);
                }
                else {
                    $("#model_colour_image").attr("src", "http://www.subaru.ca/Content/7907/Media/General/Thumbnail/" + carID + "_large.jpg");
                    $("#interior_swatch1").hide();
                    $("#interior_swatch2").hide();
                }
            }
            if (dropdown[0] == "trim") {
                $("#trim_popout_specs").empty();
                $("#trim_popout").hide();
            }
        });


        $(scope).bind("click", (function() {
            var dropdown = this.id.split("_");
            switch (dropdown[0]) {
                case "province":
                    {
                        //Check if Province was set before
                        if ($("#" + prefix + "hiddenPriceProvince").attr("value") == "") {
                            //Update hidden Province field
                            $("#" + prefix + "hiddenPriceProvince").attr("value", this.id.replace("province_", ""));
                            if ($("#hiddenSelectedCarID").text() != "") {
                                enableDropdown("Model");
                                enableDropdown("Year");
                                enableDropdown("Trim");
                                enableDropdown("Transmission");
                                enableDropdown("Colour");
                                if ($("#hiddenColourSelected").text() == "Y") {
                                    $("#Pricing_access").show();
                                    //Update payments with selected Province
                                    getFinanceDetails($("#hiddenSelectedCarID").text());
                                    PreselectPayment();
                                    $("#Payments").show();
                                }
                            }
                            else {
                                if ($("#" + prefix + "hiddenPreSelRange").text() != "") {
                                    enableDropdown("Model");
                                }
                                if ($("#" + prefix + "hiddenPreSelYear").text() != "") {
                                    enableDropdown("Year");
                                    enableDropdown("Trim");
                                }
                            }

                        }
                        else {
                            /*
                            //if user has selected a different province then must clear all dropdowns
                            if ($("#dropdownProvinceTitle").html() != $(this).html()) {
                                $("#dropdownModelTitle").html("Select Model");
                                //ClearAllDropDownLists();
                                ResetModel();
                                validateProvince();
                            }
                            */                            
                            //Update hidden Province field
                            $("#" + prefix + "hiddenPriceProvince").attr("value", this.id.replace("province_", ""));
                            
                            if ($("#Payments").is(":visible"))
                                getFinanceDetails($("#hiddenSelectedCarID").text());
                        }

                        //update dropdown list selection
                        $("#dropdownProvinceTitle").html($(this).html());
                        if ($('input.geolocated').val() != '')
                            $("#" + prefix + "dealer_search_input").val($(this).html());


                        //hide dropdownselect
                        $("#selectionProvince").hide("slow");
                        $('#PreselectProvinceArea').hide();
                        break;
                    }
                case "model":
                    {
                        //resetPricing();
                        ResetModel(true);
                        displayDealerLocator("hide", true);
                        $("#hiddenSelectedCarID").text("");
                        $("#hiddenCarID").html(dropdown[1]);
                        //update dropdown list selection
                        $("#dropdownModelTitle").html($(this).html());
                        $('#' + prefix + 'hiddenPreSelRange').text($(this).html());

                        validateModel();
                        UpdateAnotherQuote();
                        TrackPageView('/virtualpv/buildprice/select/model');
                        
                        //hide dropdownselect
                        $("#selectionModel").hide("slow");
                        break;
                    }
                case "year":
                    {
                        ResetTrims();
                        $("#hiddenCarID").text("");
                        //update dropdown list selection
                        $("#dropdownYearTitle").html($(this).html());
                        $('#' + prefix + 'hiddenPreSelYear').text($(this).html());
                        
                        UpdateAnotherQuote();
                        TrackPageView('/virtualpv/buildprice/select/year');
                        
                        //hide dropdownselect
                        $("#selectionYear").hide("slow");
                        loadModelThumbnails($("#dropdownModelTitle").text(), $(this).html())
                        break;
                    }
                case "trim":
                    {
                        $("#hiddenCarID").html(dropdown[1]);
                        $("#hiddenSelectedCarID").text(dropdown[1]);
                        $("#steps_title").text($(this).html());
                        ResetTrim();
                        $("#model_colour_image").attr("src", "http://www.subaru.ca/Content/7907/Media/General/Thumbnail/" + dropdown[1] + "_large.jpg");
                        //Set Starting At Price
                        var modelCode = '';
                        $(modelXML).find("trim[carID='" + dropdown[1] + "']").each(function() {
                            //alert($(this).attr("carID") + " : " + dropdown[1]);
//                            if ($(this).attr("carID") == dropdown[1]) {
                                $("#colourPrice").text(formatCurrency($(this).find("startingAt").text(), $("#" + prefix + "hiddenLanguage").text()));
                                modelCode = $(this).attr('code');
//                            }
                        });
                        trackedTransmission = false;
                        trackedColour = false;
                        trackedAccessory = false;
                        trackedPayment = false;
                        TrackPageView('/virtualpv/buildprice/select/trim');
                        TrackEvent('BuildPrice', 'Quote', modelCode, 1);

                        //Update Vehicle MSRP Title
                        $("#lblVehicleMSRP").text($(subaruModelsXML).find("#startingAt").text() + ":");
                        updateTransmission(dropdown[1]);
                        //update dropdown list selection
                        $("#dropdownTrimTitle").html($(this).html());
                        
                        $("#VehicleThumbnails").hide();
                        $("#colour_view").show();
                        $("#price_view").hide();
                        $("#colours").show();
            
                        UpdateAnotherQuote();
                        //hide dropdownselect
                        $("#selectionTrim").hide("slow");
                        $("#trim_popout").hide();
                        
                        // Preselect the first transmission
                        if ($('#selectionTransmission').children().length > 1)
                        {
                            $('#selectionTransmission :first-child').click();
                        }
                        break;
                    }
                case "transmission":
                    {
                        var carID = $("#hiddenCarID").html();
                        var selTransmission = $(this).html();
                        $("#interior_swatch1").hide();
                        $("#interior_swatch2").hide();
                        //Update Hidden Price
                        $(modelXML).find("trim").each(function() {
                            if ($(this).attr("carID") == carID) {
                                $(this).find("transmission").each(function() {
                                    if (selTransmission == $(this).text()) {
                                        $("#hiddenVehiclePrice").text($(this).attr("msrp"));
                                        $("#hiddenSelectedCarID").text($(this).attr("carID"));
                                        //var msrpFmt = formatCurrency($(this).attr("msrp"), $("#NewPricing_hiddenLanguage").text());
                                        var msrpFmt = formatCurrency($(this).attr("msrp"), $("#" + prefix + "hiddenLanguage").text());
                                        $("#colourPrice").text(msrpFmt);
                                        $("#lblVehicleMSRP").text($(subaruModelsXML).find("#lblVehicleMSRP").text());
                                    }
                                });
                            }
                        });
                        UpdateAnotherQuote();
                        if (!trackedTransmission)
                            TrackPageView('/virtualpv/buildprice/select/transmission');
                        trackedTransmission = true;
                        
                        //update dropdown list selection
                        $("#dropdownTransmissionTitle").html($(this).html());
                        //hide dropdownselect
                        $("#selectionTransmission").hide("slow");
                        $('div #colourDetail').show();
                        updateColour(carID);
                        break;
                    }
                case "colour":
                    {
                        $("#hiddenSelectedColourIndex").text(dropdown[2]);
                        $('#' + prefix + 'hiddenPreSelColourID').text(dropdown[1]);
                        UpdateAnotherQuote();
                        displayColour(dropdown[1]);
                        break;
                    }

            }
        }));

    }


    var bindImage = function(scope) {
        $(scope).bind("mouseover", function(event) {

            $("#modelShortSpecs").empty();
            //Display Model Box
            $("#trim_highlight").show();
            //Load Correct image and data
            //Header
            var carString = this.id.split("_");
            //UpdateImage
            $("#model_trim_image").attr("src", "http://www.subaru.ca/Content/7907/Media/General/Thumbnail/" + carString[1] + "_large.jpg");

            $(modelXML).find("trim").each(function() {
                if ($(this).attr("carID") == carString[1]) {
                    $("#model_name_large").html($(this).find("bodyTrim").text());
                    //$("#startingAtMSRP").html(formatCurrency($(this).find("startingAt").text(), $("#NewPricing_hiddenLanguage").text()));
                    $("#startingAtMSRP").html(formatCurrency($(this).find("startingAt").text(), $("#" + prefix + "hiddenLanguage").text()));
                    //Get specs
                    if ($(this).find('spec').length > 0) {
                        var specString = '<ul>';
                        $(this).find("spec").each(function() {
                            specString += "<li>" + $(this).text() + "</li>";
                        });
                        specString += '</ul>';
                        $("#modelShortSpecs").append(specString);
                    }
                }
            });
        });
        $(scope).bind("mouseout", function(event) {
            $("#trim_highlight").hide();
        });
        $(scope).bind("click", function(event) {
            //Select the correct Trim from the dropdown list
            var carIDString = this.id.split("_");
            $("#dropdownTrimTitle").html($(this).attr("alt"));
            $("#steps_title").text($(this).attr("alt"));

            $("#model_colour_image").attr("src", "http://www.subaru.ca/Content/7907/Media/General/Thumbnail/" + carIDString[1] + "_large.jpg");
            $("#lblVehicleMSRP").text($(subaruModelsXML).find("#startingAt").text() + ":");
            $("#VehicleThumbnails").hide();
            $("#colour_view").show();
            $("#price_view").hide();
            $("#colours").show();
            
            var modelCode = '';
            $(modelXML).find("trim[name='" + $(this).attr("alt") + "']").each(function() {
                    modelCode = $(this).attr('code');
            });
            
            trackedTransmission = false;
            trackedColour = false;
            trackedAccessory = false;
            trackedPayment = false;
            TrackPageView('/virtualpv/buildprice/select/trim');
            TrackEvent('BuildPrice', 'Quote', modelCode, 1);

            //Update hidden CarID
            $("#hiddenCarID").html(carIDString[1]);
            updateTransmission(carIDString[1]);
            
            $("#hiddenSelectedCarID").text(carIDString[1])
            
            UpdateAnotherQuote();
            $('#selectionTrim').hide();
            $("#trim_highlight").hide();

            // Preselect the first transmission
            if ($('#selectionTransmission').children().length > 1)
            {
                $('#selectionTransmission :first-child').click();
            }
        });
    }

    var bindAccessory = function(scope) {
        $(scope).bind("mouseover", (function(event) {
            //update Image and accessory info on left...
            var acclbl = $(this).find(".accessories_list").attr("id").split("_");
            var accPrice;
            var accTitle;

            //If the first accessory mouse over then update the description titles
            if ($("#accessory_image").attr("src", "http://www.subaru.ca/Content/7907/media/General/Accessory/accessory_blank.jpg")) {
                $("#accessory_listPriceTitle").show();
                $("#accessory_listPrice").show();
                //Update Price
                //$("#accessories_vehicle_price").text(formatCurrency($("#hiddenVehiclePrice").text(), $("#NewPricing_hiddenLanguage").text()));
                $("#accessories_vehicle_price").text(formatCurrency($("#hiddenVehiclePrice").text(), $("#" + prefix + "hiddenLanguage").text()));
            }

            //load Accessory
            $(accXML).find("accessory").each(function() {
                if ($(this).attr("id") == acclbl[1]) {
                    accTitle = $(this).find("title").text();
                    $("#accessory_title").text(accTitle);
                    $("#accessory_description").text($(this).find("description").text());
                    //accPrice = formatCurrency($(this).find("price").text(), $("#NewPricing_hiddenLanguage").text());
                    accPrice = formatCurrency($(this).find("price").text(), $("#" + prefix + "hiddenLanguage").text());
                    $("#accessory_listPrice").text(accPrice + " *");
                    //check if there is a labour rate
                    if ($("#" + prefix + "hiddenWebSiteType").text() == "Dealersite Template" && $("#" + prefix + "hiddenLabourRate").text() != "0") {
                        $("#accessory_installTitle").hide();
                        $("#accessory_install").hide();
                        $("#accessory_dealerInstallTitle").show();
                        $("#accessory_dealerInstall").show();
                        var labourRate = parseFloat($("#" + prefix + "hiddenLabourRate").text());
                        var time = parseFloat($(this).find("install").text());
                        var installCost = parseFloat(labourRate * time);
                        $("#accessory_dealerInstall").text(formatCurrency(installCost, $("#" + prefix + "hiddenLanguage").text()));
                    }
                    else {
                        $("#accessory_installTitle").show();
                        $("#accessory_install").show();
                        var hourTranslate = $(subaruModelsXML).find("#hours").text()
                        $("#accessory_install").text($(this).find("install").text() + " " + hourTranslate);
                    }
                    if ($(this).find("image").text() == "") {
                        $("#accessory_image").attr("src", "http://www.subaru.ca/Content/7907/media/General/Accessory/no_image.jpg");
                    }
                    else {
                        $("#accessory_image").attr("src", "http://www.subaru.ca/Content/7907/media/General/Accessory/" + $(this).find("image").text());
                    }
                }
            });

        }));
    }

    var bindAccessoryCheck = function(scope) {
        $(scope).bind("click", (function(event) {

            //if more than 1 accessory is selected then display selected accessories div
            var acclbl = this.id.split("_");
            if ($(this).attr("checked") == true) {

                var accSelPrice;
                var accSelTitle;
                var qtySoldIn;
                //load Accessory
                $(accXML).find("accessory").each(function() {
                    if ($(this).attr("id") == acclbl[1]) {
                        qtySoldIn = 1;
                        accSelTitle = $(this).find("title").text();
                        accSelPrice = $(this).find("price").text();
                        var actualQuantity = parseInt($(this).find("soldIn").text());
                        if (actualQuantity != NaN && actualQuantity > 1) {
                            qtySoldIn = actualQuantity;
                            accSelTitle = accSelTitle + " X " + $(this).find("soldIn").text();
                            accSelPrice = accSelPrice * qtySoldIn;
                        }
                        if ($(this).find("residual").text() == "Y") {
                            //Add to residual value
                            var accResTotal = parseFloat($("#hiddenAccResTotal").text());
                            if ($(this).find("residualValue").text() != "") {
                                var accRes = parseFloat($(this).find("residualValue").text());
                            }
                            if ($(this).find("soldIn").text() != "1") {
                                accRes = accRes * qtySoldIn;
                            }
                            var newAccResTotal = accResTotal + accRes;
                            $("#hiddenAccResTotal").text(newAccResTotal);
                        }
                    }
                });

                //Add Accessory to Selected Accessories
                var selAcc = $(document.createElement("div"));
                selAcc.css("width", "441px")
                        .css("float", "left")
                        .attr("id", "selAcc_" + acclbl[1]);

                var bullet = $(document.createElement("div"));
                bullet.html("<img height=\"13\" width=\"22\" src=\"http://www.subaru.ca/content/7907/Media/General/WebImage/grey_dot.gif\">")
                        .css("float", "left");

                var accTitle = $(document.createElement("div"));
                accTitle.css("float", "left")
                        .html(accSelTitle);

                var padding = $(document.createElement("div"));
                padding.css("float", "right")
                        .html("&nbsp;")
                        .css("width", "10px");

                var accPrice = $(document.createElement("div"));
                accPrice.css("float", "right")
                    .html(formatCurrency(accSelPrice, $("#" + prefix + "hiddenLanguage").text()));
                //.html(formatCurrency(accSelPrice, $("#NewPricing_hiddenLanguage").text()));

                selAcc.append(bullet)
                        .append(accTitle)
                        .append(padding)
                        .append(accPrice);

                $("#pricing_select_accessories").append(selAcc);

                //Update Accessory Price Total
                //Will need price unformatted?

                var currentAccTotal = parseFloat($("#hiddenAccTotal").text());

                var newAccTotal = currentAccTotal + parseFloat(accSelPrice);
                $("#hiddenAccTotal").text(newAccTotal);
                //var accTotalFmt = formatCurrency(newAccTotal, $("#NewPricing_hiddenLanguage").text());
                var accTotalFmt = formatCurrency(newAccTotal, $("#" + prefix + "hiddenLanguage").text());
                $("#price_view_acc").text(accTotalFmt);
                $("#pricing_accessory_total").text(accTotalFmt);
                var vehiclePrice = parseFloat($("#hiddenVehiclePrice").text());
                var newTotal = vehiclePrice + parseFloat(newAccTotal);
                //var newTotalFmt = formatCurrency(newTotal, $("#NewPricing_hiddenLanguage").text());
                var newTotalFmt = formatCurrency(newTotal, $("#" + prefix + "hiddenLanguage").text());
                $("#price_view_total").text(newTotalFmt);
                $("#accessories_total_price").text(newTotalFmt);
                
                if (!trackedAccessory)
                    TrackPageView('/virtualpv/buildprice/select/accessory');
                trackedAccessory = true;
            }
            else {
                //Deducted from Accessory Total
                $(accXML).find("accessory").each(function() {
                    if ($(this).attr("id") == acclbl[1]) {
                        accSelPrice = $(this).find("price").text();
                        var actualQuantity = parseInt($(this).find("soldIn").text());
                        if (actualQuantity != NaN && actualQuantity > 1) {
                            qtySoldIn = actualQuantity;
                            accSelTitle = accSelTitle + " X " + $(this).find("soldIn").text();
                            accSelPrice = accSelPrice * qtySoldIn;
                        }
                        if ($(this).find("residual").text() == "Y") {
                            //Deduct from residual value
                            var accResTotal = parseFloat($("#hiddenAccResTotal").text());
                            if ($(this).find("residualValue").text() != "") {
                                var accRes = parseFloat($(this).find("residualValue").text());
                            }
                            if ($(this).find("soldIn").text() != "1") {
                                accRes = accRes * parseInt($(this).find("soldIn").text());
                            }
                            var newAccResTotal = accResTotal - accRes;
                            $("#hiddenAccResTotal").text(newAccResTotal);
                        }
                    }
                });
                var currentAccTotal = parseFloat($("#hiddenAccTotal").text());

                var newAccTotal = currentAccTotal - parseFloat(accSelPrice);
                $("#hiddenAccTotal").text(newAccTotal);
                //var accTotalFmt = formatCurrency(newAccTotal, $("#NewPricing_hiddenLanguage").text());
                var accTotalFmt = formatCurrency(newAccTotal, $("#" + prefix + "hiddenLanguage").text());
                $("#price_view_acc").text(accTotalFmt);
                $("#pricing_accessory_total").text(accTotalFmt);
                var vehiclePrice = parseFloat($("#hiddenVehiclePrice").text());
                var newTotal = vehiclePrice + parseFloat(newAccTotal);
                //var newTotalFmt = formatCurrency(newTotal, $("#NewPricing_hiddenLanguage").text());
                var newTotalFmt = formatCurrency(newTotal, $("#" + prefix + "hiddenLanguage").text());
                $("#price_view_total").text(newTotalFmt);
                $("#accessories_total_price").text(newTotalFmt);

                //remove from List
                $("#selAcc_" + acclbl[1]).remove();
            }

            if ($("#divscroll input:checked").length == 0) {
                $("#Accessories_Detail").hide();
            }
            else {
                $("#Accessories_Detail").show();
            }

            //Recalculate Payment Options
            getFinanceDetails($("#hiddenSelectedCarID").text());

            //Reload Selected Purchase option
            //if ($("#hiddenSelectPurchaseTerm").text() != "") {
            //loadPurchaseDetails($("#hiddenSelectPurchaseTerm").text());
            //loadPurchaseDetails("Cash");
            //}
        }));
    }

    var bindPurchaseInput = function(scope) {
        $(scope).bind("click", (function(event) {
                var term = $(this).attr('value');
                if (term == undefined) {
                    term = $(this).attr('id');
                }
            //$("#hiddenSelectPurchaseTerm").text($(this).attr("value"));
            $('#hiddenSelectPurchaseTerm').text(term);
            var inputValue = $(this).attr("value");
            if (inputValue != undefined)
                inputValue = inputValue.split("_");
            else
                inputValue = $(this).attr('id').split('_');

            // Ignore, already set
            if ($("#hiddenSelectedPurchaseIndex").text() == inputValue[2] &&
                $("#hiddenSelectedPurchaseType").text() == inputValue[0].substr(0, 1))
                return;
            
            $("#hiddenSelectedPurchaseIndex").text(inputValue[2]);
            $("#hiddenSelectedPurchaseType").text(inputValue[0].substr(0, 1));
            HidePaymentDetails();
            //display correct payment details
            $("#purchasing_details").show();

            //Load PaymentDetails
            //loadPurchaseDetails($(this).attr("value"));
            loadPurchaseDetails(term);
            $("#" + inputValue[0] + "_payment").show();

            //Remove selected class from all rows
            $(".table_pricing_display_selected").removeClass("table_pricing_display_selected");

            $("input[name$='purchase_input']").removeAttr("checked");
            $('#' + term + ' input').attr("checked", "checked");
            
            //Highlight row
            if (!$('#' + term + ' input').attr('disabled')) {
                $("#" + term).addClass("table_pricing_display_selected");
                $("#" + term).find("div").each(function() {
                    $(this).addClass("table_pricing_display_selected");
                });
            }

            colourAlternateLines(inputValue[0]);
            $("#dealerSearchForm").show();
            //Update Quote Name
            var quote_translate = $(subaruModelsXML).find("#quote").text();
            var quoteCount = parseInt($("#" + prefix + "hiddenQuoteCount").text()) + 1;
            $("#quote_name").attr("value", quote_translate + " " + quoteCount.toString());
            
            if ($(this).hasClass('GAPayment')) {
                var container = $(this);
                
                if (!trackedPayment)
                    TrackPageView('/virtualpv/buildprice/select/payment');
                trackedPayment = true;
                var type = $(this).attr('id');
                if (!(/cash/i).test(type)) {
                    type = type.replace(/_.*$/, '');
                    TrackEvent('Payment', type, container.find('div.term').text() + 'mos', 1);
                }
            }
            
            resizeCol();
        }));
    }

    var bindAccCategory = function(scope) {
        $(scope).bind("click", (function(event) {
            id = $(this).text();
            clearTimeout(timer)
            scrollingDiv = document.getElementById("divscroll")

            if (document.defaultView && document.defaultView.getComputedStyle(scrollingDiv, '').getPropertyValue("position") != "absolute") {
                browserOffset = scrollingDiv.offsetTop
            }
            else {
                browserOffset = 0
            }

            if (scrollingDiv.scrollTop <= document.getElementById(id).offsetTop - scrollSteps - browserOffset) {
                scrollingDiv.scrollTop = document.getElementById("divscroll").scrollTop + scrollSteps
                timer = setTimeout("scrollDiv('" + id + "')", 10)

                // if bottom of page reached before anchor point
                if (scrollingDiv.scrollTop > (scrollingDiv.scrollHeight - scrollingDiv.offsetHeight) - scrollSteps) {
                    clearTimeout(timer)
                    scrollingDiv.scrollTop = document.getElementById("divscroll").scrollHeight - scrollingDiv.offsetHeight
                }
            }
            else {
                if (scrollingDiv.scrollTop >= document.getElementById(id).offsetTop + scrollSteps - browserOffset) {
                    scrollingDiv.scrollTop = document.getElementById("divscroll").scrollTop - scrollSteps
                    timer = setTimeout("scrollDiv('" + id + "')", 10)
                }
                else {
                    clearTimeout(timer)
                    scrollingDiv.scrollTop = document.getElementById(id).offsetTop - browserOffset
                }
            }
        }));
    }



    //Functions

    function validateProvince() {
        //Check for Insurance quote link
        if (($("#" + prefix + "hiddenPriceProvince").attr("value") == "ON") || ($("#" + prefix + "hiddenPriceProvince").attr("value") == "QC") || ($("#" + prefix + "hiddenPriceProvince").attr("value") == "AB")) {
            $("#insurance_separator").show();
            $("#insurance_quote_link").show();
        }
        else {
            $("#insurance_separator").hide();
            $("#insurance_quote_link").hide();
        }
        if ($("#" + prefix + "hiddenPriceProvince").attr("value") != "") {
            enableDropdown("Model");
        }
    }

    function validateModel() {
        $("#model_colour_image").attr("src", "");
        $("#colours").hide();
        $("#dealerSearchForm").hide();
        $("#view_spec_insurance").hide();
        $("#Pricing_access").hide();
        $("#Payments").hide();
        $("#hiddenCarID").text("");
        $("#hiddenSelectedID").text("");
        $("#hiddenAccTotal").text("0.00");
        $("#hiddenAccResTotal").text("0.00");
        $("#hiddenVehiclePrice").text("0.00");
//        $("#hiddenSelectPurchaseTerm").text("");
        $("#pricing_select_accessories").empty();
        $("#Accessories_Detail").hide();

        //Clear Accessory List
        $("#divscroll").empty();
        //reset images in accessory 
        $('#accessory_title').text($(subaruModelsXML).find('#accessory_title').text());
        $('#accessory_description').text($(subaruModelsXML).find('#accessory_description').text());
        $("#accessory_listPriceTitle").hide();
        $("#accessory_listPrice").hide();
        $("#accessory_installTitle").hide();
        $("#accessory_install").hide();
        $("#accessory_dealerInstallTitle").hide();
        $("#accessory_dealerInstall").hide();
        $("#accessory_image").attr("src", "http://www.subaru.ca/Content/7907/media/General/Accessory/accessory_blank.jpg");

        //Update Year dropdown
        //find Years from subaruModelsXML
        //clear Year Select
        $("#selectionYear").empty();
        $("#thumbnailContainer").empty();
        $(subaruModelsXML).find("model").each(function() {
            if ($(this).text() == $("#dropdownModelTitle").text()) {
                var years = $(this).attr("years").split("_");
                var i;
                for (i = 0; i < years.length; i++) {
                    //alert(years[i]);
                    var yearName = $(document.createElement("div"));
                    yearName.css("vertical-align", "middle")
                                .html(years[i])
                                .attr("id", "year_" + years[i])
                                .attr("class", "sidemenu_select");
                    $(yearName).appendTo($("#selectionYear"));

                    bindColourSelectImage(yearName);
                }
                if (years.length == 1) {
                    $("#dropdownYearTitle").html(years[0]);
                    $('#' + prefix + 'hiddenPreSelYear').text(years[0]);
                    loadModelThumbnails($("#dropdownModelTitle").text(), years[0])
                }
                else {
                    if ($("#" + prefix + "hiddenPreSelYear").text() != "") {
                        $("#dropdownYearTitle").html($("#" + prefix + "hiddenPreSelYear").text());
                        loadModelThumbnails($("#dropdownModelTitle").text(), $("#" + prefix + "hiddenPreSelYear").text())
                    }
                    else {
                        //update Year dropdownTitle to Select Year
                        $("#dropdownYearTitle").text($(subaruModelsXML).find("#dropdownYearTitle").text());
                        //Clear and Disable Trim/Transmission/Colour
                        clearDropdown("Trim");
                        clearDropdown("Transmission");
                        clearDropdown("Colour");
                        disableDropdown("Trim");
                        disableDropdown("Transmission");
                        disableDropdown("Colour");
                    }
                }
                if ($("#" + prefix + "hiddenPriceProvince").attr("value") != "") {
                    enableDropdown("Year");
                }

            }
        });

        //Update steps_title
        var model = $("#dropdownModelTitle").text();
        $("#steps_title").text(model.toUpperCase());

        //Load Vehicle Thumbnails
        //loadModelThumbnails(modelName, model[0]);
    }

    function getModels() {
        //Use AJAX to load the model?
        //Return XML file
        $.ajax({
            type: "GET",
            url: "PricingConfig/SubaruModels.aspx?Language=" + $("#" + prefix + "hiddenLanguage").text() + "&WebSiteID=" + getWebSiteID(),
            dataType: "xml",
            success: parseModelsXml
        });
    }

    function parseModelsXml(xml) {
        translateText(xml);

        subaruModelsXML = xml;

        //Load Provinces
        var selProvince;
        $(xml).find("province").each(function() {
            if ($(this).attr("Selected") == "true") {
                selProvince = $(this).text();
            }
            var provinceName = $(document.createElement("div"));
            provinceName.css("vertical-align", "middle")
                                .html($(this).text())
                                .attr("id", "province_" + $(this).attr("id"))
                                .attr("class", "sidemenu_select");
            $(provinceName).appendTo($("#selectionProvince"));

            bindColourSelectImage(provinceName);
        });
        if (selProvince != undefined && selProvince != "") {
            $("#dropdownProvinceTitle").html(selProvince);
            if ($('input.geolocated').val() != '')
                $("#" + prefix + "dealer_search_input").val(selProvince);
        }

        var range = "";
        if ($("#" + prefix + "hiddenPreSelRange").text() != "") {
            //Preselect Range if valid range then select
            range = $("#" + prefix + "hiddenPreSelRange").text();
        }

        var yearRangeCarID = "";
        $(xml).find("model").each(function() {
            year = $(this).text();
            if ($(this).text() == range) {
                yearRangeCarID = "model_" + $(this).attr("carIDs");
            }
            var modelName = $(document.createElement("div"));
            modelName.css("vertical-align", "middle")
                                .html($(this).text())
                                .attr("id", "model_" + $(this).attr("carIDs"))
                                .attr("class", "sidemenu_select");
            $(modelName).appendTo($("#selectionModel"));

            bindColourSelectImage(modelName);
        });

        if ($("#" + prefix + "hiddenPriceProvince").attr("value") != "") {
            enableDropdown("Model");
        }

        if (yearRangeCarID != "") {
            //Update title
            $("#dropdownModelTitle").text(range);
            //If more than one model year then hiddenCarID cannot be set
            var modelYears = yearRangeCarID.split("_");
            if (modelYears.length == 2) {
                $("#hiddenCarID").text(modelYears[1]);
            }
            validateModel();
        }
        
        
        if (selProvince == undefined || selProvince == "") {
            $("#preselect_dropdownProvince").click(function() {
                $(".dropdown_select").not("#preselect_selectionProvince").hide();
                if ($("#preselect_selectionProvince").is(":visible")) {
                    $("#preselect_selectionProvince").hide();
                }
                else {
                    $("#preselect_selectionProvince").show();
                }
            });
            
            $(subaruModelsXML).find("province").each(function() {
                var provinceName = $(document.createElement("div"));
                provinceName.css("vertical-align", "middle")
                                    .html($(this).text())
                                    .attr("id", "province_" + $(this).attr("id"))
                                    .attr("class", "sidemenu_select");
                $(provinceName).appendTo($("#preselect_selectionProvince"));
    
                
                $(provinceName).click(function() {
                    //Check if Province was set before
//                    if ($("#" + prefix + "hiddenPriceProvince").attr("value") == "") {
                        //Update hidden Province field
                        $("#" + prefix + "hiddenPriceProvince").attr("value", this.id.replace("province_", ""));
                        $("#dropdownProvinceTitle").html($(this).html());
                        enableDropdown("Model");
                        if ($("#hiddenSelectedCarID").text() != "") {
                            enableDropdown("Year");
                            enableDropdown("Trim");
                            enableDropdown("Transmission");
                            enableDropdown("Colour");
                            if ($("#hiddenColourSelected").text() == "Y") {
                                $("#Pricing_access").show();
                                //Update payments with selected Province
                                getFinanceDetails($("#hiddenSelectedCarID").text());
                                PreselectPayment();
                                $("#Payments").show();
                            }
                        }
                        else {
                            if ($("#" + prefix + "hiddenPreSelRange").text() != "") {
                                enableDropdown("Model");
                            }
                            if ($("#" + prefix + "hiddenPreSelYear").text() != "") {
                                enableDropdown("Year");
                                enableDropdown("Trim");
                            }
                        }
//                    }
                    
                    //update dropdown list selection
                    $('#preselect_dropdownProvinceTitle').html($(this).find('#dropdownProvinceTitle').text());                
                    
                    //hide dropdownselect
                    $("#selectionProvince").hide("slow");
                    $('#PreselectProvinceArea').hide();
                });
            });
            
            $('#preselect_dropdownProvinceTitle').html($(xml).find('#dropdownProvinceTitle').text());
            $('#dropdownProvinceTitle').html($(xml).find('#dropdownProvinceTitle').text());
            if ($('input.geolocated').val() != '')
                $("#" + prefix + "dealer_search_input").val($('#dropdownProvinceTitle').html());
            
            $("#" + prefix + "hiddenPriceProvince").val('');
            disableDropdown("Model");
            disableDropdown("Year");
            disableDropdown("Trim");
            disableDropdown("Transmission");
            disableDropdown("Colour");
            $('#PreselectProvinceArea').show();
        }
    }


    function loadModelThumbnails(model, modelYear) {
        var url = "PricingConfig/ModelData.aspx?Model=" + model.replace(/&/g, '%26') + "&Year=" + modelYear + "&Language=" + $("#" + prefix + "hiddenLanguage").text();
        //Use AJAX to load the model?
        //Return XML file
        $.ajax({
            type: "GET",
            url: url,
            dataType: "xml",
            success: parseXml
        });

    }


    function parseXml(xml) {
        modelXML = xml;

        //ClearAllDropDownLists();
        clearDropdown("Trim");
        clearDropdown("Transmission");
        
        var i = 0;
        var carID = 0;
        var bodyTrim = "";
        //var preSelectYear = "";
        var transmissionFound = false;
        //var yearCount = 0;
        //fill in year dropdown  WHY?
//        $(xml).find("years").find("year").each(function() {
//            yearCount++;
//            var year = $(this).text();
//            if (year == $("#" + prefix + "hiddenPreSelYear").text()) {
//                preSelectYear = year;
//            }
//            var yearName = $(document.createElement("div"));
//            yearName.css("vertical-align", "middle")
//                                .html(year)
//                                .attr("id", "year_" + year)
//                                .attr("class", "sidemenu_select");
//            $(yearName).appendTo($("#selectionYear"));

//            bindColourSelectImage(yearName);

//        });
//        if (yearCount == 1) {
//            $("#dropdownYearTitle").html(year);
//        }
//        if (preSelectYear != "") {
//            $("#dropdownYearTitle").html(preSelectYear);
//        }

        if ($("#" + prefix + "hiddenPriceProvince").attr("value") != "") {
            enableDropdown("Year");
        }
        $("#thumbnailContainer").empty();

        $(xml).find("trim").each(function() {
            bodyTrim = $(this).find("bodyTrim").text();
            var trimName = $(document.createElement("div"));
            trimName.css("vertical-align", "middle")
                                .html(bodyTrim)
                                .attr("id", "trim_" + $(this).attr("carID"))
                                .attr("class", "sidemenu_select");
            $(trimName).appendTo($("#selectionTrim"));

            bindColourSelectImage(trimName);

            carID = $(this).find("carID").text();

            //Need to add DIVs to #vehicle_thumbnails
            i++;
            var e = $(document.createElement("div"));
            $(e).attr("id", "Thumbnail" + i.toString());
            $(e).attr("class", "thumbnail");
            //Add Image and Name
            var divImage = $(document.createElement("div"));
            $(divImage).attr("id", "Thumbnail_image" + i.toString());

            var image = $(document.createElement("img"));
            $(image).attr("src", "http://www.subaru.ca/Content/7907/Media/General/Thumbnail/" + carID + ".jpg")
                        .attr("alt", bodyTrim)
                        .attr("id", "image_" + carID)
                        .attr("class", "thumbnailImage")
                        .appendTo(divImage);
            $(divImage).appendTo(e);

            var imageName = $(document.createElement("div"));
            $(imageName).html(bodyTrim)
                        .attr("id", "thumbnailName_" + carID)
                        .attr("class", "thumbnail_name")
                        .appendTo(e);
            $(e).appendTo("#thumbnailContainer");

            //bindBehaviors(image);
            bindImage(image);
            bindImage(imageName);

            //check transmissions for PreSelectCarID
            var transmissions = $(this).find("transmission").size();
            $(this).find("transmission").each(function() {
                if ($("#" + prefix + "hiddenPreSelCarID").text() == $(this).attr("carID")) {
                    //Set Trim
                    if (transmissions == 1) {
                        //Set actual carID
                        $("#hiddenSelectedCarID").text($(this).attr("carID"));
                    }
                    $("#hiddenCarID").html(carID);
                    $("#steps_title").text(bodyTrim);
                    //update dropdown list selection
                    $("#dropdownTrimTitle").html(bodyTrim);
                    $("#VehicleThumbnails").hide();
                    
                    if ($('#' + prefix + 'hiddenPreSelColourID').text() == '')
                        TrackPageView('/virtualpv/buildprice/select/model');
                    TrackEvent('BuildPrice', 'Quote', $(this).attr('code'), 1);
                    updateTransmission(carID);
                    transmissionFound = true;
                }
            });

        });
        if ($("#" + prefix + "hiddenPriceProvince").attr("value") != "") {
            enableDropdown("Trim");
        }

        //Display Thumbnails
        $("#steps_text").hide();
        HidePaymentDetails();
        if (!transmissionFound) {
            $("#colours").hide();
            $("#VehicleThumbnails").show("slow");
        }
    }

    function getAccessories(carID) {
        //Use AJAX to load the model?
        //Return XML file
        var xmlUrl = "PricingConfig/modelAccessories.aspx?carID=" + carID + "&Language=" + $("#" + prefix + "hiddenLanguage").text() +
            '&WebSiteID=' + getWebSiteID() + 
            '&ColourID=' + $("#" + prefix + "hiddenPreSelColourID").text();
        $.ajax({
            type: "GET",
            url:xmlUrl,
            cache:false,
            dataType: "xml",
            success: parseAccessoryXml
        });
    }

    function parseAccessoryXml(xml) {
        accXML = xml;

        $("#hiddenAccTotal").text('0');
        $("#pricing_select_accessories").empty();
        $("#accessories_category_link").empty();
        $("#divscroll").empty();
        
        var accSplit = $('#hiddenAccessoryIDs').text().split(/;/);
        var lastSelectedAcc = null;
        var selectedCheckboxes = null;

        var accessoriesFound = false;
        var catCount = $(accXML).find("category").size();
        var catWidth = 470 / parseInt(catCount);
        $(accXML).find("category").each(function() {
            //Create Div for Category link
            var catLink = $(document.createElement("div"));
            catLink.addClass("category_link")
                    .text($(this).attr("name"));

            var catLinkBorder = $(document.createElement("div"));
            catLinkBorder.addClass("catLinkBorder")
                    .append(catLink);

            $("#accessories_category_link").append(catLinkBorder);

            accessoriesFound = true;
            var category = $(document.createElement("div"));
            category.attr("id", $(this).attr("name"));

            var innerCategory = $(document.createElement("div"));
            innerCategory.css("width", "230px");

            var categoryTitle = $(document.createElement("div"));
            categoryTitle.addClass("category_title")
                        .text($(this).attr("name"));

            innerCategory.append(categoryTitle);
            bindAccCategory(catLink);

            $(this).find("accessory").each(function() {
                var accessory = $(document.createElement("div"));
                accessory.addClass("accessory_item");

                var accLabel = $(document.createElement("label"));
                var accCheck = $(document.createElement("input"));
                accCheck.attr("type", "checkbox")
                            .attr("id", "chk_" + $(this).attr("id"))
                            .addClass("accessoryInput");

                accLabel.addClass("accessories_list")
                            .attr("id", "lbl_" + $(this).attr("id"))
                            .append(accCheck)
                            .append("&nbsp;" + $(this).find("title").text())
                            .appendTo(accessory);

                bindAccessoryCheck(accCheck);
                accessory.appendTo(innerCategory);
                bindAccessory(accessory);

                var name = $(this).find("title").text();
                var id = parseInt($(this).attr("id"));
                $(accSplit).each(function() {
                        if (parseInt(this) == id) {
                            $(accCheck).attr("checked", "checked");
                            if (selectedCheckboxes == null)
                                selectedCheckboxes = new Array();
                            selectedCheckboxes[selectedCheckboxes.length] = accCheck;
                            lastSelectedAcc = accCheck;
                            $(accCheck).click();
                            return false; // break out
                        }
                });                
            });
            innerCategory.appendTo(category);
            $("#divscroll").append(category);

            if ($("#" + prefix + "hiddenPreSelColourID").text() != "" &&
                !$('#dropdownModelTitle').is('.dropdown_title_disabled')) {
                $("#Pricing_access").show();
            }
            if (accessoriesFound) {
                $("#Pricing_access_show").show();
                $("#Pricing_access_none").hide();
            }
            else {
                $("#Pricing_access_none").show();
                $("#Pricing_access_show").hide();
            }
        });
        if (lastSelectedAcc != null) {
            $(selectedCheckboxes).each(function() {
                    $(this).attr("checked", "checked");
            });
            $("#Accessories_Detail").show();
        }
    }

    function CheckMyQuoteLogIn() {
        TrackPageView('/virtualpv/login/quote/save');
        
        var accIDs = "";
        $("#pricing_select_accessories").children().each(function() {
            accIDs += $(this).attr("id").replace("selAcc_", "") + ",";
        });

        if (accIDs != "") {
            accIDs = accIDs.substr(0, accIDs.length - 1);
        }
        var queryString = "&ProvinceCode=" + $("#" + prefix + "hiddenPriceProvince").attr("value") +
                "&WebSiteID=" + getWebSiteID() +
                "&QuoteName=" + $("#quote_name").attr("value") +
                "&carID=" + $("#hiddenSelectedCarID").text() +
                "&ownerID=" + $("#dealerID").attr("value") +
                "&colourIndex=" + $("#hiddenSelectedColourIndex").text() +
                "&accessoryID=" + accIDs +
                "&financeCategory=" + $("#hiddenSelectedPurchaseType").text() +
                "&paymentIndex=" + $("#hiddenSelectedPurchaseIndex").text() +
                "&deposit=" + $("#hiddenDeposit").text() +
                "&webPageID=" + getWebPageID();
        $.ajax({
            type: "POST",
            url: "PricingConfig/MyQuote.aspx?checkLogin=Y&username=" + $("#login_email").attr("value") + "&password=" + $("#login_password").attr("value") + "&LanguageCode=" + $("#" + prefix + "hiddenLanguage").text() + queryString,
            dataType: "xml",
            success: parseLogInXML
        });
    }

    function parseLogInXML(xml) {
        if ($(xml).find("message").text() != '') {
            $("#loginArea").hide();
            $('.PricingQMDiv').show();
            $('#thank_you_text').text($(xml).find("message").text()); 
            $('#thank_you_form').show();
        }
        else if ($(xml).find("result").text() == "invalid") {
            $("#login_invalid").show();
        }
        else {
            if ((/^false$/i).test($('div #hiddenLoggedIn').text())) {
                SaveGA($('div #login_submit'));
                $('div #hiddenLoggedIn').text('True');
            }
            //Add One to QuoteCount
            var quoteCount = parseInt($("#" + prefix + "hiddenQuoteCount").text()) + 1;
            $("#" + prefix + "hiddenQuoteCount").text(quoteCount.toString());
            /*
            //open link to create compare quote page
            var webPageID = $(xml).find("webpageid").text();
            location.href = "http://" + location.host + "/WebPage.aspx?WebSiteID=" + getWebSiteID() + "&WebPageID=" + webPageID
            */
            $('.PricingQMDiv').show();
            $("#thank_you_submit").text($(subaruModelsXML).find("#save_quote_thanks").text());
            $('div#thank_you_text').hide();
//            $('#thank_you_text').text($(subaruModelsXML).find('#thank_you_text').text().replace('<model>', $('#dropdownModelTitle').text()));
            $("#thank_you_form").show();
            $("#loginArea").hide();            
        }
    }
    
    function LoggedInSaveQuote() {
        var accIDs = returnSelectedAccessoryIDs();
        
        var queryString = "&ProvinceCode=" + $("#" + prefix + "hiddenPriceProvince").attr("value") +
                "&WebSiteID=" + getWebSiteID() +
                "&QuoteName=" + $("#quote_name").attr("value") +
                "&carID=" + $("#hiddenSelectedCarID").text() +
                "&ownerID=" + $("#dealerID").attr("value") +
                "&colourIndex=" + $("#hiddenSelectedColourIndex").text() +
                "&accessoryID=" + accIDs +
                "&financeCategory=" + $("#hiddenSelectedPurchaseType").text() +
                "&paymentIndex=" + $("#hiddenSelectedPurchaseIndex").text() +
                "&deposit=" + $("#hiddenDeposit").text() +
                "&webPageID=" + getWebPageID();
        $.ajax({
            type: "POST",
            url: "PricingConfig/MyQuote.aspx?LoggedInSaveQuote=Y&LanguageCode=" + $("#" + prefix + "hiddenLanguage").text() + queryString,
            dataType: "xml",
            success: parseLogInXML
        });
    }

    function ForgottenMyQuoteLogIn() {
        $.ajax({
            type: "POST",
            url: "PricingConfig/MyQuote.aspx?Forgotten=Y&username=" + $("#login_email").attr("value") + "&websiteID=" + getWebSiteID() + "&languageCode=" + $("#" + prefix + "hiddenLanguage").text(),
            dataType: "xml",
            success: parseForgottenLogInXML
        });
    }

    function parseForgottenLogInXML(xml) {
        alert($(xml).find("message").text());
    }

    function getFinanceDetails(carID) {
        //Return XML file
        paymentXML = "";
        //alert("PricingConfig/PurchaseOption.aspx?carID=" + carID + "&Province=" + $("#" + prefix + "hiddenPriceProvince").attr("value") + "&msrp=" + $("#hiddenVehiclePrice").text() + "&deposit=" + $("#hiddenDeposit").text() + "&AccTotal=" + $("#hiddenAccTotal").text() + "&AccResTotal=" + $("#hiddenAccResTotal").text() + "&Language=" + $("#" + prefix + "hiddenLanguage").text());
        $.ajax({
            type: "GET",
            url: "PricingConfig/PurchaseOption.aspx?carID=" + carID + "&Province=" + $("#" + prefix + "hiddenPriceProvince").attr("value") + "&msrp=" + $("#hiddenVehiclePrice").text() + 
            "&deposit=" + $("#hiddenDeposit").text() + "&AccTotal=" + $("#hiddenAccTotal").text() + "&AccResTotal=" + $("#hiddenAccResTotal").text() + 
            "&Language=" + $("#" + prefix + "hiddenLanguage").text() + "&WebSiteID=" + getWebSiteID(),
            dataType: "xml",
            success: parseFinanceXML
        });
    }

    function parseFinanceXML(xml) {
        paymentXML = xml;
        //clear first
        $("#lease_options").empty();
        $("#finance_options").empty();

        $(xml).find("PurchaseDetails").each(
            function() {
                $('#purchasingDetailsTitle').text($(this).text());
            }
        );
        $(xml).find("PurchaseOption").each(function() {
            var isLeaseSection = (/lease/i).test($(this).attr("id"));
            
            var showLease = true;
            if ($(this).find("MonPaymentValue").text() == "n/a") {
                showLease = false;
            }
            var selectedTerm = false;
            if ($("#hiddenSelectPurchaseTerm").text() == $(this).attr("id")) {
                selectedTerm = true;
            }
            var purchaseTerm = $(this).attr("id").split("_");

            var monthlyPayment = $(document.createElement("div"));
            monthlyPayment.addClass("monthly_payment")
                        .attr("id", $(this).attr("id"));
            if (selectedTerm && showLease) {
                monthlyPayment.addClass("table_pricing_display_selected");
            }

            var termInputDiv = $(document.createElement("div"));
            termInputDiv.addClass("table_pricing_display")
                        .css("width", "25px")
                        .css("text-align", "right");
            if (selectedTerm && showLease) {
                termInputDiv.addClass("table_pricing_display_selected");
            }
            
            monthlyPayment.addClass('GAPayment');

            if (jQuery.browser.msie) {
                if (selectedTerm && showLease) {
                    var termInput = $(document.createElement("<input type='radio' value='" + $(this).attr("id") + "' name='purchase_input' checked='checked' >"));
                }
                else {
                    if (!showLease) {
                        var termInput = $(document.createElement("<input type='radio' value='" + $(this).attr("id") + "' name='purchase_input' disabled='disabled' >"));
                    }
                    else {
                        var termInput = $(document.createElement("<input type='radio' value='" + $(this).attr("id") + "' name='purchase_input' />"));
                    }
                }
            }
            else {
                var termInput = $(document.createElement("input"));
                termInput.attr("type", "radio")
                .attr('id', 'r_' + $(this).attr('id'))
                        .attr("value", $(this).attr("id"))
                        .attr("name", "purchase_input");
                if (selectedTerm && showLease) {
                    termInput.attr("checked", "checked"); ;
                }
                else {
                    if (!showLease) {
                        termInput.attr("disabled", "disabled");
                    }
                }
            }
//            if (isLeaseSection)
//                termInput.addClass('gaLease');

            var term = $(document.createElement("div"));
            term.addClass("table_pricing_display")
                .addClass('term')
                        .css("width", "30px")
                        .text(purchaseTerm[1]);
            if (selectedTerm && showLease) {
                term.addClass("table_pricing_display_selected");
            }

            var apr = $(document.createElement("div"));
            apr.addClass("table_pricing_display")
                        .css("width", "55px")
                        .text($(this).find("ARPValue").text());
            if (selectedTerm && showLease) {
                apr.addClass("table_pricing_display_selected");
            }

            var payment = $(document.createElement("div"));
            payment.addClass("table_pricing_display")
                        .css("width", "84px")
                        .css("float", "right")
                        .text($(this).find("MonPaymentValue").text());
            if (selectedTerm && showLease) {
                payment.addClass("table_pricing_display_selected");
            }

            //Add Input to div
            termInputDiv.append(termInput);
            monthlyPayment.append(termInputDiv)
                        .append(term)
                        .append(apr)
                        .append(payment);

            var line = $(document.createElement("div"));
            line.addClass("monthly_payment_line");

            //Add to page
            $("#" + purchaseTerm[0].toLowerCase() + "_options").append(monthlyPayment)
                        .append(line);

//            bindPurchaseInput(termInput);
            bindPurchaseInput(monthlyPayment);
            
            if ($('div#lease_options').children().length == 0)
                $('div#lease_options').css({borderBottom:'1px solid #CFCFCF', height:$('div#finance_options').height()-1});
            else
                $('div#lease_options').css({borderBottom:'none', height:'auto'});
            
            if (selectedTerm) {
                termInput.click();
            }
        });
        //Reload Selected Purchase option
        loadPurchaseDetails($("#hiddenSelectPurchaseTerm").text());
        
        $('#CcalcDiscountTitle').hide();
        $('#CcalcDiscountValue').hide();
        loadPurchaseDetails("Cash");
        
        resizeCol();
    }

    function loadPurchaseDetails(monthlyID) {
        //alert("load Purchase Details");
        var showHST = false;
        $(paymentXML).find("PurchaseOption").each(function() {
            if ($(this).attr("id") == monthlyID) {
                $(this).children().each(function() {
                    var id = $(this).attr("id");
                    if (id.match(/HST/i))
                        showHST = true;
                    
                    if (id.match(/Legal/)) {
                        $("#" + id).html($(this).text());
                    }
                    else
                        $("#" + id).text($(this).text());
                    if (id.match(/discount/i))
                        $("#" + id).show();
                });
            }
        });
        
        if (showHST == true) {
            $('div.PST').hide();
            $('div.GST').hide();
            $('div.HST').show();
        }
        else {
            $('div.PST').show();
            $('div.GST').show();
            $('div.HST').hide();
        }
        
        resizeCol();
    }

    function updateTransmission(trim) {
        //Clear Transmission and Dropdown
        clearDropdown("Transmission");
        //Transmission
        var transmission;
        $(modelXML).find("trim").each(function() {
            var transmissionCount = 0;
            if ($(this).attr("carID") == trim) {
                $(this).find("transmission").each(function() {
                    transmissionCount++;
                    transmission = $(this).text();
                    var transmissionName = $(document.createElement("div"));
                    transmissionName.css("vertical-align", "middle")
                                .html(transmission)
                                .attr("id", "transmission_" + $(this).attr("carID"))
                                .attr("class", "sidemenu_select");
                    $(transmissionName).appendTo($("#selectionTransmission"));

                    bindColourSelectImage(transmissionName);
                    
                    var carID = $(this).attr("carID");
                    var hiddenCarID = $("#" + prefix + "hiddenPreSelCarID").text();
                    if ($(this).attr("carID") == $("#" + prefix + "hiddenPreSelCarID").text())
                    {
                         $("#hiddenCarID").html($(this).attr("carID"));
                         $("#interior_swatch1").hide();
                         $("#interior_swatch2").hide();
                         $("#hiddenVehiclePrice").text($(this).attr("msrp"));
                         $("#hiddenSelectedCarID").text($(this).attr("carID"));
                         var msrpFmt = formatCurrency($(this).attr("msrp"), $("#" + prefix + "hiddenLanguage").text());
                         $("#colourPrice").text(msrpFmt);
                         $("#lblVehicleMSRP").text($(subaruModelsXML).find("#lblVehicleMSRP").text());
                         
                        $("#dropdownTransmissionTitle").html(transmission);
                    }
                });
                if (transmissionCount == 1) {
                    $("#dropdownTransmissionTitle").html(transmission);
                    //Update Selected CarID & MSRP hidden fields
                    $("#hiddenSelectedCarID").text(trim);

                    $("#hiddenVehiclePrice").text($(this).find("startingAt").text());
                    //$("#colourPrice").text(formatCurrency($(this).find("startingAt").text(), $("#NewPricing_hiddenLanguage").text()));
                    $("#colourPrice").text(formatCurrency($(this).find("startingAt").text(), $("#" + prefix + "hiddenLanguage").text()));
                    $("#lblVehicleMSRP").text($(subaruModelsXML).find("#lblVehicleMSRP").text());
                    $('div #colourDetail').show();
                    if (!trackedTransmission && $('#' + prefix + 'hiddenPreSelColourID').text() == '')
                        TrackPageView('/virtualpv/buildprice/select/transmission');
                    trackedTransmission = true;
                }
                else {
                    if ($("#" + prefix + "hiddenPreSelCarID").text() == '') {
                        $("#hiddenSelectedCarID").text("");
                        $("#hiddenVehiclePrice").text("0");
                        $('div #colourDetail').hide();
                        //$("#colourPrice").text("");
                    }
                }
                    
                updateColour(trim);
                //Update IsCurrent 
                $("#hiddenIsCurrent").text($(this).find("isCurrent").text());
            }
        });
        if ($("#" + prefix + "hiddenPriceProvince").attr("value") != "") {
            enableDropdown("Transmission");
        }
    }

    function updateColour(trim) {
        //Clear Colour Dropdown
        clearDropdown("Colour");
        var preSelColour = "";
        var colourIndex = 0;
        $(modelXML).find("trim").each(function() {
            if ($(this).attr("carID") == trim) {
                $(this).find("colour").each(function() {
                    if ($("#" + prefix + "hiddenPreSelColourID").text() == $(this).attr("id")) {
                        preSelColour = $(this).attr("name");
                        $("#hiddenSelectedColourIndex").text(colourIndex);
                    }
                    var colourImage = $(document.createElement("div"));
                    //colourImage.css("float", "left")
                    colourImage.addClass('inlineBlock')
                                .html("<img src=\"http://www.subaru.ca/Content/7907/media/General/Specification/" + $(this).attr("id") + ".jpg\" width=\"30\" height=\"15\" />");

                    var colourName = $(document.createElement("div"));
                    //colourName.css("vertical-align", "middle")
                    colourName.addClass('inlineBlock colourDiv')
                                .html($(this).attr("name"));

                    var imageName = $(document.createElement("div"));
                    $(imageName).attr("id", "colour_" + $(this).attr("id") + "_" + colourIndex.toString())
                                .attr("class", "sidemenu_select colourSelect");

                    $(imageName).append(colourImage)
                                .append(colourName)
                                .appendTo($("#selectionColour"));
                    colourIndex++;
                    bindColourSelectImage(imageName);
                });

                $("#colourPower").html($(this).find("horsePower").text() + " @ " + $(this).find("rpm").text());
                $("#colourCargo").html($(this).find("cargo").text() + "L");
                $("#colourSeating").html($(this).find("seats").text());

                $("#model_colour_image").attr("src", "http://www.subaru.ca/Content/7907/Media/General/Thumbnail/" + trim + "_large.jpg");
            }
        });
        if ($("#" + prefix + "hiddenPriceProvince").attr("value") != "") {
            enableDropdown("Colour");
        }

        //Update right screen to show colours
        $("#VehicleThumbnails").hide();
        $("#colour_view").show();
        $("#price_view").hide();
        $("#colours").show();
        if (preSelColour != "") {
            displayColour($("#" + prefix + "hiddenPreSelColourID").text());
            $("#dropdownColourTitle").text(preSelColour);
        }
    }

    function enableDropdown(ddl) {
        $("#dropdown" + ddl + "Title").removeClass("dropdown_title_disabled");
        $("#dropdown" + ddl + "Title").addClass("dropdown_title_enabled");
        $("#dropdown" + ddl + "Arrow").removeClass("dropdown_arrow_disabled");
        $("#dropdown" + ddl + "Arrow").addClass("dropdown_arrow_enabled");
    }

    function disableDropdown(ddl) {
        $("#dropdown" + ddl + "Title").addClass("dropdown_title_disabled");
        $("#dropdown" + ddl + "Title").removeClass("dropdown_title_enabled");
        $("#dropdown" + ddl + "Arrow").addClass("dropdown_arrow_disabled");
        $("#dropdown" + ddl + "Arrow").removeClass("dropdown_arrow_enabled");
    }

    function clearDropdown(ddl) {
        $("#selection" + ddl).empty();
        $("#dropdown" + ddl + "Title").html($(subaruModelsXML).find("#dropdown" + ddl + "Title").text());
    }

    function resetPricing() {
        $("#" + prefix + "hiddenPreSelRange").text("");
        $("#" + prefix + "hiddenPreSelYear").text("");
        $("#" + prefix + "hiddenPreSelCarID").text("");
        $("#" + prefix + "hiddenPreSelColourID").text("");
    }

    function displayDealerLocator(display, includeTitle) {
        if (display == "hide") {
            $("#locatorDiv").hide();
            $("#Pricing_access").css("top", "320px");
            $("#Payments").css("top", "320px");
            $("#dealer_locator_expand").css("background-image", "url('/content/7907/Media/General/Pricing/expand_dealer_loc.jpg')");
            if (includeTitle) {
                $("#dealer_locator_content").hide();
            }
        }
        else {
            $("#locatorDiv").show();
            $("#Pricing_access").css("top", "690px");
            $("#Payments").css("top", "690px");
            $("#dealer_locator_expand").css("background-image", "url('/content/7907/Media/General/Pricing/close_dealer_loc.jpg')");
            if (includeTitle) {
                $("#dealer_locator_content").show();
            }
        }
        resizeCol();
    }

    function ClearAllDropDownLists() {
        //Clear All Dropdown
        clearDropdown("Year");
        disableDropdown("Year");

        clearDropdown("Trim");
        disableDropdown("Trim");

        clearDropdown("Transmission");
        disableDropdown("Transmission");

        clearDropdown("Colour");
        disableDropdown("Colour");
    }

    function HidePaymentDetails() {
        $("#Lease_payment").hide();
        $("#Finance_payment").hide();
        $("#Cash_payment").hide();
    }

    function colourAlternateLines(paymentType) {
        //colour alternate lines on purchase details
        $("#" + paymentType.toLowerCase() + "_payment_details .pricing_description").filter(":visible").filter(":even").addClass("pricing_background");
        $("#" + paymentType.toLowerCase() + "_payment_details .pricing_value").filter(":visible").filter(":even").addClass("pricing_background");
    }

    function translateText(xml) {
        $(xml).find("translations").each(function() {
            $(this).children().each(function() {
                if ($(this).attr("attr") == "text") {
                    $("#" + $(this).attr("id")).text($(this).text());
                }
                else {
                    $("#" + $(this).attr("id")).attr("value", $(this).text());
                }
            });
        });
    }

    function SetColour(carID, colourID) {
        var colourName = "";
        $("#model_colour_image").attr("src", "http://www.subaru.ca/Content/7907/Media/General/Thumbnail/" + carID + "_" + colourID + ".jpg");
        $(modelXML).find("trim").each(function() {
            if ($(this).attr("carID") == carID) {
                $(this).find("colour").each(function() {
                    if ($(this).attr("id") == colourID) {
                        colourName = $(this).attr("name");
                        if ($(this).find("interior").size() == 1) {
                            $("#interior_trim1").attr("src", "http://www.subaru.ca" + $(this).find("interior").attr("image"));
                            $("#interior_name1").text($(this).find("interior").text());
                            $("#interior_swatch2").hide();
                            $("#interior_swatch1").show();
                        }
                        else {
                            if ($(this).find("interior").size() == 2) {
                                $("#interior_trim2").attr("src", "http://www.subaru.ca" + $(this).find("interior:first").attr("image"));
                                $("#interior_name2").text($(this).find("interior:first").text());
                                $("#interior_trim3").attr("src", "http://www.subaru.ca" + $(this).find("interior:last").attr("image"));
                                $("#interior_name3").text($(this).find("interior:last").text());
                                $("#interior_swatch1").hide();
                                $("#interior_swatch2").show();
                            }
                        }
                        return false; // break out
                    }
                });
            }
        });
        return colourName;        
    }
    
    function displayColour(colourID) {
        $("#hiddenColourSelected").text("Y");
        //update car colour
        var carID = $("#hiddenCarID").html();
        var colourName = "";

        $("#hiddenSelectedColourID").text(colourID);

        colourName = SetColour(carID, colourID);
        if (!trackedColour)
            TrackPageView('/virtualpv/buildprice/select/colour');
        trackedColour = true;
        
        //update dropdown list selection
        $("#dropdownColourTitle").html(colourName);
        //hide dropdownselect
        if ($("#selectionColour").is(":visible")) {
            $("#selectionColour").hide();
        }
        //Show pricing at top
        $("#colour_view").hide();
        $("#price_view").show();
        
        $('div #view_spec_insurance').show();
        
        //Update Price
        var msrpFmt = formatCurrency($("#hiddenVehiclePrice").text(), $("#" + prefix + "hiddenLanguage").text());
        $("#price_view_price").text(msrpFmt);
        //Reset Accessories selected
        $("#price_view_acc").text(formatCurrency("0", $("#" + prefix + "hiddenLanguage").text()));
        //Update Total
        $("#price_view_total").text(msrpFmt);
        $("#price_view").show();

        //Show Accessories if transmission has been selected
        if ($("#hiddenSelectedCarID").text() != "" &&
            $('#hiddenLastCarID').text() != $('#hiddenSelectedCarID').text()) {
            if ($('#hiddenSelectedCarID').text() != '')
                $('#hiddenLastCarID').text($('#hiddenSelectedCarID').text());
                        
            getAccessories($("#hiddenSelectedCarID").text());
//            $('#Pricing_access').show();

            //Update Deposit
            var msrp = parseInt($("#hiddenVehiclePrice").text());
            var selectedDeposit = $("#hiddenDeposit").text(); 
            if (selectedDeposit == '') {
                var deposit = parseInt((msrp / 100) * 10);
                $("#downpayment").attr("value", deposit);
                $("#hiddenDeposit").text(deposit);
            }
            else
                checkDeposit();
            //get Monthly Payments;
            getFinanceDetails($("#hiddenSelectedCarID").text());
            if ($("#" + prefix + "hiddenPriceProvince").attr("value") != "") {
                PreselectPayment();
                $("#Payments").show();
            }
            $('.pricingBottomDiv').show();
            
            //getUserLocation();
            //LoadInitialDealer();
        }
    }

    function checkProvinceSet() {
        if ($("#" + prefix + "hiddenPriceProvince").attr("value") == "") {
            disableDropdown("Model");
            disableDropdown("Year");
            disableDropdown("Trim");
            disableDropdown("Transmission");
            disableDropdown("Colour");
        }
    }

    function validateEmail(emailClientId) {
        var emailAddr = $("#" + emailClientId).attr("value");
        var AtPos = emailAddr.indexOf("@");
        var StopPos = emailAddr.lastIndexOf(".");

        if (emailAddr == '') {
            return false;
        }

        if (AtPos == -1 || StopPos == -1) {
            return false;
        }

        if (StopPos < AtPos) {
            return false;
        }

        if ((StopPos - AtPos) == 1) {
            return false;
        }

        return true;
    }

    function getWebSiteID() {
        var url = window.location.href.toUpperCase();
        var websiteID = url.substr(url.indexOf("WEBSITEID="));
        websiteID = websiteID.substr(0, websiteID.indexOf("&"));
        websiteID = websiteID.replace("WEBSITEID=", "");

        if (websiteID == '')
            return $('#hiddenWebSiteID').text();
        return websiteID;
    }

    function getWebPageID() {
        var url = window.location.href.toUpperCase();
        var webpageID = url.substr(url.indexOf("WEBPAGEID="));
        webpageID = webpageID.substr(0, webpageID.indexOf("&"));
        webpageID = webpageID.replace("WEBPAGEID=", "");
        
        if (webpageID == '')
            return $('#hiddenWebPageID').text();
        return webpageID;
    }

    function getProvinceNameString() {
        var provinceName = "";
        $(subaruModelsXML).find("province").each(function() {
            if ($(this).attr("id") == $("#" + prefix + "hiddenPriceProvince").attr("value")) {
                provinceName = $(this).attr("name");
            }
        });
        return provinceName;
    }

    function returnSelectedAccessoryIDs() {
        var accIDs = "";
        $("#pricing_select_accessories").children().each(function() {
            accIDs += $(this).attr("id").replace("selAcc_", "") + ";";
        });

        if (accIDs != "") {
            accIDs = accIDs.substr(0, accIDs.length - 1);
        }

        accIDs = accIDs.replace(/\;/g, "%3b");
        
        return accIDs;
    }

    //----------------------------------------------------------------------
    //Map Functions


    function GetMap() {
        $("#dealer_locator_content").show();

        LoadColon();

        var mapDiv = "mapDiv";
        if (document.getElementById(mapDiv) == null)
            return;

        map = new VEMap(mapDiv);
        map.SetCredentials($('div#bingKey').text());
        
        var position = new VELatLong(62, -97);
        var mapOptions = new VEMapOptions();
        
        if (navigator.userAgent.match(/Gecko/i) && !navigator.userAgent.match(/Firefox/i)) {
            Msn.Drawing.Graphic.CreateGraphic = function(f,b) { return new Msn.Drawing.SVGGraphic(f,b) };
        }
        try {
            map.LoadMap(position, 3, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 0, mapOptions);
        }
        catch (e) {
            alert(e);
        }

        map.AttachEvent("onendzoom", ZoomEndHandler);

        LoadInitialDealer();
        if ($("#" + prefix + "hiddenWebSiteType").text() == "Dealersite Template") {
            //hide prev and next images.
            $("#prevDealer").hide();
            $("#nextDealer").hide();
        }

        if (IsInternetExplorer())
            timerID = setInterval(SetupIE, 333);
        
        $("#dealer_locator_content").hide();        
    }


    function UnloadMap() {
        if (map != null) {
            map.Dispose();
            map = null;
        }
    }

    function IsInternetExplorer() {
        return navigator.userAgent.indexOf('MSIE') != -1;
    }

    function SetupIE() {
        //        var dealerInfo = document.getElementById('dealerInfo');
        //        if (dealerInfo.className.match(/hiddenDealerInfo/)) {
        //            dealerInfo.className = "dealerInfo mappingHeight";
        //            dealerInfo.style.top = -505;
        //            dealerInfo.style.position = "relative";

        clearInterval(timerID);
        timerID = null;
        //        }
    }
    function IECLick() {
        //        var dealerInfo = document.getElementById('dealerInfo');
        //        dealerInfo.className = "dealerInfo mappingHeight";
        //        dealerInfo.style.display = 'block';
    }

    function LoadColon() {
        if (colon != null)
            return;
        //var prefix = document.getElementById('pricingPrefix').value + "_";
        //var lang = document.getElementById(prefix + 'hiddenLanguage').value;
        var lang = $("#" + prefix + "hiddenLanguage").text();
        if (lang == 'en-ca')
            colon = ": ";
        else
            colon = " : ";

        languageCode = lang;
    }


    function LoadXML(url, callback) {
        var xmlrequest = null;
        if (window.XMLHttpRequest) {
            xmlrequest = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            xmlrequest = new ActiveXObject('Microsoft.XMLHTTP')
        }
        else {
            return;
        }

        xmlrequest.onreadystatechange = function() {
            if (xmlrequest.readyState == 4) {
                if (xmlrequest.status == 200) {
                    callback(xmlrequest.responseXML);
                }
            }
        };
        //**Remove**//
        url = url.replace("localhost", "localhost:49795");
        xmlrequest.open("GET", url, true);
        xmlrequest.send(null);
    }

    function LoadInitialDealer() {
        lat = $("#" + prefix + "lat").attr("value");
        lng = $("#" + prefix + "lng").attr("value");

        //alert(lat + ":" + lng);
        
        var dealerID = $("#" + prefix + "presetDealerID").attr("value");
        if (dealerID != null && dealerID != '') {
            $("#mapLoadingIcon").hide();

            //alert("lat:" + lat + "/ Long: " + lng);
            var position = new VELatLong(lat, lng);
            dealer = new VEShape(VEShapeType.Pushpin, position);
            map.AddShape(dealer);
            map.SetZoomLevel(15);
            map.SetCenter(position);
            if (map.GetZoomLevel() <= 9)
                dealer.SetCustomIcon(GetSmallIconURL());
            else
                dealer.SetCustomIcon(GetLargeIconURL());

            var dealerIDElement = document.getElementById('dealerID');
            dealerIDElement.value = dealerID;

            var domain = document.getElementById("domain").value;
            var url = domain + '/Map/2010/DealerFeed.aspx?latitude=' + lat + '&longitude=' + lng + '&maxRadius=' + 2000 + '&numResults=1&Language=' + languageCode + '&pricing=Y';
//            url = domain + 'Map/DealerFeed.aspx?location=' + $("#" + prefix + "dealer_search_input").attr("value") + '&maxRadius=' + 2000 + '&numResults=1&Language=' + languageCode;
            //alert(url);
            LoadDealers(url);
        }
        else {
            var domain = document.getElementById("domain").value;
            var url = domain + '/Map/2010/DealerFeed.aspx?latitude=' + lat + '&longitude=' + lng + '&maxRadius=' + 2000 + '&numResults=3&Language=' + languageCode;
            url = domain + 'Map/2010/DealerFeed.aspx?location=' + $("#" + prefix + "dealer_search_input").attr("value") + '&maxRadius=' + 2000 + '&numResults=3&Language=' + languageCode + '&pricing=Y';
            LoadDealers(url);
        }
    }

    function getUserLocation() {
        var token = $("#VEtoken").attr("value");
        //Use AJAX to load the model?
        //Return XML file
        $.ajax({
            type: "GET",
            url: "PricingConfig/PricingLocation.aspx?location=" + $("#" + prefix + "dealer_search_input").attr("value") + "&token=" + token,
            dataType: "xml",
            success: parseLocationXml
        });
    }

    function parseLocationXml(xml) {
        //Load Lng & Lat
        $("#" + prefix + "lat").attr("value", $(xml).find("lat").text());
        $("#" + prefix + "lng").attr("value", $(xml).find("long").text());
        LoadInitialDealer();
    }


    function LoadDealerInfo(marker) {
        if (marker == null)
            return;

        $("#dealerHeader").text(marker.getAttribute("name"));
        $("#dealerLink").text(marker.getAttribute('href'))
            .attr("href", marker.getAttribute('href'));
        var address = marker.getAttribute('address1') + "<br/>";
        if (marker.getAttribute('address2') != null) {
            address += marker.getAttribute('address2') + ", ";
        }
        address += marker.getAttribute('city') + ", " +
            marker.getAttribute('province') + " " +
            marker.getAttribute('postalCode');

        $("#dealerAddress").html(address);
        $("#dealerPhone").html("T" + colon + marker.getAttribute('phone') +
            "<br/>F" + colon + marker.getAttribute('fax'));

        if (marker.childNodes.length > 0) {
            var hours = null;
            if (IsInternetExplorer())
                hours = marker.childNodes[0];
            else
                hours = marker.childNodes[1];
            hours = hours.getElementsByTagName('time');
            for (var i = 0; i < hours.length; i++) {
                $("#day" + i).text(hours[i].getAttribute('dayName'));
                $("#time" + i).text(hours[i].getAttribute('sales'));
            }
        }

        if ($("#" + prefix + "hiddenWebSiteType").text() != "Dealersite Template") {
            $("#distanceDiv").show();
            $("#distance_total").show();
            $("#distanceDiv").text(" " + marker.getAttribute('distance') + ' km');
        }
        else {
            $("#distanceDiv").hide();
            $("#distance_total").hide();
        }

        $("#dealerID").attr("value", marker.getAttribute('id'));
    }

    function PrevDealer() {
        if (markers == null)
            return;

        $("#nextDealer").show();

        index--;
        if (index <= 0) {
            index = 0;

            $("#prevDealer").hide();
        }

        LoadDealerInfo(markers[index]);
        MoveDealerPin();
    }
    function NextDealer() {
        if (markers == null)
            return;

        $("#prevDealer").show();

        index++;
        if (index >= markers.length - 1) {
            index = markers.length - 1;

            $("#nextDealer").hide();
        }

        LoadDealerInfo(markers[index]);
        MoveDealerPin();
    }

    function MoveDealerPin() {
        var latitude = markers[index].getAttribute('latitude');
        var longitude = markers[index].getAttribute('longitude');
        var position = new VELatLong(latitude, longitude);
        if (dealer == null) {
            dealer = new VEShape(VEShapeType.Pushpin, position);
            map.AddShape(dealer);
            map.SetZoomLevel(15);

            if (map.GetZoomLevel() <= 9)
                dealer.SetCustomIcon(GetSmallIconURL());
            else
                dealer.SetCustomIcon(GetLargeIconURL());
        }
        else {
            dealer.SetPoints(new Array(position));
        }
        map.SetCenter(position);
    }

    function FindDealerships() {
        var domain = document.getElementById("domain").value;
        var address = document.getElementById('address').value;
        if (address == undefined || address == null || address == '') {
            var message = document.getElementById('findErrorMessage').value;
            alert(message);
            return;
        }

        var url = domain + '/Map/2010/DealerFeed.aspx?location=' + address + '&maxRadius=' + 2000 + '&numResults=3&Language=' + languageCode + '&pricing=Y';
        //alert(url);
        LoadDealers(url);
    }

    function LoadDealers(url) {
        var loadIcon = document.getElementById('mapLoadingIcon');
        loadIcon.style.display = "block";

        LoadXML(url, function(data) {
                if (data == null)
                    return;
            var loadIcon = document.getElementById('mapLoadingIcon');
            loadIcon.style.display = "none";

            var dealers = document.getElementById("dealers");
            if (dealers != undefined && dealers != null)
                dealers.value = data;
            rawdata = data;

            markers = data.getElementsByTagName('marker');
            var times = data.getElementsByTagName('hours');
            index = 0;

            LoadDealerInfo(markers[index]);
            MoveDealerPin();
        });
    }

    function GetLargeIconURL() {
        return document.getElementById("logoLarge").value;
    }
    function GetSmallIconURL() {
        return document.getElementById("logoSmall").value;
    }

    function ZoomEndHandler(e) {
        if (dealer == null || map == null)
            return;

        var zoomLevel = map.GetZoomLevel();
        if (zoomLevel <= 14)
            dealer.SetCustomIcon(GetSmallIconURL());
        else
            dealer.SetCustomIcon(GetLargeIconURL());
    }

    function RollOverControls() {
        var controls = document.getElementById("mapControlContainer");
        if (controls == null)
            return;

        if (IsInternetExplorer()) {
            controls.style.filter = "alpha(opacity=60)";
        }
        else {
            controls.style.MozOpacity = 1.0;
            controls.style.opacity = 1.0;
        }

        //    if (parseFloat(controls.style.MozOpacity) <= 1.0)
        //        setTimeout(function() {RollOverControls();}, 10);
    }
    function RollOutControls() {
        var controls = document.getElementById("mapControlContainer");
        if (controls == null)
            return;

        if (IsInternetExplorer()) {
            controls.style.filter = "alpha(opacity=30)";
        }
        else {
            controls.style.MozOpacity = 0.7;
            controls.style.opacity = 0.7;
        }

        //    if (parseFloat(controls.style.opacity) > 0.7)
        //        setTimeout(function() {RollOutControls();}, 10);
    }


});

