﻿// Initialise JavaScript namespaces.

Website = {};
Website.Base = {};
Website.Base.QueryString = {};

Website.Tooltip = {};

Website.Ratings = {};
Website.SecondaryMenu = {};
Website.SecondaryMenu.RefineSearch = {};

Website.Products = {};
Website.Products.Details = {};
Website.Products.Details.Tabs = {};

Website.VideoPlaylist = { };

Website.ShoppingCart = {};
Website.WishList = {};

Website.Base.Init = function() {
	if (window.name == "TB_iframeContent") {
		window.document.body.addClass("popup");
	}
}

Website.VideoPlaylist.Init = function(name, baseUrl, folder) {
	var container = $(name);
	var linkList = container.getElements("LI LI A");

	for (var index = 0; index < linkList.length; index++) {
		var link = linkList[index];
		link.VideoUrl = baseUrl + "videos/" + folder + "/" + link.getParent().getProperty("class") + ".flv";
		link.VideoQuality = link.text;

		link.addEvent("click", function() { Website.VideoPlaylist.Click(this); });
	}
}

Website.VideoPlaylist.Click = function(link) {
	var flashvars = { };
	flashvars.videoURL = link.VideoUrl;
	flashvars.skinURL = "/App_Assets/swf/SkinOverPlaySeekMute.swf";
	flashvars.autoPlay = "false";
    flashvars.videoWidth = "350";
    flashvars.videoHeight = "319";

    if (swfobject.getQueryParamValue("mode")) {
        flashvars.mode = swfobject.getQueryParamValue("mode");
    }

    var params = {};
    var attributes = {};
    attributes.id = "flashcontent";
    swfobject.embedSWF("/App_Assets/swf/gbstVideoPlayer.swf", "flashcontent", "350", "319", "9.0.45", false, flashvars, params, attributes);
}

Website.Base.Logout = function() {
	var link = "http://" + window.location.host + window.location.pathname + window.location.search;

	if (link.indexOf("?") < 0) {
		link += "?";
	} else if (link.lastIndexOf("&") != link.length - 1) {
		link += "&";
	}

	link += "logout=true";
	window.location = link;

	return false;
}

Website.Base.GetEventKeyCode = function(e) {
	if (window.event) {
		return e.keyCode;
	} else if (e.which) {
		return e.which;
	}
}

Website.Base.GetEventCaller = function(e) {
	if (window.event) {
		return e.srcElement;
	} else if (e.which) {
		return e.target;
	}
}

Website.Base.SetDefaultText = function(itemID) {
	var item = $(itemID);

	if (item.type == "text" && item.title != null && item.title != '') {
		item.addEvent("focus", function() { Website.Base.DefaultTextFocus(this); });
		item.addEvent("blur", function() { Website.Base.DefaultTextBlur(this); });

		Website.Base.DefaultTextBlur(item);
	}
}

Website.Base.DefaultTextFocus = function(input) {
	if (input.title == input.value) {
		input.value = '';
		input.removeClass("inputTitle");
	}
}

Website.Base.DefaultTextBlur = function(input) {
	if (input.value == '') {
		input.value = input.title;
		input.addClass("inputTitle");
	}
}

Website.Base.ValidateLightboxLocation = function(redirect) {
	if (window.parent == null || window.parent == undefined || window == window.parent) {
		window.location = redirect;
	}
}

Website.Base.VerifySearch = function() {
	var input = $("searchKeywords");

	if (input.value == '' || input.value == input.title) {
		Website.Tooltip.Show("shoppingCartTooltipWarning", "Please enter some search terms.");
		Website.Tooltip.Hide();

		return false;
	} else {
		return true;
	}
}

Website.Base.CheckErrors = function() {
	Page_ClientValidate();

	if (!Page_IsValid) {
		Website.Tooltip.Show("shoppingCartTooltipError", "Sorry, but there were errors in your submission.");
		Website.Tooltip.Hide();
	}
}

Website.Base.GetInputs = function(list, names) {
	var nameList = names.split(",");
	var result = new Array();

	for (var n = 0; n < nameList.length; n++) {
		result[nameList[n]] = null;
	}

	for (var i = 0; i < list.length; i++) {
		var input = list[i];

		if (input && input.id) {
			for (var n = 0; n < nameList.length; n++) {
				var name = nameList[n];

				if (name && input.id.indexOf(name) > -1) {
					result[name] = input;
				}
			}
		}
	}

	return result;
}

Website.Tooltip.Timeout = null;
Website.Tooltip.ID = "ShoppingCartTooltip";
Website.Tooltip.Class = "shoppingCartTooltip";
Website.Tooltip.IsVisible = false;

