﻿// 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;
}
////

function GetSelectedOption() {
    //get the ID of the option we want
    var ProductOptionID = $("input[name=optionId]:checked").attr("id");
    ProductOptionID = ProductOptionID.replace(/product-option-/ig, "");
    
    //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].ID == ProductOptionID) {
            return ProductOptions[idx];
        }
    }
    return null;
}

function SelectedOptionChanged(CurrentOptionID) {
    var firstLoad = false;
    if (CurrentOptionID == 0) {
        CurrentOptionID = null;
        firstLoad = true;
    }
    
    var anyAvailable = false;
	for (var idx = 0; idx < ProductOptions.length; idx++) {
	    if (ProductOptions[idx].available) {
	        anyAvailable = true;
	        break;
	    }
	}
	if (!anyAvailable) {
	    $("#treatment-options").hide();
	    $("#optional-extras").hide();
	    $("#delivery-details").hide();
	    $("#pricing-container").hide();
	}
	else {
        //clear the SelectedOptionalExtras and SelectedServices arrays
        SelectedOptionalExtras = [];
        SelectedServices = [];
        
        //get the currently selected option
        if (CurrentOptionID == null) {
            CurrentOptionID = GetSelectedOption().ID;
        }
        
        //make sure this option is actually selected
        if ($("#product-option-" + CurrentOptionID).attr("checked") != "checked") {
            $("#product-option-" + CurrentOptionID).attr("checked", "checked");
        }
        
        //set the parent row to selected
        $(".option-row").removeClass("selected");
        $("#product-option-" + CurrentOptionID).parent().addClass("selected");
                
       $("#hos-20m-tng").css("left", 580).delay(10000).queue(function () {
            $(this).css("left", -999999);
         
        
        $(this).dequeue();}).delay(1000).queue(function () {
            $(this).css("left", -999999);$(this).dequeue();
        });
      
        // Change the upsell list for the slider
	    $("#up-sell-slider #slider-body .displaying").addClass("hidden");
	    $("#up-sell-slider #slider-body .displaying").removeClass("displaying");
	    $("#up-sell-slider #slider-body #up-sale-" + CurrentOptionID).removeClass("hidden").addClass("displaying");
    	
	    //reset the loading images on the dynamic containers
	    var loadingImgStr = "<span class='section-no'></span><img class=\"loading-image\" src=\"/assets/images/loading.gif\" />";
	    $("#treatment-options").html(loadingImgStr);
	    $("#optional-extras").html(loadingImgStr);
	    $("#delivery-details").html(loadingImgStr);
	    $("#optional-services").remove();
    	
        //get the sub options
        GetSubOptions();
        UpdatePagePrices();
        GetInstallationForm();
    	
        //adjust any other dynamic content that depends on the selected option
        updateDimensionValues(CurrentOptionID);
        dimensionOptionChanged(CurrentOptionID);
        technicalSpecSelected(CurrentOptionID);
        if((!firstLoad)&&(useOptionImage)) {
            selectOptionThumbnail(CurrentOptionID);
        }
        updateAssemblyInfo();
	}
}

function GetSubOptions(ProductOptionID) {
    if (ProductOptionID == null) {
        ProductOptionID = GetSelectedOption().ID;
    }
    //clear the selected array
    SelectedOptionalExtras = [];
    $(".suboptions").attr("value", "");
    
    if ($("#floor-options-container")[0] != undefined) {
        getFloorOptions(ProductOptionID);
    }
    if ($("#slide-options-container")[0] != undefined) {
        getSlideOptions(ProductOptionID);
    }
    if ($("#verandah-options-container")[0] != undefined) {
        getVerandahOptions(ProductOptionID);
    }
    if ($("#paint-options-container")[0] != undefined) {
        getPaintOptions(ProductOptionID);
    }
    if ($("#trim-and-colour-container")[0] != undefined) {
        getTrimAndColourOptions(ProductOptionID);
    }
    if ($("#treatment-options-container")[0] != undefined) {
        getTreatmentOptions(ProductOptionID);
    }
    getOptionalExtras(ProductOptionID);
    getDeliveryDetails(ProductOptionID);    
}

function showFloorOptions() {
    var foStr = "<span class=\"section-no\">Select Floor:</span>";
    foStr += "<div id=\"floor-options\">";
    foStr += "<img class=\"loading-image\" src=\"/assets/images/loading.gif\" />";
    foStr += "</div>";
    $("#floor-options-container").addClass("choice-section");
    $("#floor-options-container").html(foStr);
    updateSectionNumbers();
}

function hideFloorOptions() {
    $("#floor-options-container").html("");
    $("#floor-options-container").removeClass("choice-section");
    updateSectionNumbers();
}

function showVerandahOptions() {
    var voStr = "<span class=\"section-no\">Select Verandah:</span>";
    voStr += "<div id=\"verandah-options\">";
    voStr += "<img class=\"loading-image\" src=\"/assets/images/loading.gif\" />";
    voStr += "</div>";
    $("#verandah-options-container").addClass("choice-section");
    $("#verandah-options-container").html(voStr);
    updateSectionNumbers();
}

function hideVerandahOptions() {
    $("#verandah-options-container").html("");
    $("#verandah-options-container").removeClass("choice-section");
    updateSectionNumbers();
}

function showSlideOptions() {
    var foStr = "<span class=\"section-no\">Select Slide:</span>";
    foStr += "<div id=\"slide-options\">";
    foStr += "<img class=\"loading-image\" src=\"/assets/images/loading.gif\" />";
    foStr += "</div>";
    $("#slide-options-container").addClass("choice-section");
    $("#slide-options-container").html(foStr);
    updateSectionNumbers();
}

function hideSlideOptions() {
    $("#slide-options-container").html("");
    $("#slide-options-container").removeClass("choice-section");
    updateSectionNumbers();
}

function showPaintOptions() {
    var voStr = "<span class=\"section-no\">Select Paint:</span>";
    voStr += "<div id=\"paint-options\">";
    voStr += "<img class=\"loading-image\" src=\"/assets/images/loading.gif\" />";
    voStr += "</div>";
    $("#paint-options-container").addClass("choice-section");
    $("#paint-options-container").html(voStr);
    updateSectionNumbers();
}

function hidePaintOptions() {
    $("#paint-options-container").html("");
    $("#paint-options-container").removeClass("choice-section");
    updateSectionNumbers();
}

function updateSectionNumbers() {
    var choiceSections = $("#product-choices-container .choice-section");
    //step through the choice sections setting their number so they have the correct order
    for (var idx = 0; idx < choiceSections.length; idx++) {
        var cs = choiceSections[idx];
        var obj = $(cs).find(".section-no");
        $(obj).attr("class", "section-no section-" + (idx + 1));
    }
}

