﻿
var useOptionImage = true;

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;
    }
    //clear the SelectedOptionalExtras and SelectedServices arrays
    SelectedOptionalExtras = [];
    SelectedServices = [];
    
    //clear all inputs in the customise-shed popup
    $(".customise-shed-container input").attr("checked", false);
    //and the checklists
    $(".customise-checklist").html("");
    $(".customise-checklist-tab").html("");
    
    //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");
    }
    // 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");
	
    //get the upsell link
    var foundOne = false;
    for (var idx = 0, len = ProductOptions.length; idx < len; idx++) {
        if (ProductOptions[idx].ID == CurrentOptionID) {
            //find the next available option if there is one
            for (var jdx = idx + 1, lenj = ProductOptions.length; jdx < lenj; jdx++) {
                if (ProductOptions[jdx].available) {
                    //this is what we want
                    //get the current option price
                    var idxPrice = ProductOptions[idx].price;
                    //get the 'upgrade' option price
                    var jdxPrice = ProductOptions[jdx].price;
                    //get the difference...
                    var differencePrice = jdxPrice - idxPrice;
                    //...and now make sure its formatted how we want it
                    differencePrice = RoundToDecimalPlaces(differencePrice, 2);
                    var upsellstring = "<a href='#' onclick='SelectedOptionChanged(" + ProductOptions[jdx].ID + "); return false;'>Click here to upgrade to the " + ProductOptions[jdx].name + " for an extra &pound;" + differencePrice + "</a>";
                    $("#option-upsell").html(upsellstring);
                    foundOne = true;
                    break;
                }
            }
            break;
        }
    }
    if (!foundOne) $("#option-upsell").html("");
    UpdatePagePrices();
	GetInstallationForm();
	
	//adjust any other dynamic content that depends on the selected option
	dimensionOptionChanged(CurrentOptionID);
	technicalSpecSelected(CurrentOptionID);
	if((!firstLoad)&&(useOptionImage)) {
	    selectOptionThumbnail(CurrentOptionID);
	}
	updateAssemblyInfo();
}

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);
    $("#checklist-price-" + ProductOption.ID + " span").html("&pound;" + totalPrice);
    
    //update the promotion prices
    if (ProductOption.price < 100.00) {
        $("#promotion-tag-container").hide();
    }
    else {
        var promotionPrice = parseFloat(totalPrice) - (0.05 * parseFloat(totalPrice));
        promotionPrice = (Math.round(promotionPrice*100)/100) + "";
        if (promotionPrice.indexOf(".") == -1) promotionPrice += ".00";
        else {
            if (promotionPrice.split(".")[1].length == 1) promotionPrice += "0";
        }
        $("#promotion-price").html(promotionPrice);
        var promotionSaving = 0.05 * parseFloat(totalPrice);
        promotionSaving = (Math.round(promotionSaving*100)/100) + "";
        if (promotionSaving.indexOf(".") == -1) promotionSaving += ".00";
        else {
            if (promotionSaving.split(".")[1].length == 1) promotionSaving += "0";
        }
        $("#promotion-saving").html(promotionSaving);
        $("#promotion-tag-container").show();
    }
    
    //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) {
    if ($("#DeliveryInformation").get(0) != null) {
        showRyMacBox("DeliveryInformation");
    }
    else 
    {
        var deliveryPageUrl = "/DeliveryInformation/" + deliveryPage + ".aspx";
        $.ajax({
            type: "GET",
            url: deliveryPageUrl,
            success: function(data, status) {
                var deliveryMacboxContainer = document.createElement("div");
                $(deliveryMacboxContainer).attr("id", "delivery-area-info");
                $(deliveryMacboxContainer).append(data);
                $("body").append(deliveryMacboxContainer);
                var deliveryMacBox = new RyMacBox("DeliveryInformation", "html|delivery-area-info", 700, 1, $("body").get(0), {}, {}, function() { showRyMacBox("DeliveryInformation"); }, true);
                $("#delivery-ajax-info div").show();
            },
            error: function(ajaxObj, status, error) {
                
            }
        });
    }
}