Website.Tooltip.Init = function() {

	// Create tooltip element.
	var element = new Element("div");
	element.setProperty("id", Website.Tooltip.ID);
	element.addClass(Website.Tooltip.Class);

	element.inject($(document.body));

	// Attach tooltip to mouse.
	$(document.body).addEvent("mousemove", Website.Tooltip.MouseMove);
	$(document.body).addEvent("mousedown", Website.Tooltip.MouseClick);
}

Website.Tooltip.MouseMove = function(e) {
	if (Website.Tooltip.IsVisible) {
		Website.Tooltip.MouseEvent(e);
	}
}

Website.Tooltip.MouseClick = function(e) {
	Website.Tooltip.MouseEvent(e);
}

Website.Tooltip.MouseEvent = function(e) {
	Website.Tooltip.AdjustPosition(e.page.x + 20, e.page.y - 10);
}

Website.Tooltip.AdjustPosition = function(x, y) {
	var element = $(Website.Tooltip.ID);

	element.setStyle('top', y);
	element.setStyle('left', x);
}

Website.Tooltip.Show = function(className, str) {
	var element = $(Website.Tooltip.ID);
	clearTimeout(Website.Tooltip.Timeout);

	if (element.Effect != null) {
		element.Effect.cancel();
	}

	element.setProperty("class", Website.Tooltip.Class);

	if (className) {
		element.addClass(className);
	}

	element.set("text", str);
	element.setStyle("opacity", 1);
	element.setStyle("display", "block");

	Website.Tooltip.IsVisible = true;
}

Website.Tooltip.Hide = function() {
	Website.Tooltip.Timeout = setTimeout(Website.Tooltip.Hide_Fade, 3000);
}

Website.Tooltip.Hide_Fade = function() {
	var element = $(Website.Tooltip.ID);

	function Complete() {
		element.setStyle("display", "none");
		element.setStyle("opacity", 1);

		Website.Tooltip.IsVisible = false;
	}

	element.Effect = new Fx.Morph(element, { onComplete: Complete });
	element.Effect.start({ opacity: "0.01" });
}

Website.Base.QueryString.Tokenize = function(path) {
	var pathSplit = path.split("?");
	var location = pathSplit[0];
	var query = (pathSplit.length > 1 ? pathSplit[1] : "");

	var querySplit = query.split("&");
	var querystring = new Array();

	for (var i = 0; i < querySplit.length; i++) {
		var item = querySplit[i];

		if (item != null && item.length > 0) {
			var itemSplit = item.split("=");
			var key = itemSplit[0];
			var value = (itemSplit.length > 1 ? itemSplit[1] : null);

			querystring.push({ "Key": key, "Value": value });
		}
	}

	return { "Location": location, "QueryString": querystring };
}

Website.Base.QueryString.Add = function(path, key, value) {
	var data = Website.Base.QueryString.Tokenize(path);

	var found = false;
	var string = "";

	function insert(k, v) {
		if (string.length > 0) { string += "&"; }

		if (v == null) {
			string += k;
		} else {
			string += k + "=" + v;
		}
	}

	// Check if the key already exists.
	for (var i = 0; i < data["QueryString"].length; i++) {
		if (data["QueryString"][i]["Key"].toLowerCase() == key.toLowerCase()) {
			data["QueryString"][i]["Value"] = value;
			found = true;
		}

		insert(data["QueryString"][i]["Key"], data["QueryString"][i]["Value"]);
	}

	// If data not found, then add to the end.
	if (!found) { insert(key, value); }

	path = data["Location"] + "?" + string;
	return path;
}

Website.SecondaryMenu.Init = function(name, header, content, showIndex) {
	var menu = new Accordion($(name), header, content, {
		opacity: false,
		show: showIndex,
		onActive: function(toggler, element) {
			if (element.getElements("LI").length > 0) {
				toggler.addClass("menuItemActive");
			}
		},

		onBackground: function(toggler, element) {
			setTimeout(function() { toggler.removeClass("menuItemActive") }, 500);
		}
	});
}

Website.Products.FilterByPrice = function(priceFilterFromInput, priceFilterToInput) {
	var inputs = Website.Base.GetInputs($("aspnetForm").getElements("INPUT[type=hidden]"), "cPriceFilterFrom,cPriceFilterTo,cProductListRepeater_PAGE");
	var fromPrice = inputs["cPriceFilterFrom"];
	var toPrice = inputs["cPriceFilterTo"];

	priceFilterFromInput = $(priceFilterFromInput);
	priceFilterToInput = $(priceFilterToInput);

	if (priceFilterFromInput && priceFilterToInput && fromPrice && toPrice) {
		fromPrice.value = priceFilterFromInput.value;
		toPrice.value = priceFilterToInput.value;

		var page = inputs["cProductListRepeater_PAGE"];
		
		if (page) {
			page.value = 1;
		}

		__doPostBack('', '');
	}
}

