﻿//  global variables.
var refineTimeout;
var refineUpdateTime = 500;

$(function () {

    jQuery.fn.extend({

        accordian: function () {
            var accordian = $(this);

            //  bind a function that hides hidden panels. This is typically used to hide
            //  panels that require an item to be saved before it can be edited.
            $(this).bind("hide", function (e) {
                $(this).find("h2.hide").each(function () {
                    $(this).hide();
                    $(this).next("div").hide();
                });
            });

            //  bind a function to show hidden panels.
            $(this).bind("show", function (e) {
                $(this).find("h2.hide").each(function () {
                    $(this).fadeIn();
                });
            });

            //  hide all containers that are not expanded by default and set the expanded
            //  attribute to false.
            $(this).children("h2:not(.expanded)").next("div").hide();

            //  bind events for collapse and expand to all h2 headers.
            $(this).children("h2").bind("collapse", function (e) {
                $(this).removeClass("expanded");
                $(this).next("div").hide();
            });
            $(this).children("h2").bind("expand", function (e) {
                $(this).addClass("expanded");
                $(this).next("div").show();
            });

            //  call the collapse and expand events on click based on the current expanded
            //  attribute.
            $(this).children("h2").click(function () {
                if (!$(this).hasClass("expanded")) {
                    $(this).trigger("expand");
                } else {
                    $(this).trigger("collapse");
                }
            });

        }
    });

    //  a loading animation is played whenever any AJAX activity commences. This is displayed against
    //  the main page heading.
    $("h1").ajaxStart(function () {
        $(this).addClass("ajax");
    });
    $("h1").ajaxStop(function () {
        $(this).removeClass("ajax");
    });

    //  Create the navigation
    $("#navigation ul.top li").hover(
        function () {
            $(this).find("ul.root").show();
        },
        function () {
            $(this).find("ul.root").hide();
        }
    );

    //  Set accordians.
    $(".accordian").accordian();
});

function clearSearch() {

    //  clear the seach box on click if the criteria has not been changed.
    var searchBox = $(".search input");
    if (searchBox.val() == "Search...") searchBox.val("");
}

function cleartext(thisfield, defaulttext) {
    if (thisfield.value == defaulttext) {
        thisfield.value = "";
        thisfield.style.color = "#333333";
    }
}
function recalltext(thisfield, defaulttext) {
    if (thisfield.value == "") {
        thisfield.value = defaulttext;
        thisfield.style.color = "#aaaaaa";
    }
}

function createCustomiseAndBuy() {

    //  this builds the functionality for the customise and buy options such
    //  as accessories and delivery. The price is recalculated on each option
    //  change and retrieved via web service.

    //  call the update when select boxes are changed or inputs clicked.
    $(".customiseandbuy select").change(function() {
        updateCustomiseAndBuy();
    });
    $(".accessories input").click(function () {
        updateCustomiseAndBuy();
    });

    //  call it on start up.
    updateCustomiseAndBuy();
    getLowestFinance();
}

function createRefineGroups() {

    //  handle refinement of categories. Refine groups are determined by
    //  the product option types with FT (or programmed manually).
    
    //  collapsable option groups.
    $(".refinegroup h3").click(function() {
        if ($(this).hasClass("hidden")) {
            $(this).next("div").show();
            $(this).removeClass("hidden");
        } else {
            $(this).next("div").hide();
            $(this).addClass("hidden");
        }
    });
    
    //  togglable option filters.
    $(".refinegroup ul li").click(function() {
        $(this).toggleClass("off");
        clearTimeout(refineTimeout);
        refineTimeout = setTimeout("$('.refine').trigger('update');", refineUpdateTime);
    });

    //  Sorting.
    $(".sortby select").change(function() {
        clearTimeout(refineTimeout);
        refineTimeout = setTimeout("updateRefine(false);", refineUpdateTime);
    });
    
    //  price slider.
    $("#refineprice").slider({
        range: true,
        min: price_min,
        max: price_max,
        step: 50,
        values: [price_min, price_max],
        slide: function(event, ui) {
            $("#refinepriceamount").val('£' + ui.values[0] + ' - £' + ui.values[1]);
        },
        stop: function(event, ui) {
            clearTimeout(refineTimeout);
            refineTimeout = setTimeout("$('.refine').trigger('update');", refineUpdateTime);
        }
    });
    $("#refinepriceamount").val('£' + $("#refineprice").slider("values", 0) + ' - £' + $("#refineprice").slider("values", 1));

    $(".refine").bind("update", function() {
        updateRefine();
    });
}

