﻿$(function() {
    $("#PayCalculatorCalculateButton").click(function() { CalculateEstimatedPayment(); });
    $("#VehicleMediaTabs").tabs({ ajaxOptions: { async: false }, cache: true });
    $("div[id^='VehicleMediaTabs-']").each(function() { if ($(this).attr("hasContent") == "False") { $("#VehicleMediaTabs").tabs('disable', $(this).attr("index")); } });
    $("#VehicleDetailTabs").tabs();
    $("div[id^='VehicleDetailTabs-']").each(function() { if ($(this).attr("hasContent") == "False") { $("#VehicleDetailTabs").tabs('disable', $(this).attr("index")); } });
    $(".mediaPlugin").media();
    $('#PaymentCalculatorDialog').dialog({
        autoOpen: false,
        bgiframe: true,
        width: 600,
        height: 300,
        modal: true,
        draggable: false,
        resizable: false
    });
    $("#VehicleListFilters > select").change(function() { ApplyVehicleListFilters(); });
    $("#SortBy").change(function() { SortInventory($("#SortBy option:selected").attr("title"), $("#SortBy option:selected").val()); });
    $("#StockNumberNew").autocomplete('/Inventory/StockNumbersNew',
            {
                width: 80,
                dataType: 'json',
                parse: function(data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].StockNumber, result: data[i].StockNumber };
                    }
                    return rows;
                },
                formatItem: function(item) { return item.StockNumber; }
            }
        )
        .result(function(event, item) { location.href = item.Url });
    $("#StockNumberUsed")
        .autocomplete('/Inventory/StockNumbersUsed',
            {
                width: 80,
                dataType: 'json',
                parse: function(data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].StockNumber, result: data[i].StockNumber };
                    }
                    return rows;
                },
                formatItem: function(item) { return item.StockNumber; }
            }
        )
        .result(function(event, item) { location.href = item.Url });
    $("#ConfiguratorStyles").change(function() { OnStyleSelect(); });
    $("#ChangeConfiguratorStyleButton").hide().click(function() { ShowStyleSelect(); });
    $("#ViewDetailsButton").hide();
});

var sortField = '';
var sortDirection = '';
function ApplyVehicleListFilters() {
    var inventoryType = $("#InventoryType").val();
    var year = $("#YearFilter option:selected").val();
    var make = $("#MakeFilter option:selected").val();
    var model = $("#ModelFilter option:selected").val();
    var price = $("#PriceFilter option:selected").val();
    if (year.length <= 0)
        year = 0;
    if (make.length <= 0)
        make = "none";
    if (model.length <= 0)
        model = "none";
    if (price.length <= 0)
        price = 0;
    var url = '/Inventory/' + inventoryType;
    make = make.replace(/ /g, "%20");
    make = make.replace(/&/g, "%26");
    model = model.replace(/ /g, "%20");
    model = model.replace(/&/g, "%26");
    url += '/' + year + '/' + make + '/' + model + '/' + price;
    var inventoryType = $("#InventoryType").val();
    if (inventoryType.toLowerCase() == "used") {
        var certified = "none";
        if ($("#CertifiedFilter").is(":checked"))
            certified = "yes";
        url += '/' + certified;
    }
    if (sortField.length > 0)
        url += '/' + sortField + '/' + sortDirection;
    $.blockUI({ message: '<h2 class="ProcessingMessage"><span class="ProcessingGlyph"></span> Applying filters...</h2>' }); 
    $("#InventoryList").load(url, null, onFiltersApplied);
}
function SortInventory(field, direction) {
    sortField = field;
    sortDirection = direction;
    ApplyVehicleListFilters();
}
function onFiltersApplied() { $.unblockUI(); }
function ConvertEmptyToZero(value) {
    return (value == "") ? 0 : value;
}
function CalculateEstimatedPayment() {
    $("#PayCalculatorErrors").text();
    $("#PayCalculatorErrors").removeClass("PayCalculatorErrors");
    var purchasePrice = parseFloat(ConvertEmptyToZero($("#PayCalculatorPurchasePrice").val()));
    var taxFee = parseFloat(ConvertEmptyToZero($("#PayCalculatorTax").val()));
    var downPayment = parseFloat(ConvertEmptyToZero($("#PayCalculatorDownPayment").val()));
    var tradeInValue = parseFloat(ConvertEmptyToZero($("#PayCalculatorTradeInValue").val()));
    var tradeInPayOff = parseFloat(ConvertEmptyToZero($("#PayCalculatorTradeInPayoff").val()));
    var interestRate = parseFloat(ConvertEmptyToZero($("#PayCalculatorInterestRate").val()));
    var loanTerm = parseFloat(ConvertEmptyToZero($("#PayCalculatorPaymentTerm").val()));
    if (
    isNaN(purchasePrice) ||
    isNaN(taxFee) ||
    isNaN(downPayment) ||
    isNaN(tradeInValue) ||
    isNaN(tradeInPayOff) ||
    isNaN(interestRate) ||
    isNaN(loanTerm)
    ) {
        $("#PayCalculatorErrors").text("You must complete all fields with numeric values.");
        $("#PayCalculatorErrors").addClass("FormErrorMessage");
    }
    else {
        var numPayments = parseInt(loanTerm);
        var actualLoanAmt = purchasePrice + taxFee + tradeInPayOff - downPayment - tradeInValue;
        if (interestRate == 0) interestRate = 0.0001;
        interestRate = interestRate / 1200;
        var monthlyPayment =
        (actualLoanAmt * (
        Math.pow((1 + interestRate), numPayments)
        )) / ((1 + interestRate) * ((
        (
        Math.pow((1 + interestRate), numPayments)
        )
        - 1) / interestRate));
        var smonthlyPayment = '$' + monthlyPayment.toFixed(2);
        var sactualLoanAmt = '$' + actualLoanAmt.toFixed(2);
        $("#PayCalculatorMonthlyPaymentAmount").text(smonthlyPayment);
        $("#PayCalculatorTotalFinancedAmount").text(sactualLoanAmt);
    }
    return false;
}