Website.Products.FilterByProductVariant = function(checkbox, name, filterName) {
	Website.Products.Filter(checkbox, name, filterName);
}

Website.Products.FilterByArticeType = function(checkbox, name) {
	Website.Products.Filter(checkbox, name, "cArticleTypeFilter");
}

Website.Products.FilterByBrand = function(checkbox, name) {
	var inputs = Website.Base.GetInputs($("aspnetForm").getElements("INPUT[type=hidden]"), "cBrandSubFilter");
	var sub = inputs["cBrandSubFilter"];
	sub.value = '';

	Website.Products.Filter(checkbox, name, "cBrandFilter");
}

Website.Products.FilterByBrandSub = function(checkbox, name) {
	Website.Products.Filter(checkbox, name, "cBrandSubFilter");
}

Website.Products.Filter = function(checkbox, name, filterName) {
	var inputs = Website.Base.GetInputs($("aspnetForm").getElements("INPUT[type=hidden]"), filterName + ",cProductListRepeater_PAGE");

	var page = inputs["cProductListRepeater_PAGE"];
	var input = inputs[filterName];

	var text = name + "|";
	var inputValue = input.value;

	text = text.replace("\'", "'");
	text = text.replace("'", "''");

	if (checkbox.checked) {
		inputValue += text;
	} else {
		inputValue = inputValue.replace(text, "");
	}

	if (page) {
		page.value = 1;
	}

	input.value = inputValue;
	__doPostBack('', '');
}

Website.Products.Details.isMSIE = (navigator.userAgent.indexOf("MSIE") > -1) ? true : false;
Website.Products.Details.isMSIE6 = (navigator.userAgent.indexOf("MSIE 6") > -1) ? true : false;

Website.Products.Details.Tabs.TabReviews = null;

Website.Products.Details.Tabs.TabsLeft = null;
Website.Products.Details.Tabs.Panels = null;
Website.Products.Details.Tabs.ActiveTab = null;

Website.Products.Details.Tabs.Init = function(root, selectedTab) {
	var panels = $(root).getElements(".productPanel");
	var container = $(root).getElement(".productTabsInner");
	var template = container.getElement(".productTemplateTab");

	Website.Products.Details.Tabs.TabsLeft = $(root).getElement(".productTabsLeft");

	var tabCount = 0;
	var link = null;

	Website.Products.Details.Tabs.Panels = panels;

	if (panels.length > 0 && container != null && template != null) {
		for (var p = 0; p < panels.length; p++) {
			var id = panels[p].id.replace("productTab-", "");
			var header = panels[p].getElement("H2");

			// Create a tab.
			if (header != null) {
				link = template.clone();
				var inner = link.getElement(".productTabMiddle");

				link.removeClass("productTemplateTab");
				link.setProperty("id", $(root).getProperty("id") + "_productTab_" + p);
				link.Panel = p;
				link.ReferenceID = id;

				if (tabCount == 0) {
					link.addClass("productTabFirst");
				}

				header.inject(inner);
				link.addEvent("click", function() { Website.Products.Details.Tabs.Click(this); });

				link.inject(container);
				tabCount++;

				Website.Products.Details.Tabs.Hide(link);

				if (id == selectedTab) {
					Website.Products.Details.Tabs.Click(link);
				}

				if (id == "reviews") {
					Website.Products.Details.Tabs.TabReviews = link;
				}
			}
		}
	}

	if (link != null) {
		link.addClass("productTabLast");
	}

	Website.Products.Details.Tabs.Panels = panels;
}

Website.Products.Details.Tabs.Click = function(tab) {
	if (Website.Products.Details.Tabs.ActiveTab != null) {
		Website.Products.Details.Tabs.Hide(Website.Products.Details.Tabs.ActiveTab);
	}

	Website.Products.Details.Tabs.Show(tab);
	Website.Products.Details.Tabs.ActiveTab = tab;

	var location = window.location.href;
	var split = location.split('#');

	location = split[0];
	window.location = location + "#" + tab.ReferenceID;
}