//  opens spot window?
function openSpot(strURL) {
    var winSpot = window.open(strURL, "moreinfo", "toolbar=0,height=400,width=500,scrollbars=1");
}

//  opens the will it fit window?
function openWillItFit() {
    var winWillItFit = window.open("/help/size-chart.aspx", "willitfit", "toolbar=0,height=400,width=840,scrollbars=1");
}

//  the updateCustomiseAndBuy function is called whenenever a user changes an option or
//  accessory in the customise and buy panel.
function updateCustomiseAndBuy() {
    var product = $(".customiseandbuy").find("input:first").val();
    var options = "";
    var accessories = "";

    //  show calculating message.
    $("span.optionsandaccessories").html("...");
    $("span.delivery").html("...");
    $("span.totalprice").html("...");

    //  get options.
    $(".options select").each(function() {
        options = options + $(this).val() + " , ";
    });
    if (options.length > 0) options = options.substr(0, options.length - 3);

    //  get accessories.
    $(".accessories input").each(function() {
        if ($(this).attr("checked")) {
            accessories = accessories + $(this).closest("span").attr("accessory_id") + " , ";
        }
    });
    if (accessories.length > 0) accessories = accessories.substr(0, accessories.length - 3);

    //  build the JSON string.
    var JSON = "{" +
               " Product_ID : " + product + " , " +
               " ProductOptions : [ " + options + " ] , " +
               " Accessories : [ " + accessories + " ] , " +
               " Delivery_ID : " + $(".delivery select").val() + " " +
               "}";

    //  call the web service passing the product, options, accessories, delivery and
    //  and then update the price.
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Assets/HLD/WebServices/HLD.asmx/CustomiseAndBuy",
        data: JSON,
        dataType: "json",
        success: function (response) {
            var oResponse = eval("(" + response.d + ")");

            //  Update prices.
            $("span.optionsandaccessories").html(oResponse.Data);
            $("span.delivery").html(oResponse.DataTwo);
            $("span.totalprice").html(oResponse.DataThree);

            //  refresh any finance information
            $(".finance-button").each(function () {
                if ($(this).hasClass("on")) {
                    calculateFinance($(this).next("div"));
                }
            });

        },
        error: function (response) {

            //  if an error has occured display for debugging purposes.
            alert(response.responseText);
        }
    });
}

//  the doRefine function calls a web service to update the products displayed. This is
//  called whenever the refine options are changed.
function updateRefine(pageChanged) {
    var category = $(".refine").find("input:first").val();
    var productOptionType;
    var selectedOptions = "";
    var pageIndex = $("#pageindex input:first").val();
    var productsPerPage = $("#productsperpage input:first").val();

    //  if this isn't a change of page then reset page index
    if (pageChanged == null) {
        pageIndex = 1;

        $("#pageindex input:first").val(pageIndex)
    }

    //  clear pagers
    $(".pager").fadeOut();

    //  get the selected option filters and build a JSON
    //  array to send to the web service.
    $(".refine ul").each(function() {
        productOptionType = $(this);
        $(this).find("li:not('.off')").each(function() {
            selectedOptions = selectedOptions + "[ '" + productOptionType.attr("id") + "', '" + $(this).attr("innerHTML") + "' ] , ";
        });
    });
    if (selectedOptions.length > 0) selectedOptions = selectedOptions.substr(0, selectedOptions.length - 3);

    //  build the JSON string.
    var JSON = "{" +
                   " Category_ID : '" + category + "' , " +
                   " PageIndex : '" + pageIndex + "' , " +
                   " ProductsPerPage : '" + productsPerPage + "' , " +
                   " Price_Min : " + $("#refineprice").slider("values", 0) + " , " +
                   " Price_Max : " + $("#refineprice").slider("values", 1) + " , " +
                   " ProductOptions : [ " + selectedOptions + " ] , " +
                   " SortBy : '" + $(".sortby select").val() + "' " +
                   "}";

    //  call the web service passing the category, min and max prices
    //  options and then display the products HTML.
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Assets/HLD/WebServices/HLD.asmx/ProductList",
        data: JSON,
        dataType: "json",
        success: function (response) {
            var oResponse = eval("(" + response.d + ")");

            //  set the product count and product HTML.
            $(".productcount").html(oResponse.Message);
            $("#products").html(oResponse.Data);

            //  set pager
            $(".pager").html(oResponse.DataTwo);
            $(".pager").fadeIn();
        },
        error: function (response) {

            //  if an error has occured display for debugging purposes.
            alert(response.responseText);
        }
    });

}