function OnStyleSelect() {
    var styleId = $("#ConfiguratorStyles option:selected").val();
    if (styleId) {
        $("#ConfiguratorStyles").hide();
        $("#ConfiguratorStyleName").text($("#ConfiguratorStyles option:selected").text());
        $("#ConfiguratorStyleName").show();
        $("#ChangeConfiguratorStyleButton").show();
        $("#ConfiguratorVehicleSettingsBlock").load("/Configurator/Vehicle/" + styleId, null, OnConfiguratorVehicleUpdated);
    }
}

function ShowStyleSelect() {
    $("#ConfiguratorStyles").show();
    $("#ConfiguratorStyleName").text("");
    $("#ConfiguratorStyleName").hide();
    $("#ChangeConfiguratorStyleButton").hide();
}

function OnConfiguratorVehicleUpdated() {
    $("div[id^=ExteriorColor-]").click(function() { SelectExteriorColor(this) })
        .hover(
            function() { $("#HighlightedExteriorColor").text($(this).attr("title")) },
            function() { $("#HighlightedExteriorColor").text("") }
            )
        .each(function() { if ($(this).attr("selected") == "True") { $(this).addClass("ColorSwatchSelected"); } });
    $("div[id^=InteriorColor-]").click(function() { SelectInteriorColor(this) })
        .each(function() { if ($(this).attr("selected") == "True") { $(this).addClass("InteriorColorSwatchSelected"); $(this).removeClass("InteriorColorSwatchNotSelected"); } });
    $("input[id^=Option-]").click(function() { ProcessVehicleOptionSelect(this.value); });
    $("#ConfiguratorPriceSummary").load("/Configurator/PriceSummary");
    $("#ViewDetailsButton").show().click(function() { location.href = '/Inventory/Vehicle/' + year + '/' + make + '/' + model; });
    $("#ConfiguratorPriceDetailsBlock").show();
    $.unblockUI();
}

function SelectExteriorColor(colorSwatchElement) {
    if ($(colorSwatchElement).attr("selected") == "True")
        return;
    var styleId = $("#ConfiguratorStyles option:selected").val();
    var optionCode = $(colorSwatchElement).attr("optionCode");
    ProcessVehicleOptionSelect(optionCode);
}

function SelectInteriorColor(colorSwatchElement) {
    if ($(colorSwatchElement).attr("selected") == "True")
        return;
    var optionCode = $(colorSwatchElement).attr("optionCode");
    ProcessVehicleOptionSelect(optionCode);
}

function ProcessVehicleOptionSelect(optionCode) {
    $.blockUI({ message: '<h2 class="ProcessingMessage"><span class="ProcessingGlyph"></span> Configuring...</h2>' }); 
    $("#ConfiguratorVehicleSettingsBlock").load("/Configurator/ToggleOption/" + optionCode, null, OnConfiguratorVehicleUpdated);
}
