﻿// 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");
        
        // 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 = "<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", "");
    
    //get the various options
    getOptionalExtras(ProductOptionID);
    getTreatmentOptions(ProductOptionID);
    getDeliveryDetails(ProductOptionID);    
}

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].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 = "";
function getOptionalExtras(ProductOptionID) {
    $.ajax({
        type: "POST",
        url: "/ProductPage4/AJAX/OptionalExtras.aspx",
        data: "ProductOptionID=" + ProductOptionID + "&date=" + Date(),
        success: function(data, textStatus) { 
            $("#optional-extras").html(data);
            //set up the click events for the newly aquired sub options
            $("#optional-extras input").click(function() {
                SelectOptionalExtraChanged($(this));
            });
            //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);
        }
    });
}

function getDeliveryDetails(ProductOptionID) {
    if (ProductOptionID == null) {
        ProductOptionID = GetSelectedOption().ID;
    }
    $.ajax({
        type: "GET",
        url: "/ProductPage4/AJAX/AJAXSubOptionsDelivery.aspx?ProductOptionID=" + ProductOptionID + "&date=" + Date(),
        success: function(data, textStatus) { 
            $("#delivery-details").html(data);
        },
        error: function(ajaxObj, textStatus, errorThrown) {
        
        }
    });
}

function getTreatmentOptions(ProductOptionID) {
    if (ProductOptionID == null) {
        ProductOptionID = GetSelectedOption().ID;
    }
    $.ajax({
        type: "POST",
        url: "/ProductPage4/AJAX/TreatmentOptions.aspx",
        data: "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 = "";
    if (SelectedOptionalExtras.length == 0) {
        totalPriceText = "&pound;" + totalPrice;
    }
    else {
        totalPriceText = "&pound;" + totalPrice + "<br /><small>(with extras)</small>";
    }
    $("#price").html(totalPriceText);
    
    //update the tech spec prices
    resetTechSpecPrices();
    $("#tech-spec-price-" + ProductOption.ID).html("&pound;" + totalPrice + ((SelectedOptionalExtras.length > 0) ? "<br />(with extras)" : ""));
}

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, ""));
    var top = $(ele).position().top - ($(popup).height() + paddingTop + paddingBottom);
    $(popup).css("top", top);
    $(popup).css("left", $(ele).position().left - 10);
}
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) {
    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() {
    $(".extras-container #assembly-note .shed").live("click", function(e) {
        triggerMacBox({
            boxID: "assembly-service-description",
            width: 780,
            ajaxUrl: "/ProductPage4/AJAX/ShedAssemblyServices.aspx"
        });
        e.preventDefault();
    });
    $(".extras-container #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"));
    $(".MainImageCaption").html($(obj).attr("title"));
}

function initProductThumbnails() {
    //When user click on the image show up the ubox
    $(".ShowUBox").click(function(e){
        setuBox({
            source: $(this).find("img").attr("rel"),
            caption: $("#product-images .MainImageCaption").text(),
            listObj: $("#image-controls #ThumbnailsList")
        });
        triggeruBox();
        e.preventDefault();
    });
    //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: "POST",
            url: upsellBetterUrl,
            data: "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]);
    }
}

//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");
            }
        });
    });
    $("#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"
        });
    });
    
    //set up handling for add to basket button
    var mainForm = $("#product-page-container").find("form")[0];
    $(mainForm).submit(function(e){
        //get the store id to see if we're doing the postcode check
        if (typeof(forcePostcode) == "undefined") return;
        if (!forcePostcode()) return;
        
        //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");
	
//	//datepicker
//	var earliestDate = new Date();
//	earliestDate.setDate(earliestDate.getDate() + 5);
//	var latestDate = new Date();
//	latestDate.setDate(earliestDate.getDate() + 14);
//	$("#datepicker").datepicker({
//	    minDate: earliestDate,
//	    maxDate: latestDate,
//	    onSelect: function(dateText, inst) {
//	        var things = "";
//	        for(var thing in inst) {
//	            things += thing + "|";
//	        }
//	        var selectedYear = inst.selectedYear;
//	        var selectedMonth = inst.selectedMonth;
//	        var selectedDay = inst.selectedDay;
//	        $("#datepicker-choice").html("You have chosen to have your product delivered on <b>" + selectedDay + "/" + selectedMonth + "/" + selectedYear + "</b>. Please add this product to the basket to proceed.");
//	        $("#designated-delivery").val(selectedDay + "-" + selectedMonth + "-" + selectedYear);
//	    }
//	});
//	$("#designated-delivery").val("null");
});