﻿//page load
$(document).ready(function(){
    //event handling
    $("#select-product-option-container input").mousedown(function(){
        SelectedOptionChanged(this.value);
    });
    ////////////////
    
    //set option specific stuff
    SelectedOptionChanged();
    
    //initialise the warranty container
    InitialiseWarranty(); 
	
    ////Product images
    //When user click on the image show up the ubox
    $(".ShowUBox").click(function(e){
        triggeruBox();
        e.preventDefault();
    });
    
    //When user click on the thumbnails
    $("#image-controls .thumbnails li img").click(function(e){
        $(".Product-Main-Image").ImageSwitch({Type:"FadeIn", NewImage: $(this).attr("rel")});
        $(".MainImageCaption").html($(this).attr("title"));
        e.preventDefault();
    });
});
////
// Helper Functions //
function RoundToDecimalPlaces(number, dec)
{
    number = Math.round(number*Math.pow(10, dec))/Math.pow(10, dec);
    number += "";
    if (number.indexOf('.') == -1)
    {
        number += ".00";
    }
    else 
    {
        var parts = number.split('.');
        if (parts.length > 1)
        {
            if (parts[1].length == 1)
            {
                number += "0";
            }
        }
    }
    return number;
}
////
var SelectedOptionalExtras = [];
var SelectedServices = [];

//functions
function GetSelectedOption()
{
    //get the ID of the option we want
    var ProductOptionID = -1;
    var checkboxes = $("#select-product-option-container input");
    if (checkboxes == null) return;
    for (var idx = 0, len = checkboxes.length; idx < len; idx++)
    {
        if (checkboxes[idx].checked)
        {
            ProductOptionID = checkboxes[idx].value;
        }
    }
    //now match this up with the product option we want and return the option
    for (var idx = 0, len = ProductOptions.length; idx < len; idx++)
    {
        if (ProductOptions[idx].ProductOptionID == ProductOptionID)
        {
            return ProductOptions[idx];
        }
    }
}

function GetSubOptions(ProductOptionID)
{
    //clear the selected array
    SelectedOptionalExtras = [];
    $(".suboptions").attr("value", "");
    //included ones
    var response = $.ajax(
    {
        type: "GET",
        url: "/ProductPage/AJAX/AJAXSubOptionsIncluded.aspx?ProductOptionID=" + ProductOptionID + "&date=" + Date(),
        complete: function(response)
        { 
            $("#included-extras-table-container").html(response.responseText);
            //hide extra optional extras
            $("#optional-extras-container-extra").css("display", "none");
            //hide extra information cells
            $(".extras-information").hide();
            //set up functions to show info
            $(".included-sub-option").click(function(e) {
                if (e) e.preventDefault();
                var id = this.id.replace(/sub-option-/ig, "");
                if ($("#extras-information-" + id).is(":hidden")) {
                    $("#extras-information-" + id).slideDown("slow");
                }
                else {
                    $("#extras-information-" + id).slideUp("slow");
                }
            });
            $(".included-sub-option-radio-container span input[type=radio]").click(function(e) {
                var name = $(this).attr("name");
                var obj = $("#" + name);
                SelectOptionalExtraChanged(obj);
            });
            //run a check over these new included options so that we pick them all up
            //(i.e. they're automatically 'picked')
            var objs = $(".included-sub-option-checkbox");
            for (var idx = 0, len = objs.length; idx < len; idx++)
            {
                SelectOptionalExtraChanged(objs[idx]);
            }
        }
    });
    //optional ones
    response = $.ajax(
    {
        type: "GET",
        url: "/ProductPage/AJAX/AJAXSubOptionsOptional.aspx?ProductOptionID=" + ProductOptionID + "&date=" + Date(),
        complete: function(response)
        { 
            $("#optional-extras-table-container").html(response.responseText);
            //hide extra optional extras
            $("#optional-extras-container-extra").css("display", "none");
            //hide extra information cells
            $(".extras-information").hide();
            //set up functions to show info
            $(".sub-option").click(function(e) {
                if (e) e.preventDefault();
                var id = this.id.replace(/sub-option-/ig, "");
                if ($("#extras-information-" + id).is(":hidden")) {
                    $("#extras-information-" + id).slideDown("slow");
                }
                else {
                    $("#extras-information-" + id).slideUp("slow");
                }
            });
            $(".sub-option-checkbox").click(function(e) {
                var obj = $(this).get(0);
                SelectOptionalExtraChanged(obj);
            });
            $(".sub-option-radio-container span input[type=radio]").click(function(e) {
                var name = $(this).attr("name");
                var obj = $("#" + name);
                SelectOptionalExtraChanged(obj);
            });
        }
    });
    //delivery options
    response = $.ajax(
    {
        type: "GET",
        url: "/ProductPage/AJAX/AJAXSubOptionsDelivery.aspx?ProductOptionID=" + ProductOptionID + "&date=" + Date(),
        complete: function(response)
        { 
            $("#delivery-details-table-container").html(response.responseText);
        }
    });
}