function initOptionalExtras() {
    $("#select-extras").click(function(e) {
        e.preventDefault();
        showOptionalExtrasPopup(GetSelectedOption().ID);
    });
}
function getSubOption(id) {
    for (var idx = 0, len = OptionalExtras.length; idx < len; idx++) {
        if (OptionalExtras[idx].ID == id) {
            return OptionalExtras[idx];
        }
    }
    return null;
}
function showOptionalExtrasPopup(optionId) {
    if ($("#OptionalExtras" + optionId).get(0) != null) {
        gotoCustomiseStep(1);
        showRyMacBox("OptionalExtras" + optionId);
        initChecklistTab(optionId);
        UpdatePagePrices();
    }
    else {
        var optionalExtrasUrl = "/ProductPage2/AJAX/OptionalExtras.aspx";
        $.ajax({
            type: "POST",
            url: optionalExtrasUrl,
            data: "ProductOptionID=" + optionId,
            success: function(data, status) {
                var optionalExtrasMBContainer = document.createElement("div");
                $(optionalExtrasMBContainer).attr("id", "optional-extras" + optionId);
                $(optionalExtrasMBContainer).append(data);
                $("body").append(optionalExtrasMBContainer);
                var optExtrasMacBox = new RyMacBox("OptionalExtras" + optionId, "html|optional-extras" + optionId, 740, 1, 
                    $("#product-options-container").get(0), {}, {}, function() {
                        showRyMacBox("OptionalExtras" + optionId);
                        initChecklistTab(optionId);
                        UpdatePagePrices();
                        $("#cancel-suboptions-" + optionId).click(function() {
                            cancelOptionalExtras();
                            hideRyMacBox("OptionalExtras" + optionId);
                        });
                    }, true, "round");
                initOptionalExtrasEvents();
            },
            error: function(ajaxObj, status, error) {
                
            }
        });
    }
}
function initChecklistTab(optionId) {
    var checklistTab = {};
    if ($("#checklist-tab-" + optionId).get(0) == undefined) {
        //we need to create it
        checklistTab = document.createElement("div");
        $(checklistTab).attr("id", "checklist-tab-" + optionId);
        $(checklistTab).attr("class", "checklist-tab");
        $("#OptionalExtras" + optionId).append(checklistTab);
        
        //top bit
        var checklistTabTop = document.createElement("div");
        $(checklistTabTop).attr("class", "checklist-tab-top");
        $(checklistTab).append(checklistTabTop);
        
        //middle bit
        var checklistTabMiddle = document.createElement("div");
        $(checklistTabMiddle).attr("class", "checklist-tab-middle");
        $(checklistTab).append(checklistTabMiddle);
        var checklist = document.createElement("ul");
        $(checklist).attr("class", "customise-checklist-tab");
        $(checklistTabMiddle).append(checklist);
        
        //bottom bit        
        var checklistTabBottom = document.createElement("div");
        $(checklistTabBottom).attr("class", "checklist-tab-bottom");
        $(checklistTab).append(checklistTabBottom);
        var priceContainer = document.createElement("div");
        $(priceContainer).attr("id", "checklist-price-" + optionId);
        $(priceContainer).attr("class", "checklist-price");
        $(priceContainer).html("Total Price: ");
        $(checklistTabBottom).append(priceContainer);
        var price = document.createElement("span");
        $(priceContainer).append(price);
        var delText = document.createElement("div");
        $(delText).attr("id", "checklist-del-text-" + optionId);
        $(delText).attr("class", "checklist-del-text");
        $(delText).html("Price includes VAT and <a href=\"/Delivery\">Delivery</a>");
        $(checklistTabBottom).append(delText);
    }
}
function gotoCustomiseStep(step) {
    $(".customise-step").hide();
    $(".customise-step-" + step).show();
    $(".customise-titles").attr("class", "customise-titles customise-titles-step-" + step);
}
function cancelOptionalExtras() {
    SelectedOptionalExtras = [];
    //clear all inputs in the customise-shed popup
    $(".customise-shed-container input").attr("checked", false);
    //and the checklists
    $(".customise-checklist").html("");
    $(".customise-checklist-tab").html("");
    UpdatePagePrices();
}
function initOptionalExtrasEvents() {
    $(".customise-shed-container input").click(function() {
		SelectExtraOptionChange($(this).get(0));
	});
    $(".customise-titles-selectors li").click(function() {
        var step = $(this).attr("rel").replace(/step-/ig, "");
        gotoCustomiseStep(step);
    });
    $(".customise-shed-container input").each(function() {
        var jObj = $(this);
        //get the id of this element so we can work out which sub option is selected
        var id = jObj.attr("id");
        //the sub option id will be the last part if split on '-'
        var lastHyphen = id.lastIndexOf("-");
        id = id.substr(lastHyphen + 1);

        for (var idx = 0; idx < SelectedOptionalExtras.length; idx++) {
            // Check if this optional extras is selected or not
            if (SelectedOptionalExtras[idx].ID == id) {
                // Update the checkbox
                $(this).attr("checked", true)
                //should only be one in there so break here
                break;
            }
        }
        // Update the checklist
        updateCustomiseChecklist();
    });    
}
function SelectExtraOptionChange(object) {
	var jObj = $(object);
	//get the id of this element so we can work out which sub option is selected
	var id = jObj .attr("id");
	//the sub option id will be the last part if split on '-'
	var lastHyphen = id.lastIndexOf("-");
	id = id.substr(lastHyphen + 1);
	//decide whether we're adding it to the selected list or taking it away
	if (jObj .attr("checked")) {
		//add it
		//if it's a radio button we treat things a little differently
		if (jObj .attr("type") == "radio") {
			//it's from a group of sub options, so we need to remove all related sub options from the selected list
			//get the input name for the group
			var name = jObj .attr("name");
			//look for radio buttons with this name
			var eles = $(".customise-shed-container input[name=" + name + "]");
			//for each of these eles, grab the id and make sure it's not in the selected list
			for (var idx = 0; idx < eles.length; idx++) {
				var curId = $(eles[idx]).attr("id");
				lastHyphen = curId.lastIndexOf("-");
				curId = curId.substr(lastHyphen + 1);
				//check the selected list to make sure this isn't in there
				for (var jdx = 0; jdx < SelectedOptionalExtras.length; jdx++) {
					if (SelectedOptionalExtras[jdx].ID == curId) {
						SelectedOptionalExtras.splice(jdx, 1);
						//should only be one in there so break here
						break;
					}
				}
			}
		}
		//now we're all in order!
		//if this element is not the 'none' one (value of -1) we can add it to the list
		if ($(this).val() != -1) {
			var thisSubOp = getSubOption(id);
			if (thisSubOp != null) {
				SelectedOptionalExtras.push(thisSubOp);
			}

        }
        updateCheckboxes(id, true);
	}
	else {
		//take it out
		for (var idx = 0; idx < SelectedOptionalExtras.length; idx++) {
			if (SelectedOptionalExtras[idx].ID == id) {
				SelectedOptionalExtras.splice(idx, 1);
			}
		}
		updateCheckboxes(id, false);
	}
	//put the selected sub options into a hidden input for the add to basket button
	var subOpsString = "";
	for (var idx = 0, len = SelectedOptionalExtras.length; idx < len; idx++) {
		subOpsString += SelectedOptionalExtras[idx].ID;
		if (idx < len - 1) subOpsString += ",";
	}
	$("#suboptions-main").val(subOpsString);
	updateCustomiseChecklist();
	UpdatePagePrices();
}