function showSpecialOptionalsContainer(outputEle, title, sectionName) {
    var oStr = "<span class=\"section-no\">" + title + "</span>";
    oStr += "<div id=\"" + sectionName + "\">";
    oStr += "<img class=\"loading-image\" src=\"/assets/images/loading.gif\" />";
    oStr += "</div>";
    $(outputEle).addClass("choice-section");
    $(outputEle).html(oStr);
    updateSectionNumbers();
}

function hideSpecialOptionalsContainer(outputEle) {
    $(outputEle).html("");
    $(outputEle).removeClass("choice-section");
    updateSectionNumbers();
}

function SelectOptionalExtraChanged(OptionalExtraEle) {
    if ($(OptionalExtraEle).attr("type") == "checkbox") {
        var className = $(OptionalExtraEle).attr("class");
        if (className.indexOf("optional-group-") != -1) {
            var groupID = className.replace(/optional-group-/ig, "");
            var radioGroup = $("input[name=optional-group-" + groupID + "]");
            //enable/disable the appropriate radio buttons
            if ($(OptionalExtraEle).attr("checked")) {
                $(radioGroup).attr("disabled", false);
                $(radioGroup[0]).attr("checked", true);
                //add the first one to the selected array
                addSubOption($(radioGroup[0]));
            }
            else {
                $(radioGroup).attr("disabled", true);
                $(radioGroup).attr("checked", false);
                for (var idx = 0; idx < $(radioGroup).length; idx++) {
                    removeSubOption($(radioGroup[idx]));
                }
            }
        }
        else {
            var subOpId = $(OptionalExtraEle).attr("id").replace(/optional-extra-/ig, "");
            if ($(OptionalExtraEle).attr("checked")) {
                addSubOption($(OptionalExtraEle));
            }
            else {
                removeSubOption($(OptionalExtraEle));
            }
        }
    }
    else if ($(OptionalExtraEle).attr("type") == "radio") {
        //get the rest of the group and make sure they're not in the selected array
        var groupID = $(OptionalExtraEle).attr("name").replace(/optional-group-/ig, "");
        var radioGroup = $("input[name=optional-group-" + groupID + "]");
        for (var idx = 0; idx < $(radioGroup).length; idx++) {
            removeSubOption($(radioGroup[idx]));
        }
        //then add this selected one
        addSubOption($(OptionalExtraEle));
    }
    //update the hidden field with the sub option ids
    updateOptionalExtrasField();
}

function addSubOption(OptionalExtraEle) {
    for (var idx = 0, len = OptionalExtras.length; idx < len; idx++)
    {
        if (OptionalExtras[idx] == undefined) continue;
        if (OptionalExtras[idx].ID == $(OptionalExtraEle).attr("value"))
        {
            SelectedOptionalExtras.push(OptionalExtras[idx]);
            break;
        }
    }
}

function removeSubOption(OptionalExtraEle) {
    for (var idx = 0, len = SelectedOptionalExtras.length; idx < len; idx++)
    {
        if (SelectedOptionalExtras[idx].ID == $(OptionalExtraEle).attr("value"))
        {
            SelectedOptionalExtras.splice(idx, 1);
            break;
        }
    }
}

function updateOptionalExtrasField() {
    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();
}

var defaultOptionalsHeight = "";
var shrunkenOptionalsHeight = "152px";
var defaultOptionalsText = "";
var getOptionalExtrasAjax = null;
function getOptionalExtras(ProductOptionID) {
	if(getOptionalExtrasAjax != null) getOptionalExtrasAjax.abort();
    getOptionalExtrasAjax = $.ajax({
        type: "GET",
        url: "/ProductPage4/AJAX/OptionalExtras.aspx?ProductOptionID=" + ProductOptionID + "&date=" + Date(),
        success: function(data, textStatus) { 
            $("#optional-extras").html("<span class='section-no'></span>" + data);
            //set up the click events for the newly aquired sub options
            $("#optional-extras input").click(function() {
                SelectOptionalExtraChanged($(this));
            });
            //run a check to select any included extras
            var objs = $("#optional-extras input[rel=included]");
            for (var idx = 0, len = objs.length; idx < len; idx++)
            {
                SelectOptionalExtraChanged(objs[idx]);
            }
            //set the initial height of the optional extras box
            defaultOptionalsHeight = $("#optional-extras-table-container").height();
            $("#optional-extras-table-container").css("height", shrunkenOptionalsHeight);
            //set up the click for showing more options
            defaultOptionalsText = $("#optional-extras-show-more").html();
            $("#optional-extras-show-more").click(function(e) {
                e.preventDefault();
                if ($(this).hasClass("expanded")) {
                    //need to close it
                    $(this).removeClass("expanded");
                    $(this).html(defaultOptionalsText);
                    $("#optional-extras-table-container").animate({
                        height: shrunkenOptionalsHeight
                    }, 1000, function() {
                        $("html, body").animate({
                            scrollTop: $("#product-options-container h1").offset().top - 10
                        });
                    });
                }
                else {
                    //need to open it
                    $(this).addClass("expanded");
                    $(this).html("Click here to hide optional extras");
                    $("#optional-extras-table-container").animate({
                        height: defaultOptionalsHeight
                    }, 1000);
                }
            });
            //set the popup for when the user clicks on the name of the optional extra
            $(".optional-extra-name").click(function() {
                triggerSubOptionMacBox($(this).attr("rel"));
            });
        },
        error: function(ajaxObj, textStatus, errorThrown) {
            //$("#debug-box").html(ajaxObj.responseText);
        }
    });
}

var getDeliveryAjax = null;
function getDeliveryDetails(ProductOptionID) {
    if (ProductOptionID == null) {
        ProductOptionID = GetSelectedOption().ID;
    }

	if(getDeliveryAjax != null) getDeliveryAjax.abort();

    getDeliveryAjax = $.ajax({
        type: "GET",
        url: "/ProductPage4/AJAX/AJAXSubOptionsDelivery.aspx?ProductOptionID=" + ProductOptionID + "&date=" + Date(),
        success: function(data, textStatus) { 
            $("#delivery-details").html("<span class='section-no'></span>" + data);
        },
        error: function(ajaxObj, textStatus, errorThrown) {
        }
    });
}