function changePage(page) {

    //  set the new index
    $("#pageindex input:first").val(page);

    //  update the products
    updateRefine(true);
}

function theRotator() {
    //Set the opacity of all images to 0
    $('div.rotator ul li').css({ opacity: 0.0 });

    //Get the first image and display it (gets set to full opacity)
    $('div.rotator ul li:first').css({ opacity: 1.0 });

    //Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds

    setInterval('rotate()', 6000);

}

function rotate() {
    //Get the first image
    var current = ($('div.rotator ul li.show') ? $('div.rotator ul li.show') : $('div.rotator ul li:first'));

    if (current.length == 0) current = $('div.rotator ul li:first');

    //Get next image, when it reaches the end, rotate it back to the first image
    var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.rotator ul li:first') : current.next()) : $('div.rotator ul li:first'));

    //Un-comment the 3 lines below to get the images in random order

    //var sibs = current.siblings();
    //var rndNum = Math.floor(Math.random() * sibs.length );
    //var next = $( sibs[ rndNum ] );


    //Set the fade in effect for the next image, the show class has higher z-index
    next.css({ opacity: 0.0 })
	.addClass('show')
	.animate({ opacity: 1.0 }, 1000);

    //Hide the current image
    current.animate({ opacity: 0.0 }, 1000)
	.removeClass('show');

};