Website.Products.Details.Tabs.Show = function(tab) {
	var panel = Website.Products.Details.Tabs.Panels[tab.Panel];

	if (Website.Products.Details.Tabs.TabsLeft != null) {
		if (tab.Panel == 0) {
			Website.Products.Details.Tabs.TabsLeft.addClass("productTabsSelectedLeft");
		} else {
			Website.Products.Details.Tabs.TabsLeft.removeClass("productTabsSelectedLeft");
		}
	}

	if (panel != null) {
		tab.addClass("productTabSelected");
		if (tab.Panel > 0) { tab.addClass("productTabSelectedSpecial"); }
		panel.setStyle("display", "block");
	}
}

Website.Products.Details.Tabs.Hide = function(tab) {
	var panel = Website.Products.Details.Tabs.Panels[tab.Panel];

	if (panel != null) {
		tab.removeClass("productTabSelected");
		tab.removeClass("productTabSelectedSpecial");
		panel.setStyle("display", "none");
	}
}

Website.Products.Details.Tabs.ShowReviews = function() {
	if (Website.Products.Details.Tabs.TabReviews) {
		Website.Products.Details.Tabs.Click(Website.Products.Details.Tabs.TabReviews);
	}
}

Website.Products.Details.InitStars = function(starContainer) {
	var container = $(starContainer);
	var stars = container.getElements(".stars");

	for (var s = 0; s < stars.length; s++) {
		var star = stars[s];
		var overlay = star.getElement(".starsOverlay");
		var link = overlay.getElement(".starsLinks");

		if (overlay && link) {
			overlay.DefaultWidth = overlay.getWidth();
			overlay.Number = s;

			link.addEvent("mousemove", Website.Products.Details.StarMove);
			link.addEvent("mouseout", Website.Products.Details.StarOut);
			link.addEvent("click", Website.Products.Details.StarClick);
		}
	}
}

Website.Products.Details.Star = null;

Website.Products.Details.StarMove = function(event) {
	Website.Products.Details.Star = (event.relatedTarget != null && event.relatedTarget != undefined) ? $(event.relatedTarget) : $(event.target);

	if (Website.Products.Details.Star) {
		var redStars = Website.Products.Details.Star.getParent(".starsOverlay");

		if (redStars) {
			var positionStars = redStars.getPosition();
			var xOffset = event.page.x - positionStars.x;

			var rating = Website.Products.Details.GetStarRating(xOffset);

			redStars.setStyle("width", rating.width + "px");
		}
	}
}

Website.Products.Details.StarOut = function(event) {
	if (Website.Products.Details.Star) {
		var redStars = Website.Products.Details.Star.getParent(".starsOverlay");

		if (redStars) {
			redStars.setStyle("width", redStars.DefaultWidth + "px");
		}
	}
}

Website.Products.Details.StarClick = function(event) {
	var link = (event.relatedTarget != null && event.relatedTarget != undefined) ? $(event.relatedTarget) : $(event.target);

	if (link) {
		var redStars = link.getParent(".starsOverlay");

		if (redStars) {
			redStars.DefaultWidth = redStars.getWidth();

			var rating = Website.Products.Details.GetStarRating(redStars.DefaultWidth);
			var id = null;

			if (redStars.Number == 0) {
				id = "ctl00_ctl00_cBodyContainer_cBodyContainer_ctl05_cProductTabReviews_cProductQuality";
			} else if (redStars.Number == 1) {
				id = "ctl00_ctl00_cBodyContainer_cBodyContainer_ctl05_cProductTabReviews_cProductValue";
			} else if (redStars.Number == 2) {
				id = "ctl00_ctl00_cBodyContainer_cBodyContainer_ctl05_cProductTabReviews_cProductFeatures";
			}

			if (id != null) {
				var hiddenField = $(id);

				if (hiddenField) {
					hiddenField.setProperty("value", rating.rating);
				}
			}
		}
	}
}

Website.Products.Details.GetStarRating = function(width) {
	var widthOneStar = 13;

	var remainder = (width % widthOneStar);
	var count = (width - remainder) / widthOneStar;

	count = count;
	width = (count + 1) * widthOneStar;

	if (count == 5) {
		width = width - 3;
	}

	var results = {
		rating: count,
		width: width
	};

	return results;
}

Website.Products.Details.ValidateReviewStars = function(src, args) {
	var quality = $(src.controltovalidate.replace("cTitle", "cProductQuality"));
	var value = $(src.controltovalidate.replace("cTitle", "cProductValue"));
	var features = $(src.controltovalidate.replace("cTitle", "cProductFeatures"));

	if (quality.value == '0' || value.value == '0' || features.value == '0') {
		args.IsValid = false;
	} else {
		args.IsValid = true;
	}
}

Website.Products.Details.ValidateReviewTitle = function(src, args) {
	var title = $(src.controltovalidate);
	var content = $(src.controltovalidate.replace("cTitle", "cReview"));

	if (content.value != '' && title.value == '') {
		args.IsValid = false;
	} else {
		args.IsValid = true;
	}
}