var getFloorAjax = null;
function getFloorOptions(ProductOptionID) {
    //get rid of old options
    hideFloorOptions();
    //then start again
    if (ProductOptionID == null) {
        ProductOptionID = GetSelectedOption().ID;
    }

	if(getFloorAjax != null) getFloorAjax.abort();

    getFloorAjax = $.ajax({
        type: "GET",
        url: "/ProductPage4/AJAX/FloorOptions.aspx?ProductOptionID=" + ProductOptionID,
        success: function(data, textStatus) {
            if (data.length != 0) {
                showSpecialOptionalsContainer($("#floor-options-container"), "Select Floor:", "floor-options");
            }
            else {
                hideSpecialOptionalsContainer($("#floor-options-container"));
            }
            $("#floor-options").html(data);
            var floorGroup = $("#floor-options input[name=floor-option-group]");
            $(floorGroup).click(function() {
                for (var idx = 0; idx < floorGroup.length; idx++) {
                    removeSubOption($(floorGroup[idx]));
                }
                if ($(this).val() != -1) {
                    addSubOption($(this));
                }
                updateOptionalExtrasField();
            });
            //we need to select the default floor option
            var defaultFloorEle = $("#floor-options .floor-option label[rel=no-floor]").attr("for");
            if (defaultFloorEle == undefined) {
                defaultFloorEle = $("#floor-options .floor-option label[rel=not-required]").attr("for");
            }
            $("#" + defaultFloorEle).click();
        },
        error: function(ajaxObj, textStatus, errorThrown) {
        }
    });
}

function getVerandahOptions(ProductOptionID) {
    //get rid of old options
    hideVerandahOptions();
    //then start again
    if (ProductOptionID == null) {
        ProductOptionID = GetSelectedOption().ID;
    }
    $.ajax({
        type: "GET",
        url: "/ProductPage4/AJAX/VerandahOptions.aspx?ProductOptionID=" + ProductOptionID,
        success: function(data, textStatus) {
            if (data.length != 0) {
                showSpecialOptionalsContainer($("#verandah-options-container"), "Select Verandah:", "verandah-options");
            }
            else {
                hideSpecialOptionalsContainer($("#verandah-options-container"));
            }
            $("#verandah-options").html(data);
            var verandahGroup = $("#verandah-options input[name=verandah-option-group]");
            $(verandahGroup).click(function() {
                for (var idx = 0; idx < verandahGroup.length; idx++) {
                    removeSubOption($(verandahGroup[idx]));
                }
                if ($(this).val() != -1) {
                    addSubOption($(this));
                }
                updateOptionalExtrasField();
            });
        },
        error: function(ajaxObj, textStatus, errorThrown) {
        }
    });
}

function getSlideOptions(ProductOptionID) {
    //get rid of old options
    hideSlideOptions();
    //then start again
    if (ProductOptionID == null) {
        ProductOptionID = GetSelectedOption().ID;
    }
    $.ajax({
        type: "POST",
        url: "/ProductPage4/AJAX/SlideOptions.aspx",
        data: "ProductOptionID=" + ProductOptionID,
        success: function(data, textStatus) {
            if (data.length != 0) {
                showSpecialOptionalsContainer($("#slide-options-container"), "Select Slide:", "slide-options");
            }
            else {
                hideSpecialOptionalsContainer($("#slide-options-container"));
            }
            $("#slide-options").html(data);
            var slideGroup = $("#slide-options input[name=slide-option-group]");
            $(slideGroup).click(function() {
                for (var idx = 0; idx < slideGroup.length; idx++) {
                    removeSubOption($(slideGroup[idx]));
                }
                if ($(this).val() != -1) {
                    addSubOption($(this));
                }
                updateOptionalExtrasField();
            });
        },
        error: function(ajaxObj, textStatus, errorThrown) {
        }
    });
}

function showPaintChoices() {
    $("#paint-options .choices").removeClass("disabled");
    var paintChoices = $("#paint-options input[name=paint-option-choice]");
    for (var i = 0, len = paintChoices.length; i < len; i++) {
        $(paintChoices).attr("disabled", false);
    }
}

function hidePaintChoices() {
    $("#paint-options .choices").addClass("disabled");
    var paintChoices = $("#paint-options input[name=paint-option-choice]");
    $(paintChoices).attr("disabled", true);
    $(paintChoices).attr("checked", false);
    for (var i = 0, len = paintChoices.length; i < len; i++) {
        removeSubOption(paintChoices[i]);
    }
    updateOptionalExtrasField();
}

function getPaintOptions(ProductOptionID) {
    //get rid of old options
    hidePaintOptions();
    //then start again
    if (ProductOptionID == null) {
        ProductOptionID = GetSelectedOption().ID;
    }
    $.ajax({
        type: "GET",
        url: "/ProductPage4/AJAX/PaintOptions.aspx?ProductOptionID=" + ProductOptionID,
        success: function(data, textStatus) {
            if (data.length != 0) {
                showSpecialOptionalsContainer($("#paint-options-container"), "Select Paint:", "paint-options");
            }
            else {
                hideSpecialOptionalsContainer($("#paint-options-container"));
            }
            $("#paint-options").html(data);
            var paintGroup = $("#paint-options input[name=paint-option-group]");
            $(paintGroup).click(function() {
                if ($(this).val() == 1) {
                    showPaintChoices();
                }
                else {
                    hidePaintChoices();
                }
            });
            var paintChoices = $("#paint-options input[name=paint-option-choice]");
            $(paintChoices).click(function() {
                if ($(this).attr("checked")) {
                    addSubOption($(this));
                }
                else {
                    removeSubOption($(this));
                }
                updateOptionalExtrasField();
            });
            $("#paint-options h2").click(function() {
                triggerSubOptionMacBox($(this).attr("rel"));
            });
        },
        error: function(ajaxObj, textStatus, errorThrown) {
        }
    });
}

function clearTrimAndColourOptions(ele) {
    //remove all of the selected trim and colour options from the basket
    var trimEles = $("#trim-choices .choices input");
    for (var i = 0; i < trimEles.length; i++) {
        removeSubOption($(trimEles[i]));
        $(trimEles[i]).parent().removeClass("selected");
    }
    $("#trim-choices .choices input[value=0]").attr("checked", true);
    $("#trim-choices .choices input[value=0]").parent().addClass("selected");
    
    var colourEles = $("#colour-choices .choices input");
    for (var i = 0; i < colourEles.length; i++) {
        removeSubOption($(colourEles[i]));
        $(colourEles[i]).parent().removeClass("selected");
    }
    $("#colour-choices .choices input[value=0]").attr("checked", true);
    $("#colour-choices .choices input[value=0]").parent().addClass("selected");
}

