﻿//  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 li").hover(
        function() {
            $(this).find("ul").show();
        },
        function() {
            $(this).find("ul").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();
}

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("$('.refine').trigger('update');", 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=500,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);
            
        },
        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() {
    var category = $(".refine").find("input:first").val();
    var productOptionType;
    var selectedOptions = "";

    //  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 + " , " +
                   " 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);
        },
        error: function(response) {

            //  if an error has occured display for debugging purposes.
            alert(response.responseText);
        }
    });

}