﻿/* Copyright © Website Engineers Limited */

/* Car Search Details */

var ControlPrefix = "ctl00_ContentCarSearchDetails_";
var Interval = "month";
var Currency = "GBP";

var OriginalTotalAmount;
var OriginalDeposit;
var OriginalCostNew;
var OriginalSaving;

jQuery(document).ready(function() {

    $("#Tabs").tabs({ fx: { opacity: 'toggle'} });
    $("#SpecificationTabs").tabs({ fx: { opacity: 'toggle'} });

    $(".PicturePlaceholder").hide();

    $(".Protection .Flash").html(embedFlash('Diamondbrite', '/images/car_search/details/diamond_brite.swf', 150, 100));
    $(".Protection #YouTube1").html(embedYouTube('http://www.youtube.com/v/opNx9jmv_N4&hl=en_GB&fs=1&', 425, 344));
    $(".Protection #YouTube2").html(embedYouTube('http://www.youtube.com/v/MWOYrdSc9Rs&hl=en_GB&fs=1&', 425, 344));
    $(".Protection #YouTube3").html(embedYouTube('http://www.youtube.com/v/TOSgK_4IRu0&hl=en_GB&fs=1&', 425, 344));
    $(".Protection #YouTube4").html(embedYouTube('http://www.youtube.com/v/FWMG84iw47w&hl=en_GB&fs=1&', 425, 344));

    EnableAddressSelection("#ctl00_ContentCarSearchDetails_", ".TestDrive");
    EnableAddressSelection("#ctl00_ContentCarSearchDetails_Contact", ".Contact");

    $(".Thumbnails img").each(function(i, val) {
        $(val).mouseout(function() { $("#SlideShow").cycle({ fx: 'fade', speed: 900, timeout: 3000, pause: 1, startingSlide: i }); $(".PicturePlaceholder").hide(); $("#SlideShow").show(); });
        $(val).mouseover(function() { $("#SlideShow").cycle('pause'); $("#SlideShow").hide(); $(".PicturePlaceholder").attr("src", $(this).attr("src")); $(".PicturePlaceholder").show(); });
    });

    $("#ctl00_ContentCarSearchDetails_Salesman").change(
        function() {
            $.ajax({
                type: "POST",
                url: "/admin_service.asmx/Customers",
                data: "&SalesmanID=" + $("#ctl00_ContentCarSearchDetails_Salesman option:selected").val(),
                dataType: "xml",
                success: function(data, statusText) {
                    AjaxSucceededSalesman(data, statusText);
                },
                error: AjaxFailed
            });
        }
    );

    $("#ctl00_ContentCarSearchDetails_TestDriveDay").change(
        function() {
            $.ajax({
                type: "POST",
                url: "/opening_hours_service.asmx/TestDriveTimes",
                data: "&Date=" + $("#ctl00_ContentCarSearchDetails_TestDriveDay option:selected").val(),
                dataType: "xml",
                success: function(data, statusText) {
                    AjaxSucceededTestDriveDay(data, statusText);
                },
                error: AjaxFailed
            });
        }
    );

    $("#ctl00_ContentCarSearchDetails_ContactSalesman").change(
        function() {
            $.ajax({
                type: "POST",
                url: "/admin_service.asmx/Customers",
                data: "&SalesmanID=" + $("#ctl00_ContentCarSearchDetails_ContactSalesman option:selected").val(),
                dataType: "xml",
                success: function(data, statusText) {
                    AjaxSucceededContactSalesman(data, statusText);
                },
                error: AjaxFailed
            });
        }
    );

    $("#" + ControlPrefix + "Term").keydown(function(event) { DisableFormSubmit(event) });
    $("#" + ControlPrefix + "Deposit").keydown(function(event) { DisableFormSubmit(event) });

    OriginalTotalAmount = $("#TotalAmount").text();
    OriginalDeposit = $("#FinanceDeposit").text();
    OriginalCostNew = $("#CostNew").text();
    OriginalSaving = $("#Saving").text();



    $("#" + ControlPrefix + "GBP").click(

            function() {
                Currency = "GBP";
                DisplayPrices();
            }

        );

    $("#" + ControlPrefix + "Euros").click(

            function() {
                Currency = "EURO";
                DisplayPrices();
            }

        );

    $("#" + ControlPrefix + "Monthly").click(

            function() {
                Interval = "month";
                DisplayPrices();
            }

        );

    $("#" + ControlPrefix + "Weekly").click(

            function() {
                Interval = "week";
                DisplayPrices();
            }

        );

    $("#Calculate").click(

            function() {
                DisplayPrices();
            }

        );

});

function AjaxSucceededSalesman(data, statusText) {  
    $("#ctl00_ContentCarSearchDetails_Customer").empty();
    $("#ctl00_ContentCarSearchDetails_Customer").append('<option value="">Please select</option>');
    $('Customer', data).each (
        function(i) { 
            $("#ctl00_ContentCarSearchDetails_Customer").append('<option value="' + $(this).find("CustomerID").text() + '">' + $(this).find("Name").text() + '</option>');
        }
    );
}

function AjaxSucceededTestDriveDay(data, statusText) {
    $("#ctl00_ContentCarSearchDetails_TestDriveTime").empty();
    $('Time', data).each(
        function(i) {
            $("#ctl00_ContentCarSearchDetails_TestDriveTime").append('<option value="' + $(this).find("Value").text() + '">' + $(this).find("Display").text() + '</option>');
        }
    );
}  