function getTrimAndColourOptions(ProductOptionID) {
    //get rid of old options
    hidePaintOptions();
    //then start again
    if (ProductOptionID == null) {
        ProductOptionID = GetSelectedOption().ID;
    }
    $.ajax({
        type: "GET",
        url: "/ProductPage4/AJAX/TrimAndColourOptions.aspx?ProductOptionID=" + ProductOptionID,
        success: function(data, textStatus) {
            if (data.length != 0) {
                showSpecialOptionalsContainer($("#trim-and-colour-container"), "Colour your building:", "trim-and-colour-options");
            }
            else {
                hideSpecialOptionalsContainer($("#trim-and-colour-container"));
            }
            $("#trim-and-colour-options").html(data);
            var TrimChoices = $("#trim-choices input[name=trim-option-choice]");
            $(TrimChoices).click(function() {
                var trimEles = $("#trim-choices .choices input");
                //check to see if it is the 'none' option
                if ($(this).val() == 0) {
                    clearTrimAndColourOptions();
                }
                else {
                    //make sure none of the other choices are in the basket
                    for (var i = 0; i < trimEles.length; i++) {
                        removeSubOption($(trimEles[i]));
                        //remove the 'selected' class from the list element
                        $(trimEles[i]).parent().removeClass("selected");
                    }
                    addSubOption($(this));
                    //add the 'selected' class to the list element
                    $(this).parent().addClass("selected");
                    //make sure that one of the colour options is selected
                    if ($("#colour-choices input[value=0]").attr("checked")) {
                        $($("#colour-choices input[name=colour-option-choice]")[1]).click();
                    }
                }
                updateOptionalExtrasField();
            });
            var ColourChoices = $("#colour-choices input[name=colour-option-choice]");
            $(ColourChoices).click(function() {
                var colourEles = $("#colour-choices .choices input");
                //check to see if it is the 'none' option
                if ($(this).val() == 0) {
                    clearTrimAndColourOptions();
                }
                else {
                    for (var i = 0; i < colourEles.length; i++) {
                        removeSubOption($(colourEles[i]));
                        //remove the 'selected' class from the list element
                        $(colourEles[i]).parent().removeClass("selected");
                    }
                    addSubOption($(this));
                    //add the 'selected' class to the list element
                    $(this).parent().addClass("selected");
                    //make sure that one of the trim options is selected
                    if ($("#trim-choices input[value=0]").attr("checked")) {
                        $($("#trim-choices input[name=trim-option-choice]")[1]).click();
                    }
                }
                updateOptionalExtrasField();
            });
            //set up the learn more link
            $("#trim-and-colour-options .learn-more").click(function(e) {
                e.preventDefault();
                triggerSubOptionMacBox($(this).attr("rel"));
            });
            //set up the hovers
            $("#trim-choices label").each(function() {
                var val = $(this).parent().find("input[name=trim-option-choice]").val();
                if (val != 0) {
                    var rel = $(this).attr("rel");
                    $(this).hoverbubble({
                        html: "<img src=\"/global/images/product-page/trim-wall-colours/" + rel + "\" />",
                        rel: "trim-option",
                        width: 520,
                        offsetLeft: -40,
                        keepBubbleOnHover: false
                    });
                }
            });
            $("#colour-choices label").each(function() {
                var val = $(this).parent().find("input[name=colour-option-choice]").val();
                if (val != 0) {
                    var rel = $(this).attr("rel");
                    $(this).hoverbubble({
                        html: "<img src=\"/global/images/product-page/trim-wall-colours/" + rel + "\" />",
                        rel: "colour-option",
                        width: 520,
                        offsetLeft: -40,
                        keepBubbleOnHover: false
                    });
                }
            });
        },
        error: function(ajaxObj, textStatus, errorThrown) {
        }
    });
}

function getTreatmentOptions(ProductOptionID) {
    if (ProductOptionID == null) {
        ProductOptionID = GetSelectedOption().ID;
    }
    $.ajax({
        type: "GET",
        url: "/ProductPage4/AJAX/TreatmentOptions.aspx?ProductOptionID=" + ProductOptionID,
        success: function(data, textStatus) {
            $("#treatment-options").html(data);
            var treatmentGroup = $("#treatment-options input[name=treatment-option-group]");
            $(treatmentGroup).click(function() {
                for (var idx = 0; idx < treatmentGroup.length; idx++) {
                    removeSubOption($(treatmentGroup[idx]));
                }
                if ($(this).val() != -1) {
                    addSubOption($(this));
                }
                updateOptionalExtrasField();
            });
            //set up the sub option macbox for the click
            $("#treatment-options h2").click(function() {
                triggerSubOptionMacBox($(this).attr("rel"));
            });
        },
        error: function(ajaxObj, textStatus, errorThrown) {
            
        }
    });
}

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 totalPriceText = "&pound;" + totalPrice;
    $("#price").html(totalPriceText);

//    //////////////////////////////////////////////////////////////////////////
//    //Concept code for showing altered value after something updates the price
//    var priceHover = document.createElement("div");
//    $("body").append(priceHover);
//    $(priceHover).css("position", "absolute");
//    $(priceHover).css("z-index", 1);
//    $(priceHover).html("blahblahblah");
//    var top = $("#total-price").offset().top;
//    var left = $("#total-price").offset().left + $("#total-price").width() - $(priceHover).width();
//    $(priceHover).css("top", top);
//    $(priceHover).css("left", left);
//    $(priceHover).animate({
//        top: top - 20,
//        opacity: 0
//    }, {
//        duration: 1000
//    });
//    setTimeout(function() {
//        $(priceHover).remove();
//    }, 1000);
//    //////////////////////////////////////////////////////////////////////////
    
    //update the tech spec prices
    resetTechSpecPrices();
    $("#tech-spec-price-" + ProductOption.ID).html("&pound;" + totalPrice);
}

function resetTechSpecPrices() {
    var eles = $(".tech-spec-price");
    for (var idx = 0, len = eles.length; idx < len; idx++) {
        var price = "";
        var id = $(eles[idx]).attr("id").replace(/tech-spec-price-/ig, "");
        //find the appropriate option
        for (var jdx = 0, lenj = ProductOptions.length; jdx < lenj; jdx++) {
            if (ProductOptions[jdx].ID == id) {
                //get the price
                price = ProductOptions[jdx].price;
            }
        }
        $(eles[idx]).html("&pound;" + price);
    }
}