Website.Products.Details.ValidateReviewContent = function(src, args) {
	var content = $(src.controltovalidate);
	var title = $(src.controltovalidate.replace("cReview", "cTitle"));

	if (title.value != '' && content.value == '') {
		args.IsValid = false;
	} else {
		args.IsValid = true;
	}
}

Website.SecondaryMenu.RefineSearch.Init = function() {
	var containers = $$(".refineSearchContainer");

	for (var index = 0; index < containers.length; index++) {
		var panel = containers[index];
		var title = panel.getElement(".refineTitle");
		var id = "rPanel_" + index;
		
		if (title) {
			panel.setProperty("id", id);
			title.PanelID = id;

			title.addEvent("click", function() { Website.SecondaryMenu.RefineSearch.Click(this.PanelID); });

			// If the price range container needs to be active.
			if (panel.hasClass("priceRangeContainer")) {
				var inputs = Website.Base.GetInputs(panel.getElements("INPUT[type=text]"), "cPriceFilterFrom,cPriceFilterTo");
				var fromPrice = inputs["cPriceFilterFrom"];
				var toPrice = inputs["cPriceFilterTo"];

				if (fromPrice && toPrice && (fromPrice.value.length > 0 || toPrice.value.length > 0)) {
					Website.SecondaryMenu.RefineSearch.Click(title.PanelID);
				}

			} else {
				var checked = panel.getElements("INPUT[type=checkbox]");

				for (var c = 0; c < checked.length; c++) {
					if (checked[c].checked) {
						Website.SecondaryMenu.RefineSearch.Click(title.PanelID);
						break;
					}
				}
			}
		}
	}
}

Website.SecondaryMenu.RefineSearch.Click = function(id) {
	var panel = $(id);
	var panelContent = panel.getElement(".refineContent");
	var panelHeader = panel.getElement(".refineTitle");

	if (panelContent != null) {
		if (panelContent.getStyle("display") == "none") {
			panelContent.setStyle("display", "block");
			panelHeader.addClass("active");
		} else {
			panelContent.setStyle("display", "none");
			panelHeader.removeClass("active");
		}
	}
}

Website.ShoppingCart.WaitMessage = "Please wait, your shopping cart is being updated.";
Website.ShoppingCart.SuccessMessage = "Your shopping cart has been successfully updated.";
Website.ShoppingCart.ErrorMessage = "Sorry, but an error occured making the update. Please reload your page and try again.";

Website.ShoppingCart.Init = function() {
	if (window.Library != null && window.Library != undefined) {
		JSLibrary.ShoppingCart.UserFunction_GetOrderStart = function() { };
		JSLibrary.ShoppingCart.UserFunction_GetOrderComplete = function() { Website.ShoppingCart.SetComplete(Website.ShoppingCart.ErrorMessage, Website.ShoppingCart.SuccessMessage, arguments); };
		
		JSLibrary.ShoppingCart.UserFunction_AddItemStart = function() { Website.ShoppingCart.SetLoading(Website.ShoppingCart.WaitMessage); };
		JSLibrary.ShoppingCart.UserFunction_AddItemComplete = function() { Website.ShoppingCart.SetComplete(Website.ShoppingCart.ErrorMessage, Website.ShoppingCart.SuccessMessage, arguments); };
		JSLibrary.ShoppingCart.UserFunction_UpdateItemStart = function() { Website.ShoppingCart.SetLoading(Website.ShoppingCart.WaitMessage); };
		JSLibrary.ShoppingCart.UserFunction_UpdateItemComplete = function() { Website.ShoppingCart.SetComplete(Website.ShoppingCart.ErrorMessage, Website.ShoppingCart.SuccessMessage, arguments); };
		JSLibrary.ShoppingCart.UserFunction_IncrementItemStart = function() { Website.ShoppingCart.SetLoading(Website.ShoppingCart.WaitMessage); };
		JSLibrary.ShoppingCart.UserFunction_IncrementItemComplete = function() { Website.ShoppingCart.SetComplete(Website.ShoppingCart.ErrorMessage, Website.ShoppingCart.SuccessMessage, arguments); };
		JSLibrary.ShoppingCart.UserFunction_DecrementItemStart = function() { Website.ShoppingCart.SetLoading(Website.ShoppingCart.WaitMessage); };
		JSLibrary.ShoppingCart.UserFunction_DecrementItemComplete = function() { Website.ShoppingCart.SetComplete(Website.ShoppingCart.ErrorMessage, Website.ShoppingCart.SuccessMessage, arguments); };
		JSLibrary.ShoppingCart.UserFunction_RemoveItemStart = function() { Website.ShoppingCart.SetLoading(Website.ShoppingCart.WaitMessage); };
		JSLibrary.ShoppingCart.UserFunction_RemoveItemComplete = function() { Website.ShoppingCart.SetComplete(Website.ShoppingCart.ErrorMessage, Website.ShoppingCart.SuccessMessage, arguments); };
	}

	Website.ShoppingCart.GetOrder();
	Website.ShoppingCart.InitProductList();
}