function AjaxSucceededContactSalesman(data, statusText) {  
    $("#ctl00_ContentCarSearchDetails_ContactCustomer").empty();
    $("#ctl00_ContentCarSearchDetails_ContactCustomer").append('<option value="">Please select</option>');
    $('Customer', data).each (
        function(i) { 
            $("#ctl00_ContentCarSearchDetails_ContactCustomer").append('<option value="' + $(this).find("CustomerID").text() + '">' + $(this).find("Name").text() + '</option>');
        }
    );
}  

function AjaxFailed(result) {  
    alert ("Error: " + result);
}

function EnableAddressSelection(Prefix, ParentClass)
{     
    $(Prefix + "AddressSelection").hide();
    $(ParentClass + " .PersonalDetails").hide();

    $(Prefix + "AddressSelection").change( function() {
        var GetAddressesUrl = "http://services.postcodeanywhere.co.uk/json.aspx?action=fetch&id="+$(Prefix + "AddressSelection option:selected").val()+"&account_code=JFTC111112&license_code=TM37-RP67-XW14-MB12&machine_id=&callback=?";
        $.getJSON(GetAddressesUrl, function(data) { 
            $.each(data, function(i, item) {
                if (typeof(item.error_number) == "undefined")
                {                      
                    $(Prefix + "AddressSelection").hide("slow");
                    $(Prefix + "Address1").val(item.line1);
                    $(Prefix + "Address2").val(item.line2 + " " + item.line3 + " " + item.line4 + " " + item.line5 );
                    $(Prefix + "Town").val(item.post_town);
                    $(Prefix + "County").val(item.county);
                    
                    $(ParentClass + " .PersonalDetails").show("slow");
                }
                else
                {
                    //alert(item.message);
                }
            });
        });
    });

    $(Prefix + "GetAddresses").click(function(){
        var GetAddressesUrl = "http://services.postcodeanywhere.co.uk/json.aspx?action=lookup&type=by_postcode&postcode="+$(Prefix + "Postcode").val()+"&account_code=JFTC111112&license_code=TM37-RP67-XW14-MB12&machine_id=&callback=?";
        $.getJSON(GetAddressesUrl, function(data) { 

            $(Prefix + "AddressSelection").hide();
            $(Prefix + "AddressSelection").empty();
    
                $.each(data, function(i, item) {
                    if (typeof(item.description) != "undefined")
                    {
                        $(Prefix + "AddressSelection").append('<option value="' +item.id+ '">' +item.description+ '</option>');
                    } else 
                    { 
                        $(Prefix + "AddressSelection").append('<option value="">No Addresses Found - Please Try Again</option>');
                    }
                });
   
            $(Prefix + "AddressSelection").show("slow");
        
        });
        return false;
    });
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function DisableFormSubmit(event) {
    if (event.keyCode == 13 || e.which == 13) {
        DisplayPrices();
        return false;
    }
}

function DisplayPrices() {
    $("#Display").slideUp("fast", function() { GetFinancePrice(); });
}

function GetFinancePrice() {
    try {
        $("#FinancePayment").text("");
        $("#Interval").text("");

        $.ajax({
            type: "POST",
            url: "/finance_service.asmx/CalculatePrices",
            data: "&TotalAmount=" + OriginalTotalAmount + "&Term=" + $("#" + ControlPrefix + "Term").val() + "&Deposit=" + $("#" + ControlPrefix + "Deposit").val().replace(/,/g, "").replace(/£/g, "").replace(/€/g, "") + "&CostNew=" + OriginalCostNew + "&Saving=" + OriginalSaving + "&Currency=" + Currency,
            dataType: "xml",
            success: function(data, statusText) {
                AjaxSucceeded(data, statusText);
            },
            error: AjaxFailed
        });

    }
    catch (e) {
        alert(e.message);
    }
}

function AjaxSucceeded(data, statusText) {
    try {

        switch (Currency) {
            case "GBP":
                $(".DynamicCurrency").text("£");
                break;
            case "EURO":
                $(".DynamicCurrency").text("€");
                break;
        }

        $("AjaxReturnItem", data).each(

            function() {
                switch ($(this).find("Key").text()) {
                    case "FinancePayment":
                        if (Interval == "month") {
                            $("#FinancePayment").text(parseInt($(this).find("Value").text()));
                            $("#Interval").text("month");
                        }
                        else {
                            $("#FinancePayment").text(parseInt($(this).find("Value").text() / 4));
                            $("#Interval").text("week");
                        }
                        break;

                    case "CostNew":
                        $("#CostNew").text(addCommas(parseInt($(this).find("Value").text())));
                        break;

                    case "Saving":
                        $("#Saving").text(addCommas(parseInt($(this).find("Value").text())));
                        break;

                    case "Deposit":
                        $("#FinanceDeposit").text(addCommas(parseInt($(this).find("Value").text())));
                        break;

                    case "TotalAmount":
                        $("#TotalAmount").text(addCommas(parseInt($(this).find("Value").text())));
                        break;
                }
            }

        );
        $("#Display").slideDown("slow");

    }
    catch (e) {
        alert(e.message);
    }
}  

/* End */