function createAssemblyEle(assemblyEle, htmlId, popupTitle, innerText, gotOne) {
    //image
    var ele = document.createElement("div");
    $(ele).attr("class", htmlId + " assembly-item " + ((!gotOne) ? " first" : ""));
    $(assemblyEle).append(ele);
    $(ele).hover(function() {
        $("#" + htmlId + "-popup").show();
    }, function() {
        $("#" + htmlId + "-popup").hide();
    });
    //popup
    var popup = document.createElement("div");
    $(popup).attr("id", htmlId + "-popup");
    $(popup).attr("class", "assembly-popup");
        var topBit = document.createElement("div");
        $(topBit).attr("class", "top");
    $(popup).append(topBit);
        var middleBit = document.createElement("div");
        $(middleBit).attr("class", "middle");
            var title = document.createElement("span");
            $(title).attr("class", "assembly-popup-title");
            $(title).html(popupTitle + ":");
        $(middleBit).append(title);
            var text = document.createElement("span");
            $(text).html(innerText);
        $(middleBit).append(text);
    $(popup).append(middleBit);
        var bottomBit = document.createElement("div");
        $(bottomBit).attr("class", "bottom");
    $(popup).append(bottomBit);
    $(assemblyEle).append(popup);
    
    var paddingTop = parseInt($(popup).css("padding-top").replace(/px/ig, ""));
    var paddingBottom = parseInt($(popup).css("padding-bottom").replace(/px/ig, ""));
    try {
        var top = $(ele).position().top - ($(popup).height() + paddingTop + paddingBottom);
        $(popup).css("top", top);
        $(popup).css("left", $(ele).position().left - 10);
    }
    catch (ex) {}
}
function updateAssemblyInfo() {
    //clear the current ones
    var assemblyEle = $("#shed-assembly-items");
    $(assemblyEle).html("");
    //put in any that we have
    var gotOne = false;
    var option = GetSelectedOption();
    if (option.peopleRequired.length != 0) {
        var htmlId = "people-required";
        var popupTitle = "People Required";
        createAssemblyEle(assemblyEle, htmlId, popupTitle, option.peopleRequired, gotOne);
        gotOne = true;
    }
    if (option.toolsRequired.length != 0) {
        var htmlId = "tools-required";
        var popupTitle = "Tools Required";
        var innerText = "<ul>";
        for (var idx = 0, len = option.toolsRequired.length; idx < len; idx++) {
            if (option.toolsRequired[idx].length == 0) continue;
            innerText += "<li>" + option.toolsRequired[idx] + "</li>";
        }
        innerText += "</ul>";
        createAssemblyEle(assemblyEle, htmlId, popupTitle, innerText, gotOne);
        gotOne = true;
    }
    if (option.packageDimensions.length != 0) {
        var htmlId = "package-dimensions";
        var popupTitle = "Package Dimensions";
        createAssemblyEle(assemblyEle, htmlId, popupTitle, option.packageDimensions, gotOne);
        gotOne = true;
    }
    if (option.assemblyTime.length != 0) {
        var htmlId = "assembly-time";
        var popupTitle = "Assembly Time";
        createAssemblyEle(assemblyEle, htmlId, popupTitle, option.assemblyTime, gotOne);
        gotOne = true;
    }
    if (gotOne) {
        $("#shed-assembly").show();
    }
    else {
        $("#shed-assembly").hide();
    }
}

function showDeliveryPopup(deliveryPage) {
    if (getStoreID() == 3) {
        triggerMacBox({
            boxID: "delivery-area-info",
            width: 700,
            ajaxUrl: "/DeliveryInformation/" + deliveryPage + ".aspx"
        });
        return false;
    }
}
function getSubOption(id) {
    for (var idx = 0, len = OptionalExtras.length; idx < len; idx++) {
        if (OptionalExtras[idx].ID == id) {
            return OptionalExtras[idx];
        }
    }
    return null;
}

function triggerSubOptionMacBox(subOpId) {
    triggerMacBox({
        boxID: "sub-option-info-" + subOpId,
        width: 600,
        ajaxUrl: "/ProductPage4/AJAX/SubOptionInformation.aspx?SubOptionID=" + subOpId
    });
}

function initDescriptionBlocks() {
    $(".dblock-img-container .expander").click(function(e) {
        e.preventDefault();
        showDescBlockPopup($(this).attr("rel"));
    });
    $(".dblock-img-container .dblock-img img").click(function() {
        var id = $(this).attr("id");
        id = id.replace(/dblock-img-/ig, "");
        showDescBlockPopup(id);
    });
}
function showDeliveryProcessPopup() {
    if ($("#DeliveryProcessPopup").get(0) != null) {
        showRyMacBox("DeliveryProcessPopup");
    }
    else {
        var billyOhAdvantageUrl = "/ProductPage4/AJAX/DeliveryProcess.aspx";
        $.ajax({
            type: "GET",
            url: billyOhAdvantageUrl,
            success: function(data, status) {
                var billyOhAdvantage = document.createElement("div");
                $(billyOhAdvantage).attr("id", "billyoh-process-popup");
                $(billyOhAdvantage).append(data);
                $("body").append(billyOhAdvantage);
                var assemblyMacBox = new RyMacBox("DeliveryProcessPopup", "html|billyoh-process-popup", 484, 1, 
                    $("body").get(0), {}, {}, function() { 
                        showRyMacBox("DeliveryProcessPopup"); 
                    }, true, "round");
            },
            error: function(ajaxObj, status, error) {
                
            }
        });
    }
}
function showAssemblyWidgetPopup() {
    if ($("#AssemblyWidgetPopup").get(0) != null) {
        showRyMacBox("AssemblyWidgetPopup");
    }
    else {
        var billyOhAdvantageUrl = "/ProductPage4/AJAX/AssemblyWidget.aspx";
        $.ajax({
            type: "GET",
            url: billyOhAdvantageUrl,
            success: function(data, status) {
                var billyOhAdvantage = document.createElement("div");
                $(billyOhAdvantage).attr("id", "assembly-widget-popup");
                $(billyOhAdvantage).append(data);
                $("body").append(billyOhAdvantage);
                var assemblyMacBox = new RyMacBox("AssemblyWidgetPopup", "html|assembly-widget-popup", 721, 1, 
                    $("body").get(0), {}, {}, function() { 
                        showRyMacBox("AssemblyWidgetPopup"); 
                    }, true, "round");
            },
            error: function(ajaxObj, status, error) {
                
            }
        });
    }
}

// Show pop up for assembly service
function initAssemblyServiceDescription() {
    $("#delivery-details #assembly-note .shed").live("click", function(e) {
        triggerMacBox({
            boxID: "assembly-service-description",
            width: 780,
            ajaxUrl: "/ProductPage4/AJAX/ShedAssemblyServices.aspx"
        });
        e.preventDefault();
    });
    $("#delivery-details #assembly-note .logcabin").live("click", function(e) {
        triggerMacBox({
            boxID: "assembly-service-description",
            width: 780,
            ajaxUrl: "/ProductPage4/AJAX/LogCabinAssemblyServices.aspx"
        });
        e.preventDefault();
    });       
}

////Product images
function selectOptionThumbnail(optionId) {
    var newListImageHtml = "";
    var count = 0;
    for(var idx = 0; idx < OptionImages.length; idx++) {
        if(OptionImages[idx].optionID == optionId) {
            newListImageHtml += "<li><img id=\"option-image-" + OptionImages[idx].optionID + "-" + count + "\"" +
                "rev=\"/images/products/" + OptionImages[idx].medium +"\" " +
                "rel=\"/images/products/" + OptionImages[idx].large +"\" " +
                "alt=\""+ OptionImages[idx].caption +"\" " +
                "title=\""+ OptionImages[idx].caption +"\" " +
                "src=\"/images/products/"+ OptionImages[idx].thumbnail + "\" /></li>";
            count++;
        }
    }
    $("#image-controls #ThumbnailsList").html(newListImageHtml);
    selectThumbnail($("#image-controls #ThumbnailsList li img").get(0));
    resizeThumbnailListContainer();
}
function selectThumbnail(obj) {
    $(".Product-Main-Image").ImageSwitch({  Type: "FadeIn",
                                            NewImage: $(obj).attr("rev"),
                                            EffectOriginal: false,
                                            Direction: "DownTop"
                                        });
    $(".Product-Main-Image").attr("rel", $(obj).attr("rel"));
    $(".Product-Main-Image").attr("alt", $(obj).attr("title"));
    $(".Product-Main-Image").attr("title", $(obj).attr("title"));
    $(".MainImageCaption").html($(obj).attr("title"));
}