// sync the checkbox and button when a optional extra add or remove from the basket
function updateCheckboxes(subOptId, val) {
    // Change the button image for the up sell slider
    if (val) {
        $("#suboptionbutton-" + subOptId).attr("src", "/productpage2/assets/images/smallRemoveFromBasket.gif");
    } else {
        $("#suboptionbutton-" + subOptId).attr("src", "/productpage2/assets/images/smallAddtoBasket.gif");
    }
    
    $("#subOptId-" + subOptId).attr("checked", val);
    $("#treatment-item-" + subOptId).attr("checked", val);
    $("#tool-item-" + subOptId).attr("checked", val);
    $("#accessory-item-" + subOptId).attr("checked", val);
}

function updateCustomiseChecklist() {
    var checklist = "";
    var checklistTab = "";
    for (var idx = 0, len = SelectedOptionalExtras.length; idx < len; idx++) {
        var price = SelectedOptionalExtras[idx].price + "";
        if (price.indexOf(".") != -1) {
            //if there is only one number after the . then add a 0
            if (price.split(".")[1].length == 1) {
                price += "0";
            }
        }
        //no . so just add .00 to the end of the price
        else {
            price += ".00";
        }
        checklist += "<li><img src=\"/images/products/" + SelectedOptionalExtras[idx].thumbImage + "\" />" + 
             SelectedOptionalExtras[idx].name + " - " + SelectedOptionalExtras[idx].subName + 
             " <span>&pound;" + price + "</span></li>";
        checklistTab += "<li>" + SelectedOptionalExtras[idx].subName + " <span>&pound;" + price + "</span></li>";
    }
    $(".customise-checklist").html(checklist);
    $(".customise-checklist-tab").html(checklistTab);
}

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 showBillyOhAdvantagePopup() {
    triggerMacBox({
        boxID: "BillyOhAdvantagePopup",
        width: 742,
        ajaxUrl: "/ProductPage2/AJAX/BillyOhAdvantage.aspx"
    });
}
function showDeliveryProcessPopup() {
    triggerMacBox({
        boxID: "DeliveryProcessPopup",
        width: 484,
        ajaxUrl: "/ProductPage2/AJAX/DeliveryProcess.aspx"
    });
}