Website.ShoppingCart.SetLoading = function(message) {
	Website.Tooltip.Show("shoppingCartTooltipLoading", message);
}

Website.ShoppingCart.SetComplete = function(error, message, args) {
	var element = args[0];
	var order = args[1];
	var plu = args[2];
	var quantity = args[3];

	if (order == null) {
		Website.Tooltip.Show("shoppingCartTooltipError", error);

	} else {
		try {
			var shoppingCartWidgetLoading = $("shoppingCartWidget_Loading");
			var shoppingCartWidgetContainer = $("shoppingCartWidget_Container");

			if (element && element.id.indexOf("cProductList") > -1) {
				if (order.Items == 0) {
					window.location = "/online-store/shopping-cart/checkout.aspx";
				}
			}

			Website.ShoppingCart.UpdateWidget(order);

			if (element) {
				Website.ShoppingCart.UpdateCart(plu, order);
			}

			if (shoppingCartWidgetLoading) { shoppingCartWidgetLoading.setStyle("display", "none"); }
			if (shoppingCartWidgetContainer) { shoppingCartWidgetContainer.setStyle("display", "block"); }

			if (order.Message != null) {
				Website.Tooltip.Show("shoppingCartTooltipWarning", order.Message);
			} else if (element) {
				Website.Tooltip.Show("shoppingCartTooltipSuccess", message);
			}

			Website.Tooltip.Hide();

		} catch (ex) {
			Website.Tooltip.Show("shoppingCartTooltipWarning", "Sorry, an error occured trying to update the page. Please refresh and try again.");
			JSLibrary.ShoppingCart.Log(ex);
		}
	}
}

Website.ShoppingCart.UpdateWidget = function(order) {
	Website.ShoppingCart.SetValue("shoppingCartWidget_ItemsInCart", order.Items);
	Website.ShoppingCart.SetValue("shoppingCartWidget_Subtotal", order.SubTotal);
	Website.ShoppingCart.SetValue("shoppingCartWidget_Freight", order.Freight);
	Website.ShoppingCart.SetValue("shoppingCartWidget_GST", order.GST);
	Website.ShoppingCart.SetValue("shoppingCartWidget_Total", order.Total);
}

Website.ShoppingCart.SetValue = function(id, val) {
	var element = $(id);

	if (!element) {
		try {
			element = window.parent.document.getElementById(id);
		} catch (e) { }
	}

	if (element) {
		$(element).setProperty("text", val);
	}
}

Website.ShoppingCart.CartRowID = "productRow-";
Website.ShoppingCart.CartPriceID = "productPrice-";
Website.ShoppingCart.CartQuantityID = "productQuantity-";
Website.ShoppingCart.CartCostID = "productCost-";
Website.ShoppingCart.CartDeleteID = "productDelete-";

Website.ShoppingCart.GetOrder = function() {
	var interval = null;

	function run() {
		if (window.JSLibrary != null) {
			clearInterval(interval);
			JSLibrary.ShoppingCart.GetOrder(null);
		}
	}

	interval = setInterval(run, 10);
}

Website.ShoppingCart.InitProductList = function(id) {
	var productList = $("onlineStoreShoppingCart");

	if (productList) {
		var quantityInputs = productList.getElements("INPUT.quantity");
		var deleteLinks = productList.getElements("A.delete");

		for (var i = 0; i < quantityInputs.length; i++) {
			var input = quantityInputs[i];

			if (input) {
				input.PLU = input.getProperty("id");

				var split = input.PLU.split(Website.ShoppingCart.CartQuantityID);
				input.PLU = split[1];

				input.addEvent("keyup", function(e) { Website.ShoppingCart.ItemQuantityUpdated(e, this); });
				input.addEvent("blur", function(e) { Website.ShoppingCart.UpdateItem(this); });
			}
		}

		for (var i = 0; i < deleteLinks.length; i++) {
			var button = deleteLinks[i];

			if (button) {
				button.PLU = button.getProperty("id");

				var split = button.PLU.split(Website.ShoppingCart.CartDeleteID);
				button.PLU = split[1];

				button.addEvent("click", function() { Website.ShoppingCart.RemoveItem(this); });
			}
		}
	}
}