function CreateShowAllExtrasLink() {
    //create link to toggle hiding on and off
    var ToggleOptionalsEle = document.createElement("div");
    var ToggleLink = document.createElement("a");
    ToggleLink.id = "toggle-optionals-link";
    ToggleLink.innerHTML = "Click here to show more optional extras";
    ToggleLink.href = "#";
    ToggleLink.onclick = function(){
        if ($("#optional-extras-container-extra").is(":hidden")) {
            $("#optional-extras-container-extra").slideDown("slow");
            this.innerHTML = "Click here to hide extra optional extras";
        }
        else {
            $("#optional-extras-container-extra").slideUp("slow");
            this.innerHTML = "Click here to show more optional extras";
        }
        return false;
    }
    ToggleOptionalsEle.appendChild(ToggleLink);
    var OptionalsTableEle = $("#optional-extras-table-container").get(0);
    if (OptionalsTableEle != null)
    {
        OptionalsTableEle.appendChild(ToggleOptionalsEle);
    }
}

function SelectedOptionChanged(CurrentOptionID)
{
    if (CurrentOptionID == null)
    {
        CurrentOptionID = GetSelectedOption().ProductOptionID;
    }
    
    if ($("#product-option-" + CurrentOptionID).attr("checked") != "checked")
    {
        $("#product-option-" + CurrentOptionID).attr("checked", "checked");
    }
    
    //get the upsell link
    var foundOne = false;
    for (var idx = 0, len = ProductOptions.length; idx < len; idx++)
    {
        if (ProductOptions[idx].ProductOptionID == CurrentOptionID)
        {
            //find the next available option if there is one
            for (var jdx = idx + 1, lenj = ProductOptions.length; jdx < lenj; jdx++)
            {
                if (ProductOptions[jdx].available)
                {
                    //this is what we want
                    //get the current option price
                    var idxPrice = ProductOptions[idx].price;
                    //get the 'upgrade' option price
                    var jdxPrice = ProductOptions[jdx].price;
                    //get the difference...
                    var differencePrice = jdxPrice - idxPrice;
                    //...and now make sure its formatted how we want it
                    differencePrice = RoundToDecimalPlaces(differencePrice, 2);
                    var upsellstring = "<a href='#' onclick='SelectedOptionChanged(" + ProductOptions[jdx].ProductOptionID + "); return false;'>Click here to upgrade to the " + ProductOptions[jdx].name + " for an extra &pound;" + differencePrice + "</a>";
                    $("#upgrade-details").html(upsellstring);
                    foundOne = true;
                    break;
                }
            }
            break;
        }
    }
    if (!foundOne) $("#upgrade-details").html("");
    GetSubOptions(CurrentOptionID);
    UpdatePagePrices();
    UpdateUpsellBanner();
}

function SelectOptionalExtraChanged(OptionalExtraEle)
{
    //see if this tickbox is for a radio button group
    //if it is then change the OptionalExtraEle object to the specific button that's checked
    var radioGroupID = "";
    if (RegExp("radio-group-").exec($(OptionalExtraEle).attr("id")) != null)
    {
        radioGroupID = "input[name*=" + $(OptionalExtraEle).attr("id") + "]";
        //enable/disable the radio buttons for this group
        if($(OptionalExtraEle).attr("checked"))
        {
            $(radioGroupID).attr("disabled", "");
        }
        else 
        {
            $(radioGroupID).attr("disabled", "disabled");
        }
    }
    
    //if it's been selected
    if ($(OptionalExtraEle).attr("checked"))
    {
        //if it's a radio group option then get that element so we can look for it in the optionals array
        if (radioGroupID.length != 0)
        {
            OptionalExtraEle = $(radioGroupID + ":checked");
            //make sure itself and none of it's siblings are in the selected array
            //by removing any that are
            var RadioGroup = $(radioGroupID);
            for (var idx = 0; idx < SelectedOptionalExtras.length; idx++)
            {
                for (var jdx = 0, lenj = RadioGroup.length; jdx < lenj; jdx++)
                {
                    if (SelectedOptionalExtras[idx].ID == $(RadioGroup[jdx]).attr("value"))
                    {
                        SelectedOptionalExtras.splice(idx, 1);
                        idx--;
                        break;
                    }
                }
            }
        }
        //look for the option that matches this one selected and add it to the selected list
        for (var idx = 0, len = OptionalExtras.length; idx < len; idx++)
        {
            if (OptionalExtras[idx].ID == $(OptionalExtraEle).attr("value"))
            {
                SelectedOptionalExtras.push(OptionalExtras[idx]);
                break;
            }
        }
    }
    //else we need to remove it from the selected list
    else 
    {
        //if it's a radio group button then check for any elements from that group as there
        //could be some in the SelectedOptionalExtras array
        if (radioGroupID.length != 0)
        {
            OptionalExtraEle = $(radioGroupID);
        }
        //step through the SelectedOptionalExtras array looking for this one
        for (var jdx = 0; jdx < SelectedOptionalExtras.length; jdx++)
        {
            //if this is a radio group, we need to check that none of the group are in the selected list
            if (radioGroupID.length != 0)
            {
                for (var kdx = 0; kdx < OptionalExtraEle.length; kdx++)
                {
                    if (SelectedOptionalExtras[jdx].ID == $(OptionalExtraEle[kdx]).attr("value"))
                    {
                        SelectedOptionalExtras.splice(jdx, 1);
                        idx--;
                        break;
                    }
                }
            }
            else 
            {
                if (SelectedOptionalExtras[jdx].ID == $(OptionalExtraEle).attr("value"))
                {
                    SelectedOptionalExtras.splice(jdx, 1);
                    break;
                }
            }
        }
    }

    //selected suboptions hidden fields
    var idsForAddToBasket = "";
    for (var idx = 0, len = SelectedOptionalExtras.length; idx < len; idx++)
    {
        idsForAddToBasket += SelectedOptionalExtras[idx].ID;
        if (idx < len - 1) idsForAddToBasket += ",";
    }
    $(".suboptions").attr("value", idsForAddToBasket);
    UpdatePagePrices();
}