function showAssemblyWidgetPopup() {
    if ($("#AssemblyWidgetPopup").get(0) != null) {
        showRyMacBox("AssemblyWidgetPopup");
    }
    else {
        var billyOhAdvantageUrl = "/ProductPage2/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: "/ProductPage2/AJAX/ShedAssemblyServices.aspx"
        });
        e.preventDefault();
    });
    $(".extras-container #assembly-note .logcabin").live("click", function(e) {
        triggerMacBox({
            boxID: "assembly-service-description",
            width: 780,
            ajaxUrl: "/ProductPage2/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));
}
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"));
    });    
}

// Up sale slider
function initUpSaleSlider(){
	// Control the slider
    $("#up-sell-slider #slider-next").click(function() {
        // Just get basic information
        var ulObj = $("#up-sell-slider #slider-body .displaying");
        var ulWidth = ulObj.width();
        var ulLeft = ulObj.position().left;
        var liWidth = ulObj.find("li").outerWidth(true);
        // See if the next move is outsite of the list or not
        if (ulLeft - liWidth * 4 > -ulWidth) {
            ulObj.css("left",ulLeft - liWidth * 4);
        } else {
            // Move the the first round if this is the last round already
            ulObj.css("left", 0);
        }
    });
    $("#up-sell-slider #slider-prev").click(function() {
	    // Just get basic information
	    var ulObj = $("#up-sell-slider #slider-body .displaying");
	    var ulWidth = ulObj.width();
	    var ulLeft = ulObj.position().left;
	    var liWidth = ulObj.find("li").outerWidth(true);
	    // See if the next move is outsite of the list or not
	    if (ulLeft + liWidth * 4 <= 0) {
	        ulObj.css("left", ulLeft + liWidth * 4);
	    } else {
	        // Move to the last row if this is the first round already
	    ulObj.css("left", -ulWidth + liWidth * 4);
	    }
	});
	$("#slider-body .subOptionSliderAddButton").click(function() {
	    var obj = $("#suboptioninput-" + $(this).attr("rel"));
        obj.attr("checked", !obj.attr("checked"));
        SelectExtraOptionChange(obj.get(0));
	});
	$("#slider-body .upsell-sub-option").click(function(e) {
	    e.preventDefault();
	    var subOpId = $(this).attr("rel");
	    triggerSubOptionMacBox(subOpId);
	});
	$("#slider-body .sub-name a").click(function(e) {
	    e.preventDefault();
	    var subOpId = $(this).attr("rel");
	    triggerSubOptionMacBox(subOpId);
	});
}
function triggerSubOptionMacBox(subOpId) {
    triggerMacBox({
        boxID: "sub-option-info-" + subOpId,
        width: 600,
        ajaxUrl: "/ProductPage3/AJAX/SubOptionInformation.aspx?SubOptionID=" + subOpId
    });
}

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 = "/ProductPage2/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: '/ProductPage2/AJAX/AJAXCustomerImages.aspx',
	        ajaxData: 'productID=' + $(this).attr("rev")
	    });	    
	    triggeruBox();
	});
}