Website.ShoppingCart.UpdateCart = function(plu, order) {
	var item = order.ItemReference[plu];

	Website.ShoppingCart.SetValue("shoppingCart_GST", order.GST);
	Website.ShoppingCart.SetValue("shoppingCart_Subtotal", order.SubTotal);
	Website.ShoppingCart.SetValue("shoppingCart_Freight", order.Freight);
	Website.ShoppingCart.SetValue("shoppingCart_Total", order.Total);

	if (item) {
		var row = $("productRow-" + plu);

		if (row) {
			var cartQuantity = row.getElement("INPUT");

			if (cartQuantity) { cartQuantity.value = item.Quantity; }

			Website.ShoppingCart.SetValue(Website.ShoppingCart.CartPriceID + plu, item.Cost);
			Website.ShoppingCart.SetValue(Website.ShoppingCart.CartCostID + plu, item.Total);
		}
	}

	if ($("onlineStoreShoppingCart") != null && order.Items == 0) {
		var noItems = $("ctl00_ctl00_cBodyContainer_cBodyContainer_ctl02_cProductList_cNoItems");

		try {
			noItems.setStyle("display", "table-row");
		} catch (ex) {
			noItems.setStyle("display", "block");
		}

		$("aspnetForm").setStyle("display", "none");
	}
}

Website.ShoppingCart.ItemQuantityUpdated = function(e, element) {
	var value = element.getProperty("value").replace(/[^0-9]/g, "");
	var update = function() { Website.ShoppingCart.UpdateItem(element); }

	element.setProperty("value", value);
	clearTimeout(element.TypeTimeout);

	if (value.length > 0) {
		element.TypeTimeout = setTimeout(update, 200);
	}

	if (e.code == 13) {
		//Website.ShoppingCart.UpdateItem(this);
		element.blur();
	}
}

Website.ShoppingCart.UpdateItem = function(element) {
	var value = parseInt(element.getProperty("value"));

	if (value < 1) {
		Website.ShoppingCart.RemoveItem(element);
	} else {
		JSLibrary.ShoppingCart.UpdateItem(element, element.PLU, value);
	}
}

Website.ShoppingCart.RemoveItem = function(element) {
	JSLibrary.ShoppingCart.RemoveItem(element, element.PLU);
	$(Website.ShoppingCart.CartRowID + element.PLU).dispose();
}

Website.ShoppingCart.SetAnchor = function(anchorName) {
	window.location = window.location.href += "#" + anchorName;
}

Website.WishList.WaitMessage = "Please wait, your wishlist is being updated.";
Website.WishList.SuccessMessage = "Your wishlist has been successfully updated.";
Website.WishList.ErrorMessage = "Sorry, but an error occured making the update. Please reload your page and try again.";


Website.WishList.Init = function() {
	if (window.Library != null && window.Library != undefined) {
		JSLibrary.WishList.UserFunction_AddToWishListStart = function() { Website.WishList.SetLoading(Website.WishList.WaitMessage); };
		JSLibrary.WishList.UserFunction_AddToWishListComplete = function() { Website.WishList.SetCompleteForAdd(Website.WishList.ErrorMessage, Website.WishList.SuccessMessage, arguments); };
		JSLibrary.WishList.UserFunction_UpdateItemStart = function() { Website.WishList.SetLoading(Website.WishList.WaitMessage); };
		JSLibrary.WishList.UserFunction_UpdateItemComplete = function() { Website.WishList.SetCompleteForUpdate(Website.WishList.ErrorMessage, Website.WishList.SuccessMessage, arguments); };
		JSLibrary.WishList.UserFunction_RemoveItemStart = function() { Website.WishList.SetLoading(Website.WishList.WaitMessage); };
		JSLibrary.WishList.UserFunction_RemoveItemComplete = function() { Website.WishList.SetCompleteForDelete(Website.WishList.ErrorMessage, Website.WishList.SuccessMessage, arguments); };
	}
	
	Website.WishList.InitItemList();
}


Website.WishList.InitItemList = function(id) {
	var wishList = $("wishListContainer");
	if (!wishList) return;

	var quantityInputs = wishList.getElements("INPUT.quantity");
	var deleteLinks = wishList.getElements("A.delete");

	for (var i = 0; i < quantityInputs.length; i++) {
		var input = quantityInputs[i];

		if (input) {
			var id = input.getProperty("id");

			var split = id.split("@@@");
			input.PLU = split[1];
			input.WISHLIST = split[2];

			input.addEvent("keyup", function(e) { Website.WishList.ItemQuantityUpdated(e, this); });
			input.addEvent("blur", function(e) { Website.WishList.UpdateItem(this); });
		}
	}

	for (var i = 0; i < deleteLinks.length; i++) {
		var button = deleteLinks[i];

		if (button) {
			var id = button.getProperty("id");
			var split = id.split("@@@");
			button.PLU = split[1];
			button.WISHLIST = split[2];
			button.addEvent("click", function() { Website.WishList.RemoveItem(this); });
		}
	}
}