function initProductThumbnails() {
    //When user click on the image show up the ubox
    $(".ShowUBox").click(function(e){
        e.preventDefault();
        setuBox({
            source: $(this).find(".Product-Main-Image").attr("rel"),
            caption: $("#product-images .MainImageCaption").text(),
            listObj: $("#image-controls #ThumbnailsList")
        });
        triggeruBox();
    });
     $(".ABShowUBox").click(function(e) {
        e.preventDefault();
        triggerMacBox({
            boxID: "AB-Show-Gallery",
            width: 1040,
            ajaxUrl: "/playback/AJAX/gallery.aspx?optionID=" + GetSelectedOption().ID + "&date=" + new Date(),
            callback: function() {
                initABGallery();
            },
            borderType: "basic"
        });
    });
    //When user click on the thumbnails
    $("#image-controls #ThumbnailsList li img").live("click", function(e){
        e.preventDefault();
        selectThumbnail(this);
    });
    $("#image-controls #OptionSelectThumbnails li img").click(function(e){
        e.preventDefault();
        SelectedOptionChanged($(this).attr("rev"));
    });
    // When you want to slide the images list back
    $("#image-controls #thumbnail-slide-next").click(function(e) {
        e.preventDefault();
        $("#image-controls .all-thumbnails-list").stop(true, true);
        var leftPos = $("#image-controls .all-thumbnails-list").position().left;
        var widthSize = $("#image-controls .all-thumbnails-list").width();
        if (widthSize + (leftPos - 300) > 0) {
            $("#image-controls .all-thumbnails-list").animate({ left: leftPos - 300 + "px" }, 200);
        }
    });
    $("#image-controls #thumbnail-slide-prev").click(function(e) {
        e.preventDefault();
        $("#image-controls .all-thumbnails-list").stop(true, true);
        var leftPos = $("#image-controls .all-thumbnails-list").position().left;
        if ($("#image-controls .all-thumbnails-list").position().left + 300 < 0) {
            $("#image-controls .all-thumbnails-list").animate({ left: leftPos + 300 + "px" }, 200);
        } else {
            $("#image-controls .all-thumbnails-list").animate({ left: "0px" }, 200);
        }
    });

    // Init for the slider, if users don't have js, this setting not work and show them the full list
    $("#product-images #image-controls #ThumbnailsList").css("position", "absolute");
    $("#product-images #image-controls #thumbnails-viewport").css("height", "85px");
    $("#product-images #image-controls #thumbnails-viewport").css("overflow", "hidden");
    $("#product-images #image-controls #thumbnail-slide-next").css("visibility", "visible");
    $("#product-images #image-controls #thumbnail-slide-prev").css("visibility", "visible");
    
    resizeThumbnailListContainer();
}

// As we using the scroll, we need to resize the thumbnails list to maximize to scroll it
function resizeThumbnailListContainer() {
    $("#thumbnails-viewport .all-thumbnails-list").css("left", 0);
    $("#thumbnails-viewport .all-thumbnails-list").width($("#thumbnails-viewport .all-thumbnails-list li").length * 75);
}

function showDescBlockPopup(id) {
    if ($("#DescriptionBlock" + id).get(0) != null) {
        showRyMacBox("DescriptionBlock" + id);
    }
    else {
        var imgSrc = $("#dblock-img-" + id).attr("rel");
        var imgText = $("#dblock-img-" + id).attr("title");
        var descBlockMacBox = new RyMacBox("DescriptionBlock" + id, "img|desc-block-" + id, 550, 1, 
            $("body").get(0), { image: imgSrc, text: imgText }, {}, function() { showRyMacBox("DescriptionBlock" + id); }, true);
    }
}

function showUpsellBetterPopup() {
    var optionId = GetSelectedOption().ID;
    if ($("#UpsellBetter" + optionId).get(0) != null) {
        showRyMacBox("UpsellBetter" + optionId);
    }
    else {
        var upsellBetterUrl = "/ProductPage4/AJAX/UpsellBetter.aspx";
        $.ajax({
            type: "GET",
            url: upsellBetterUrl + "?OptionID=" + optionId,
            success: function(data, status) {
                var upsellBetter = document.createElement("div");
                $(upsellBetter).attr("id", "upsell-better-popup-" + optionId);
                $(upsellBetter).append(data);
                $("body").append(upsellBetter);
                var upsellBetterMacBox = new RyMacBox("UpsellBetter" + optionId, "html|upsell-better-popup-" + optionId, 485, 1, 
                    $("body").get(0), {}, {}, function() { 
                        showRyMacBox("UpsellBetter" + optionId); 
                    }, true, "round");
            },
            error: function(ajaxObj, status, error) {
                
            }
        });
    }
}

function submitAtbForm() {
    $("#product-choices-container form").get(0).submit();
}

function initCustomerImages(){
	$("#customer-photos #customer-images-list .customer-image-link").click(function(e){
	    setuBox({
	        source: $(this).attr("rel"),
	        caption: $(this).attr("title"),
	        getDataFrom: 'AJAX',
	        ajaxUrl: '/ProductPage4/AJAX/AJAXCustomerImages.aspx',
	        ajaxData: 'productID=' + $(this).attr("rev")
	    });	    
	    triggeruBox();
	});
}