function dimensionOptionChanged(optionId) {
    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[index].shedType == "apex")||(dimensionValues[index].shedType == "bigbarn")) {
        $("#dimension-ridge").html(dimensionValues[index].ridge);
        $("#dimension-eaves").html(dimensionValues[index].eaves);
        $("#dimension-door-width").html(dimensionValues[index].doorWidth);
        $("#dimension-door-height").html(dimensionValues[index].doorHeight);
        $("#dimension-width").html(dimensionValues[index].width);
        $("#dimension-depth").html(dimensionValues[index].depth);
        $("#dimension-width-internal").html(dimensionValues[index].widthInternal);
        $("#dimension-depth-internal").html(dimensionValues[index].depthInternal);
        $("#dimension-eaves-internal").html(dimensionValues[index].eavesInternal);
        $("#dimension-ridge-internal").html(dimensionValues[index].ridgeInternal);
        $("#dimension-floor-area-internal").html(dimensionValues[index].areaFloorInternal);
    }
    else if (dimensionValues[index].shedType == "pent") {
        $("#dimension-front").html(dimensionValues[index].ridge);
        $("#dimension-back").html(dimensionValues[index].eaves);
        $("#dimension-door-width").html(dimensionValues[index].doorWidth);
        $("#dimension-door-height").html(dimensionValues[index].doorHeight);
        $("#dimension-width").html(dimensionValues[index].width);
        $("#dimension-depth").html(dimensionValues[index].depth);
        $("#dimension-width-internal").html(dimensionValues[index].widthInternal);
        $("#dimension-depth-internal").html(dimensionValues[index].depthInternal);
        $("#dimension-back-internal").html(dimensionValues[index].eavesInternal);
        $("#dimension-front-internal").html(dimensionValues[index].ridgeInternal);
        $("#dimension-floor-area-internal").html(dimensionValues[index].areaFloorInternal);
    }
    else if (dimensionValues[index].shedType == "cornershed") {
        $("#dimension-front").html(dimensionValues[index].ridge);
        $("#dimension-back").html(dimensionValues[index].eaves);
        $("#dimension-door-width").html(dimensionValues[index].doorWidth);
        $("#dimension-door-height").html(dimensionValues[index].doorHeight);
        $("#dimension-width").html(dimensionValues[index].width);
        $("#dimension-depth").html(dimensionValues[index].depth);
        $("#dimension-gable-door").html(dimensionValues[index].doorGable);
        $("#dimension-gable-window").html(dimensionValues[index].windowGable);
        $("#dimension-gable-plain").html(dimensionValues[index].plainGable);
        $("#dimension-gable-plain-internal").html(dimensionValues[index].plainGableInternal);
        $("#dimension-gable-door-internal").html(dimensionValues[index].doorGableInternal);
        $("#dimension-gable-window-internal").html(dimensionValues[index].windowGableInternal);
        $("#dimension-back-internal").html(dimensionValues[index].eavesInternal);
        $("#dimension-floor-area-internal").html(dimensionValues[index].areaFloorInternal);
    }
    
    //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) {
    $("#product-page-container #main-column #technical-specifications table th, #product-page-container #main-column #technical-specifications table td").removeClass("selected");
    $("*[rel=" + rel + "]").addClass("selected");
}

//some global variables
var Product = {};
var ProductOptions = [];
var OptionalExtras = [];
var SelectedOption = {};
var SelectedOptionalExtras = [];
var SelectedServices = [];

$(document).ready(function() {
    //events
	$("#productOptionsControls input, #productOptionsControls label").click(function(){
        SelectedOptionChanged();
    });
    $("#dimensions-select").change(function() {
        var optionId = $("#dimensions-select").val();
        SelectedOptionChanged(optionId);
    });
    $("#billyoh-advantage, #billyoh-advantage-link, #product-features .feature-row div").click(function(e) {
        e.preventDefault();
        showBillyOhAdvantagePopup();
    });
    $("#delivery-process").click(function(e) {
        e.preventDefault();
        showDeliveryProcessPopup();
    });
    $("#assembly-popup-link").click(function(e) {
        e.preventDefault();
        showAssemblyWidgetPopup();
    });
    $("#add-button").click(function(e) {
        if (SelectedOptionalExtras.length == 0) {
            e.preventDefault();
            showOptionalExtrasPopup(GetSelectedOption().ID);
        }
    });
    $("#add-to-basket-table .add-button").click(function() {
        if (SelectedOptionalExtras.length == 0) {
            showOptionalExtrasPopup(GetSelectedOption().ID);
        }
        else {
            submitAtbForm();
        }
    });
    $("#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);
    });
    $("#tech-specs-change-units-select").change(function() {
        if ($(this).val() == "met") {
            $("#technical-specifications .met").show();
            $("#technical-specifications .imp").hide();
        }
        else {
            $("#technical-specifications .met").hide();
            $("#technical-specifications .imp").show();
        }
    });
    $("#upsell-better-link").click(function(e) {
        e.preventDefault();
        showUpsellBetterPopup();
    });
    
    //init
    initOptionalExtras();
    initDescriptionBlocks();
    initProductThumbnails(); 
    SelectedOptionChanged(0);
	initCustomerImages();
	initUpSaleSlider();
	initAssemblyServiceDescription();

	// display all the object need javascript
	$(".js-required").removeClass("js-required");
});

// 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;
}
////