function calculateFinance(calculator) {
    var JSON = "{" +
                   " 'ProductCode' : '" + calculator.find(".financeproductcode").val() + "' , " +
                   " 'Deposit' : '" + calculator.find(".financedeposit").val() + "' , " +
                   " 'TotalPrice' : '" + $("span.totalprice").html() + "' " +
                   "}";

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Assets/HLD/WebServices/HLD.asmx/FinanceCalculator",
        data: JSON,
        dataType: "json",
        success: function (response) {
            var oResponse = eval("(" + response.d + ")");
            var costOfLoan = oResponse.cost_of_loan;

            if (costOfLoan == "-0.00") costOfLoan = "0.00";

            calculator.find(".finance_monthlypayment").html(oResponse.monthly_repayment);
            calculator.find(".finance_cashprice").html(oResponse.goods_spend);
            calculator.find(".finance_deposittopay").html(oResponse.deposit);
            calculator.find(".finance_loanamount").html(oResponse.loan_amount);
            calculator.find(".finance_loanrepayment").html(oResponse.total_cost);
            calculator.find(".finance_costofloan").html(costOfLoan);
            calculator.find(".finance_totalamountpayable").html((Number(oResponse.total_cost.toString().replace(",", "")) + Number(oResponse.deposit.toString().replace(",", ""))).toFixed(2));
            calculator.find(".finance_numberofmonthlypayments").html(oResponse.term);
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

function getLowestFinance() {
    var JSON = "{" +
                   " 'ProductID' : '" + $(".customiseandbuy").find("input:first").val() + "' " +
                   "}";

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Assets/HLD/WebServices/HLD.asmx/LowestFinance",
        data: JSON,
        dataType: "json",
        success: function (response) {
            var oResponse = eval("(" + response.d + ")");
            
            //  set from html            
            $(".fromprice").html("<span class='normal'>Payments from</span> &pound;<span class='lowestfinance'>" + oResponse.monthly_repayment + "</span> a month");
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

function payOnFinance() {
    var productCode = $("#financetype input:first").val();
    var depositPercentage = $("#financedeposit input:last").val();
    var totalamount = $("#totalamount input:first").val();
    var minimumDeposit = $("#minimumdeposit input:first").val();
    var deposit;

    //  calculate deposit
    deposit = (Number(depositPercentage) / 100) * Number(totalamount);

    //  check validity of chosen finance product
    if (productCode == "") {
        alert("Please select a finance type");

        return;
    }

    //  prepare JSON request
    var JSON = "{" +
                   " 'ProductCode' : '" + productCode + "' , " +
                   " 'Deposit' : '" + deposit + "' , " +
                   " 'TotalPrice' : '" + totalamount + "' " +
                   "}";

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Assets/HLD/WebServices/HLD.asmx/FinanceCalculator",
        data: JSON,
        dataType: "json",
        success: function (response) {
            var oResponse = eval("(" + response.d + ")");

            if (Math.round(Number(oResponse.min_deposit)) < Math.round(Number(minimumDeposit))) {
                if (Math.round(Number(deposit)) < Math.round(Number(minimumDeposit))) {
                    alert("The entered deposit is too low, the minimum deposit value is £" + minimumDeposit);

                    return;
                }
            } else {
                if (Math.round(Number(deposit)) < Math.round(Number(oResponse.min_deposit))) {
                    alert("The entered deposit is too low, the minimum deposit value is £" + oResponse.min_deposit);

                    return;
                }
            }
            if (Math.round(Number(deposit)) > Math.round(Number(oResponse.max_deposit))) {
                alert("The entered deposit is too high, the maximum deposit value is £" + oResponse.max_deposit);

                return;
            }
            if ((Number(totalamount) - Number(deposit)) < 250) {
                alert("Sorry the smallest amount we can provide finance for is £250");

                return;
            }
            if ((Number(totalamount) - Number(deposit)) > 5000) {
                alert("Sorry the largest amount we can provide finance for is £5000");

                return;
            }

            //  set pay4later fields
            $("#financecode input:first").val(productCode);
            $("#financedeposit input:first").val(deposit);

            //  submit form (test/live)
            //  document.forms[0].action = "https://test.pay4later.com/credit_app/";
            document.forms[0].action = "https://secure.pay4later.com/credit_app/";
            document.forms[0].submit();

        },
        error: function (response) {
            alert(response.responseText);
        }
    });
}

$(document).ready(function () {
    $(".datepicker").datepicker(
    {
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        showButtonPanel: true
    });

    $(".finance-button").click(function () {
        var financeOptions = $(this).parent().find("div:first");

        if ($(this).hasClass("on")) {
            financeOptions.hide()

            //  remove any on class
            $(this).removeClass("on");
            $(this).find(".more").html("More Details")
        } else {
            financeOptions.fadeIn(function () {
                calculateFinance($(this).closest("div"));

            });

            //  add on class
            $(this).addClass("on");
            $(this).find(".more").html("Hide")
        }
    });

    $(".financeproductcode").change(function () {
        calculateFinance($(this).closest("div"));
    });
    $(".financedeposit").change(function () {
        calculateFinance($(this).closest("div"));
    });
});


$(document).ready(function() {
    //Show the paging and activate its first link
    $(".paging").hide();
    $(".paging a:first").addClass("active");

    //Get size of the image, how many images there are, then determin the size of the image reel.
    var imageWidth = $(".window").width();
    var imageSum = $(".image_reel img").size();
    var imageReelWidth = imageWidth * imageSum;

    //Adjust the image reel to its new size
    $(".image_reel").css({ 'width': imageReelWidth });

    //Paging  and Slider Function
    rotate = function () {
        var triggerID = $active.attr("rel") - 1; //Get number of times to slide
        var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

        $(".paging a").removeClass('active'); //Remove all active class
        $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

        //Slider Animation
        $(".image_reel").animate({
            left: -image_reelPosition
        }, 2000);

    };

    //Rotation  and Timing Event
    rotateSwitch = function () {
        play = setInterval(function () { //Set timer - this will repeat itself every 7 seconds
            $active = $('.paging a.active').next(); //Move to the next paging
            if ($active.length === 0) { //If paging reaches the end...
                $active = $('.paging a:first'); //go back to first
            }
            rotate(); //Trigger the paging and slider function
        }, 6000); //Timer speed in milliseconds (7 seconds)
    };

    rotateSwitch(); //Run function on launch

    //On Hover
    $(".image_reel a").hover(function () {
        clearInterval(play); //Stop the rotation
    }, function () {
        rotateSwitch(); //Resume rotation timer
    });

    //On Click
    $(".paging a").click(function () {
        $active = $(this); //Activate the clicked paging
        //Reset Timer
        clearInterval(play); //Stop the rotation
        rotate(); //Trigger rotation immediately
        rotateSwitch(); // Resume rotation timer
        return false; //Prevent browser jump to link anchor
    });
});