// When user select or unselect a service checkbox
function SelectServiceChanged(serviceID){
    var serviceSelection = "#service-" + serviceID;
    //If service is checked
    if($(serviceSelection).attr("checked")){
        // find the services from the list of services and add it to the list
        for(var idx=0; idx< Services.length; idx++){
            if(Services[idx].ID == serviceID){
                SelectedServices.push(Services[idx]);
                break;
            }
        }
    } else {
        // find the services from the list of services and remove it from the list
        for(var idx=0; idx< SelectedServices.length; idx++){
            if(SelectedServices[idx].ID == serviceID){
                SelectedServices.splice(idx, 1);
                break;
            }
        }        
    }
    var selectedServicesList = "";
    for(var idx =0;idx<SelectedServices.length; idx++){
        selectedServicesList += "," + SelectedServices[idx].ID;
    }
    selectedServicesList = selectedServicesList.substr(1, selectedServicesList.length-1);
    $("#services-values").val(selectedServicesList);
    UpdatePagePrices();
}

function UpdatePagePrices()
{   
    //add up the sub option prices
    var SubOptionTotal = 0.00;
    for (var idx = 0, len = SelectedOptionalExtras.length; idx < len; idx++)
    {
        SubOptionTotal += SelectedOptionalExtras[idx].price;
    }
    // Add up the service prices as well
    for (var idx =0; idx < SelectedServices.length; idx++){
        SubOptionTotal += SelectedServices[idx].price;
    }
    //work out the total price box text
    var ProductOption = GetSelectedOption();
    var totalPrice = (Math.round((ProductOption.price + SubOptionTotal)*100)/100);
    //its possible at this point that totalPrice may have less decimal places than we want, so fix it
    totalPrice += "";
    //if we have a . in there...
    if (totalPrice.indexOf(".") != -1)
    {
        //if there is only one number after the . then add a 0
        if (totalPrice.split(".")[1].length == 1)
        {
            totalPrice += "0";
        }
    }
    //no . so just add .00 to the end of the price
    else 
    {
        totalPrice += ".00";
    }
    var totalPriceBox = "";
    if (SelectedOptionalExtras.length == 0)
    {
        totalPriceBox = "<span id='total'>Total Price: &pound;" + totalPrice + "</span>\n";
    }
    else 
    {
        totalPriceBox = "<span id='total'>Total Price: &pound;" + totalPrice + " (with extras)</span>\n";
    }
    if (ProductOption.onSale)
    {
        var difference = ProductOption.wasPrice - ProductOption.price;
        totalPriceBox += "<span id='saving'>(You Save &pound;" + difference + ")</span>";
    }
    totalPriceBox += "<span id='includes'>Price includes VAT &amp; FREE <a href='#delivery-information-container' onclick='doDeliveryPopupLink(); return false;'>delivery*</a> to most of mainland GB";
    totalPriceBox += "<br />Some postcodes may have <a href='#delivery-information-container' onclick='doDeliveryPopupLink(); return false;'>additional delivery times</a></span>"
    $("#total-price-container").html(totalPriceBox);
    
    
    //update the promotion prices
    if (ProductOption.price < 100.00) {
        $("#promotion-tag-container").hide();
    }
    else {
        var promotionPrice = parseFloat(totalPrice) - (0.05 * parseFloat(totalPrice));
        promotionPrice = (Math.round(promotionPrice*100)/100) + "";
        if (promotionPrice.indexOf(".") == -1) promotionPrice += ".00";
        else {
            if (promotionPrice.split(".")[1].length == 1) promotionPrice += "0";
        }
        $("#promotion-price").html(promotionPrice);
        var promotionSaving = 0.05 * parseFloat(totalPrice);
        promotionSaving = (Math.round(promotionSaving*100)/100) + "";
        if (promotionSaving.indexOf(".") == -1) promotionSaving += ".00";
        else {
            if (promotionSaving.split(".")[1].length == 1) promotionSaving += "0";
        }
        $("#promotion-saving").html(promotionSaving);
        $("#promotion-tag-container").show();
    }
}