function dimensionOptionChanged(optionId) {
    //if this product has no dimensions defined then skip this function
    if (typeof dimensionValues == "undefined") return;
    ///
    var index = 0;
    if (optionId != null) {
        //find the relevant option
        var ops = $("#dimensions-select option");
        for (var idx = 0, len = ops.length; idx < len; idx++) {
            if ($(ops[idx]).val() == optionId) {
                $("#dimensions-select").attr("selectedIndex", idx);
                index = idx;
                break;
            }
        }
    }
    else {
        index = $("#dimensions-select").attr("selectedIndex");
        optionId = $("#dimensions-select").val();
    }
    
    //different values depending on shedType
    if ((dimensionValues["_" + optionId].shedType == "apex")
        ||(dimensionValues["_" + optionId].shedType == "bigbarn")
        ||(dimensionValues["_" + optionId].shedType == "logalpine")
        ||(dimensionValues["_" + optionId].shedType == "logtraditional")) {
        $("#dimension-ridge").html(dimensionValues["_" + optionId].ridge);
        $("#dimension-eaves").html(dimensionValues["_" + optionId].eaves);
        $("#dimension-door-width").html(dimensionValues["_" + optionId].doorWidth);
        $("#dimension-door-height").html(dimensionValues["_" + optionId].doorHeight);
        $("#dimension-width").html(dimensionValues["_" + optionId].width);
        $("#dimension-depth").html(dimensionValues["_" + optionId].depth);
        $("#dimension-width-internal").html(dimensionValues["_" + optionId].widthInternal);
        $("#dimension-depth-internal").html(dimensionValues["_" + optionId].depthInternal);
        $("#dimension-eaves-internal").html(dimensionValues["_" + optionId].eavesInternal);
        $("#dimension-ridge-internal").html(dimensionValues["_" + optionId].ridgeInternal);
        $("#dimension-floor-area-internal").html(dimensionValues["_" + optionId].areaFloorInternal);
    }
    else if (dimensionValues["_" + optionId].shedType == "pent") {
        $("#dimension-front").html(dimensionValues["_" + optionId].ridge);
        $("#dimension-back").html(dimensionValues["_" + optionId].eaves);
        $("#dimension-door-width").html(dimensionValues["_" + optionId].doorWidth);
        $("#dimension-door-height").html(dimensionValues["_" + optionId].doorHeight);
        $("#dimension-width").html(dimensionValues["_" + optionId].width);
        $("#dimension-depth").html(dimensionValues["_" + optionId].depth);
        $("#dimension-width-internal").html(dimensionValues["_" + optionId].widthInternal);
        $("#dimension-depth-internal").html(dimensionValues["_" + optionId].depthInternal);
        $("#dimension-back-internal").html(dimensionValues["_" + optionId].eavesInternal);
        $("#dimension-front-internal").html(dimensionValues["_" + optionId].ridgeInternal);
        $("#dimension-floor-area-internal").html(dimensionValues["_" + optionId].areaFloorInternal);
    }
    else if (dimensionValues["_" + optionId].shedType == "cornershed") {
        $("#dimension-front").html(dimensionValues["_" + optionId].ridge);
        $("#dimension-back").html(dimensionValues["_" + optionId].eaves);
        $("#dimension-door-width").html(dimensionValues["_" + optionId].doorWidth);
        $("#dimension-door-height").html(dimensionValues["_" + optionId].doorHeight);
        $("#dimension-width").html(dimensionValues["_" + optionId].width);
        $("#dimension-depth").html(dimensionValues["_" + optionId].depth);
        $("#dimension-gable-door").html(dimensionValues["_" + optionId].doorGable);
        $("#dimension-gable-window").html(dimensionValues["_" + optionId].windowGable);
        $("#dimension-gable-plain").html(dimensionValues["_" + optionId].plainGable);
        $("#dimension-gable-plain-internal").html(dimensionValues["_" + optionId].plainGableInternal);
        $("#dimension-gable-door-internal").html(dimensionValues["_" + optionId].doorGableInternal);
        $("#dimension-gable-window-internal").html(dimensionValues["_" + optionId].windowGableInternal);
        $("#dimension-back-internal").html(dimensionValues["_" + optionId].eavesInternal);
        $("#dimension-floor-area-internal").html(dimensionValues["_" + optionId].areaFloorInternal);
    }
    //small version at top of page
    var widthMet = dimensionValues["_" + optionId].width;
    widthMet = widthMet.replace(/cm/ig, "");
    widthMet = (parseInt(widthMet) / 100) + "m";
    var widthImp = dimensionValues["_" + optionId].widthImp;
    var depthMet = dimensionValues["_" + optionId].depth;
    depthMet = depthMet.replace(/cm/ig, "");
    depthMet = (parseInt(depthMet) / 100) + "m";
    var depthImp = dimensionValues["_" + optionId].depthImp;
    var heightMet = dimensionValues["_" + optionId].ridge;
    heightMet = heightMet.replace(/cm/ig, "");
    heightMet = (parseInt(heightMet) / 100) + "m";
    var heightImp = dimensionValues["_" + optionId].ridgeImp;
    $("#dims-width").html(widthMet + " (" + widthImp + ")");
    $("#dims-depth").html(depthMet + " (" + depthImp + ")");
    $("#dims-height").html(heightMet + " (" + heightImp + ")");
    
    //for now show the same image for all sizes, will maybe bring back later if we decide
    //to do different images for different sizes
    //$("#shed-dimensions-image-external").attr("src", "/images/products/shed-dimensions/" + Product.ID + "-" + optionId + ".jpg");
}

function showShedSizes(view) {
    $(".shed-dimensions-sizes").hide();
    $("#shed-dimensions-sizes-" + view).show();
    $("#shed-dimensions-tabs ul li").removeClass("selected");
    $("#shed-dimensions-tab-" + view).addClass("selected");
    $(".shed-dimensions-image").hide();
    $("#shed-dimensions-image-" + view).show();
}

function technicalSpecSelected(rel) {
    $("#technical-specifications table th, #technical-specifications table td").removeClass("selected");
    $("#technical-specifications-2 table th, #technical-specifications-2 table td").removeClass("selected");
    $("*[rel=" + rel + "]").addClass("selected");
}

function showWarrantyPopup() {
    triggerMacBox({
        boxID: "product-warranty-box",
        width: 780,
        ajaxUrl: "/ProductPage4/AJAX/WarrantyPopup.aspx?prodID=" + Product.ID
    });
}

function showImagePopup(ele) {
    var boxId = $(ele).attr("id");
    var imgSrc = $(ele).attr("rel");
    var imgTxt = $(ele).attr("title");
    triggerMacBox({
        boxID: boxId + "-large",
        source: "IMAGE",
        width: 550,
        image: imgSrc,
        imageText: imgTxt
    });
}

function showVideoPopup(ele) {
    var boxId = $(ele).attr("id");
    var videoSrc = $(ele).attr("rel");
    var captionTxt = $(ele).attr("title");
    triggerMacBox({
        boxID: boxId + "-video",
        source: "VIDEO",
        width: 350,
        video: videoSrc,
        imageText: captionTxt
    });
}

var units = "metric";
function updateMeasurementUnits() {
    if (units == "metric") {
        //show/hide relevant values
        $(".met").show();
        $(".imp").hide();
    }
    else {
        //show/hide relevant values
        $(".met").hide();
        $(".imp").show();
    }
    //make sure all units selects are updated on the page
    var unitOptions = $("#units-select option");
    for (var idx = 0; idx < unitOptions.length; idx++) {
        if ($(unitOptions[idx]).val() == units) {
            $("#units-select").attr("selectedIndex", idx);
            break;
        }
    }
    unitOptions = $("#tech-specs-change-units-select option");
    for (var idx = 0; idx < unitOptions.length; idx++) {
        if ($(unitOptions[idx]).val() == units) {
            $("#tech-specs-change-units-select").attr("selectedIndex", idx);
            break;
        }
    }
}
function updateDimensionValues(optionId) {
    if (optionId == null) {
        optionId = GetSelectedOption().ID;    
    }
    //make sure this value is selected on the select
    var dimsSelectOptions = $("#dims-select option");
    for (var idx = 0; idx < dimsSelectOptions.length; idx++) {
        if ($(dimsSelectOptions[idx]).val() == optionId) {
            $("#dims-select").attr("selectedIndex", idx);
            break;
        }
    }
    //get the dimensions object for this option
    var dims = dimensionValues["_" + optionId];
    for (var attribute in dims) {
        var eleId = "#dims2-" + attribute;
        $(eleId).html(dims[attribute]);
    }
    //update the image to show the correct image for this option
    var imgSrc = "/images/products/" + Product.ID + "/dimensions/" + optionId + ".jpg";
    $("#dims-select-image").attr("src", imgSrc);
}