Website.WishList.SetValue = function(id, val) {
	var element = $(id);

	if (element) {
		element.set("text", val);
	}
}


Website.WishList.ItemQuantityUpdated = function(e, element) {

	var value = element.getProperty("value").replace(/[^0-9]/g, "");
	var update = function() { Website.WishList.UpdateItem(element); }

	element.setProperty("value", value);
	clearTimeout(element.TypeTimeout);

	if (value.length > 0) {
		element.TypeTimeout = setTimeout(update, 200);
	}

	if (e.code == 13) {
		//Website.WishList.UpdateItem(this);
		element.blur();
	}
}

Website.WishList.UpdateItem = function(element) {
	var value = parseInt(element.getProperty("value"));

	if (value < 1) {
		Website.WishList.RemoveItem(element);
	}
	else {
		JSLibrary.WishList.UpdateItem(element, element.WISHLIST, element.PLU, value);
	}
}


Website.WishList.RemoveItem = function(element) {
	JSLibrary.WishList.RemoveItem(element, element.WISHLIST, element.PLU);
	//$("wishlist_row-" +element.PLU).dispose();//SHOULD THIS BE DONE AFTER CALLBACK?
}



Website.WishList.SetLoading = function(message) {
	Website.Tooltip.Show("shoppingCartTooltipLoading", message);
}

Website.WishList.SetCompleteForAdd = function(error, message, args) {
	if (args[0] == true) {
		Website.Tooltip.Show("shoppingCartTooltipSuccess", message);
	}
	else {
		Website.Tooltip.Show("shoppingCartTooltipError", error);
	}
	Website.Tooltip.Hide();
}

Website.WishList.SetCompleteForUpdate = function(error, message, args) {
	var webWishlist = args[0];
	var plu = args[1];

	if (webWishlist) {
		Website.WishList.SetValue("wishlist_Subtotal", webWishlist.SubTotal);
		Website.WishList.SetValue("wishlist_Freight", webWishlist.Freight);
		Website.WishList.SetValue("wishlist_Total", webWishlist.TotalIncGst);

		Website.WishList.UpdateRow(plu, webWishlist);

		Website.Tooltip.Show("shoppingCartTooltipSuccess", message);
	}
	else {
		Website.Tooltip.Show("shoppingCartTooltipError", error);
	}
	Website.Tooltip.Hide();
}

Website.WishList.SetCompleteForDelete = function(error, message, args) {
	var webWishlist = args[0];
	var plu = args[1];

	if (webWishlist) {
		Website.WishList.SetValue("wishlist_Subtotal", webWishlist.SubTotal);
		Website.WishList.SetValue("wishlist_Freight", webWishlist.Freight);
		Website.WishList.SetValue("wishlist_Total", webWishlist.TotalIncGst);

		$("wishlist_row-" + plu).dispose();

		Website.Tooltip.Show("shoppingCartTooltipSuccess", message);
	}
	else {
		Website.Tooltip.Show("shoppingCartTooltipError", error);
	}
	Website.Tooltip.Hide();
}

Website.WishList.UpdateRow = function(plu, webWishlist) {

	var item = webWishlist.ItemReference[plu];
	if (item) {
		var row = $("wishlist_row-" + plu);
		var quantity = row.getElement("INPUT");
		if (quantity) { quantity.value = item.Quantity; }

		Website.WishList.SetValue("wishlist_price-" + plu, item.Price);
		Website.WishList.SetValue("wishlist_subtotal-" + plu, item.Subtotal);
	}
}

window.addEvent("load", Website.Base.Init);
window.addEvent("load", Website.Tooltip.Init);
window.addEvent("load", Website.ShoppingCart.Init);
window.addEvent("load", Website.WishList.Init);

// Prevent webservice errors from showing up.
window.baseAlert = window.alert;

window.alert = function(obj) {
	var show = true;

	try {
		if (obj.indexOf("The server method") >= 0) { show = false; }
	} catch (e) { }

	if (show) {
		window.baseAlert(obj);
	}
}

// IE6 background image flicker fix.
try { document.execCommand("BackgroundImageCache", false, true); } catch (err) { }