function UpdateUpsellBanner()
{
    var ProductOptionID = GetSelectedOption().ProductOptionID;
    var response = $.ajax(
    {
        type: "GET",
        url: "/ProductPage/AJAX/AJAXUpsellbanner.aspx?ProductOptionID=" + ProductOptionID,
        complete: function(response)
        { 
            $("#upsell-banner-container").html(response.responseText);
        }
    });
}

function UpdatePAForOption(){
    var ProductOptionID = $("#choosesize1").val();
    $.ajax({
        type: "GET",
        dataType: "html",
        url: "/ProductPage/AJAX/AJAXPackagingAndAssembly.aspx?ProductOptionID=" + ProductOptionID,
        success: function(data){
            $("#packaging-and-assembly-container").html(data);
        }
    });
}

function InitialiseWarranty()
{
    //update the warranty summary box with a link to the full warranty
    var warrantySummary = $("#warranty-summary").html();
    warrantySummary += "<p>Click <a href='#' onclick='toggleFullWarranty(); return false;'>here</a> to view the full warranty description</p>";
    $("#warranty-summary").html(warrantySummary);
    
    //make the warranty image link bring this new full summary too
    $("#warranty-logo-main").click(function(e){
        toggleFullWarranty();
        e.preventDefault();
    });
    
    //and hide the full warranty so we can bring it up with the click
    $("#warranty-full").css("display", "none");
}

function toggleFullWarranty()
{
    var curDisplay = $("#warranty-full").css("display");
    if (curDisplay == "none")
    {
        $("#warranty-full").css("display", "block");
    }
    else
    {
        $("#warranty-full").css("display", "none");
    }
}

function showDeliveryPopup(deliveryPage) {
    if ($("#DeliveryInformation").get(0) != null) {
        showRyMacBox("DeliveryInformation");
    }
    else 
    {
        var deliveryPageUrl = "/DeliveryInformation/" + deliveryPage + ".aspx";
        $.ajax({
            type: "GET",
            url: deliveryPageUrl,
            success: function(data, status) {
                var deliveryMacboxContainer = document.createElement("div");
                $(deliveryMacboxContainer).attr("id", "delivery-area-info");
                $(deliveryMacboxContainer).append(data);
                $("body").append(deliveryMacboxContainer);
                var deliveryMacBox = new RyMacBox("DeliveryInformation", "html|delivery-area-info", 700, 1, $("#delivery-details-table-container").get(0), {}, {}, function() { showRyMacBox("DeliveryInformation"); }, true);
                $("#delivery-ajax-info div").show();
            },
            error: function(ajaxObj, status, error) {
                
            }
        });
    }
}

function doDeliveryPopupLink() {
    if (getStoreID() == 3) {
        var link = $("#free-delivery-popup-link");
        showDeliveryPopup($(link).attr("rel"));
    }
    else {
        window.location = "/delivery";
    }
}

function showAssemblyPopup() {
    if ($("#AssemblyInformation").get(0) != null) {
        showRyMacBox("AssemblyInformation");
    }
    else {
        var assemblyPageUrl = "/assembly/assembly-popup.aspx";
        $.ajax({
            type: "GET",
            url: assemblyPageUrl,
            success: function(data, status) {
                var assemblyMacboxContainer = document.createElement("div");
                $(assemblyMacboxContainer).attr("id", "assembly-info");
                $(assemblyMacboxContainer).append(data);
                $("body").append(assemblyMacboxContainer);
                var assemblyMacBox = new RyMacBox("AssemblyInformation", "html|assembly-info", 500, 1, $("#delivery-details-table-container").get(0), {}, {}, function() { showRyMacBox("AssemblyInformation"); }, true);
            },
            error: function(ajaxObj, status, error) {
                
            }
        });
    }
}