function showProductPriceHistoryPopup(promoID) {
    var productID = Product.ID;
    triggerMacBox({
        boxID: "ProductPriceHistory",
        width: 350,
        ajaxUrl: "/global/promotions/ProductPriceHistoryAJAX.aspx?promoID=" + promoID + "&productID=" + productID + "&date=" + new Date()
    });
}

function showProductVideoPopup(videoType) {
    triggerMacBox({
        boxID: "ProductVideo",
        width: 720,
        ajaxType: "post",
        ajaxUrl: "/ProductPage4/AJAX/ProductVideo.aspx",
        ajaxData: "productID=" + Product.ID + "&type=" + videoType + "&date=" + new Date(),
        borderType: "round",
        onclose: function() {
            $("#ProductVideo").remove();
        }
    });
}

//some global variables
var Product = {};
var ProductOptions = [];
var OptionalExtras = [];
var SelectedOption = {};
var SelectedOptionalExtras = [];
var SelectedServices = [];
var useOptionImage = true;

$(document).ready(function() {
    $("#productOptionsControls input, #productOptionsControls label").click(function() {
        var optionId = $(this).val();
        SelectedOptionChanged(optionId);
    });
    $("#dimensions-select").change(function() {
        var optionId = $("#dimensions-select").val();
        SelectedOptionChanged(optionId);
    });
    $("#dims-select").change(function() {
        var optionId = $(this).val();
        SelectedOptionChanged(optionId);
    });
    $("#units-select").change(function() {
        units = $(this).val();
        updateMeasurementUnits();
    });
    $("#assembly-popup-link").click(function(e) {
        e.preventDefault();
        showAssemblyWidgetPopup();
    });
    $("#shed-dimensions-tab-external").click(function() {
        showShedSizes("external");
    });
    $("#shed-dimensions-tab-internal").click(function() {
        showShedSizes("internal");
    });
    $("#technical-specifications table th, #technical-specifications table td").click(function() {
        var optionId = $(this).attr("rel");
        SelectedOptionChanged(optionId);
    });
    $("#technical-specifications-2 table th, #technical-specifications-2 table td").click(function() {
        var optionId = $(this).attr("rel");
        SelectedOptionChanged(optionId);
    });
    $("#tech-specs-change-units-select").change(function() {
        units = $(this).val();
        updateMeasurementUnits();
    });
    $("#upsell-better-link").click(function(e) {
        e.preventDefault();
        showUpsellBetterPopup();
    });
    $("#left-menu").hover(function() {
        $(this).find("h2").addClass("expanded");
        $(this).find(".parents").slideDown(200);
    }, function() {
        $("#left-menu .parents").slideUp(200, function() {
            $("#left-menu h2").removeClass("expanded");
        });
    });
    $("#left-menu .parents li").hover(function() {
        if (!$(this).hasClass("has-children")) return;
        $(this).addClass("hovered");
        $(this).find(".children").animate({
            width: "200px"
        }, { duration: 100, queue: false });
    }, function() {
        $(this).find(".children").animate({
            width: "0"
        }, { duration: 100, queue: false, complete: function() {
            $(this).parent().removeClass("hovered");
            $(this).hide();
        }
        });
    });
    $("#support-pane").hover(function() {
        $(this).addClass("expanded");
        $(this).find("#support-pane-content").animate({
            height: "208"
        }, { duration: 200, queue: false, complete: function() {
            //just make sure it still has the expanded class
            $(this).addClass("expanded");
        }
        });
    }, function() {
        $(this).find("#support-pane-content").animate({
            height: "33"
        }, { duration: 200, queue: false, complete: function() {
            $("#support-pane").removeClass("expanded");
        }
        });
    });
    $("#warranty-popup-link").click(function(e) {
        e.preventDefault();
        showWarrantyPopup();
    });
    $("#technical-images img").click(function() {
        showImagePopup($(this));
    });
    $(".delivery-process-explained").click(function(e) {
        e.preventDefault();
        triggerMacBox({
            boxID: "delivery-process-explained",
            width: 484,
            ajaxUrl: "/ProductPage4/AJAX/DeliveryProcess.aspx"
        });
    });
    $(".dblock-child-image").click(function(e) {
        e.preventDefault();
        //get it's rel so we know what element to put the big picture in
        var mainEle = $("#" + $(this).attr("rel"));
        //and use the href to get the image we need to show
        var childImgSrc = $(this).attr("href");
        $(mainEle).attr("src", childImgSrc);
    });
    $(".price-history-link").click(function(e) {
        e.preventDefault();
        showProductPriceHistoryPopup($(this).attr("rel"));
    });

    //view larger images and play product video buttons
    $("#product-images .view-larger-images, #product-images .view-larger-images-full").click(function(e) {
        e.preventDefault();
        $(".Main-Image-Link").click();
    });
    $("#product-images .view-product-video").click(function(e) {
        e.preventDefault();
        showProductVideoPopup("vimeo");
    });

    $(window).scroll(function() {
        var diff = $(document).height() - $(window).scrollTop();
        if (diff < 2000) {
            $("#scroll-down-image").animate({
                opacity: 0
            }, {
                duration: 200,
                queue: false
            });
        }
        else if ($("#scroll-down-image").css("opacity") == 0) {
            $("#scroll-down-image").animate({
                opacity: 1
            }, {
                duration: 200,
                queue: false
            });
        }
    });

    //set up handling for add to basket button
    var mainForm = $("#product-page-container").find("form")[0];
    $(mainForm).submit(function(e) {
        //see if there has been a postcode set so we know any surcharges are applied
        var postcodeEntered = $("#postcode-entered").val();
        if (postcodeEntered.length == 0) {
            e.preventDefault();
            if (typeof (showPleaseEnterPostCodeBox) != "undefined") {
                showPleaseEnterPostCodeBox();
            }
        }
    });

    //init
    SelectedOptionChanged(0);
    initDescriptionBlocks();
    initProductThumbnails();
    initCustomerImages();
    initAssemblyServiceDescription();
    // display all the object need javascript
    $(".js-required").removeClass("js-required");
});
