﻿
var Scan = {};
Scan.ApplicationRoot = "";

Scan.SetApplicationRoot = function (applicationRoot) {
    Scan.ApplicationRoot = applicationRoot;
}


/* Scan.Basket */
Scan.Basket = {};
Scan.Basket.BasketObject = null;
Scan.Basket.EnableLiveBasket = true;

//BasketType: 0=Standard 1=Categorised
Scan.Basket.GetBasketType = function () {
	return $.cookie("BasketType") != null ? $.cookie("BasketType") : 0;
}

Scan.Basket.SetBasketType = function (value) {
	$.cookie("BasketType", value, { expires: 7 });
}

Scan.Basket.AddProduct = function (WebProductId) {
	Scan.Basket.AddProductQty(WebProductId, 1);
}

Scan.Basket.AddProductQty = function (WebProductId, Qty) {
    $.ajax({ type: 'POST',
        url: Scan.ApplicationRoot + "Scan.asmx/Basket_AddProduct",
        data: "{\"WebProductId\":\"" + WebProductId + "\",\"Quantity\":\"" + parseInt(Qty) + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: Scan.Basket.Refresh,
        error: function (request, error) { }
    });
}

Scan.Basket.AddProductByLN = function (ln) {
    $.ajax({ type: "POST",
        url: Scan.ApplicationRoot + "Scan.asmx/Basket_AddProductByLN",
        data: "{\"LN\":\"" + ln + "\",\"Quantity\":\"1\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: Scan.Basket.Refresh,
        error: function (request, error) { }
    });
}

Scan.Basket.ChangeQty = function (wpid, qty) {
    $.ajax({ type: 'POST',
        url: Scan.ApplicationRoot + "Scan.asmx/Basket_ChangeProductQty",
        data: "{\"WebProductId\":\"" + wpid + "\",\"Quantity\":\"" + qty + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: Scan.Basket.Refresh,
        error: function (request, error) { }
    });
}

Scan.Basket.Refresh = function () {
	$.ajax({ type: 'POST',
		url: Scan.ApplicationRoot + 'Scan.asmx/' + (Scan.Basket.GetBasketType() == 0 ? 'Basket_GetCurrent' : 'Basket_GetCategorisedCurrent'),
		data: '{}',
		contentType: 'application/json; charset=utf-8',
		dataType: 'json',
		success: function (result) {
			Scan.Basket.BasketObject = (typeof result.d != undefined) ? result.d : result;
			Scan.Basket.UpdateLiveBasket();
			Scan.Basket.UpdateProductLists();
		}
	});
}

Scan.Basket.UpdateProductLists = function () {
	if (Scan.Basket.BasketObject) {
		$.each($(".basket-product"), function (index, element) {
			var imageName = $(element).hasClass("preorder") == "1" ? "buy-button-preorder" : "buy-button-add";
			$(".buy-button", element).html('<a href="javascript:" class="buy-button-add" title="Add this product to your basket"><img src="' + Scan.ApplicationRoot + 'images/' + imageName + '.png" width="90" height="35" alt="Buy" /></a>');
			$(".basket-text", element).text("");
		});

		$(".basket-product").removeClass("basket-product");

		$.each(Scan.Basket.BasketObject.Lines, function (index, basketLine) {
			$.each($(".wpid-" + basketLine.WebProductId), function () {
				var WebProduct = $(this);
				WebProduct.addClass("basket-product");

				var imageNameInc, imageNameDec, basketText;

				if (WebProduct.hasClass("preorder") == "1") {
					imageNameInc = "buy-button-preorder-inc";
					imageNameDec = "buy-button-preorder-dec";
					basketText = "You have " + basketLine.Quantity + " of these in your basket on pre-order";
				}
				else {
					imageNameInc = "buy-button-inc";
					imageNameDec = "buy-button-dec";
					basketText = "You have " + basketLine.Quantity + " of these in your basket";
				}

				$(".buy-button", WebProduct).html('<a href="javascript:" class="buy-button-dec"><img src="' + Scan.ApplicationRoot + 'images/' + imageNameDec + '.png" alt="Remove" width="32" height="35" /></a><p title="You have ' + basketLine.Quantity + ' of these in your basket">' + basketLine.Quantity + '</p><a href="javascript:" class="buy-button-inc"><img src="' + Scan.ApplicationRoot + 'images/' + imageNameInc + '.png" alt="Remove" width="33" height="35" /></a>');
				$(".basket-text", WebProduct).text(basketText);
			});
		});
	}
}

Scan.Basket.ShowLiveBasket = function () {
    $("#live-basket").show();
    $(".live-basket-switch").attr("src", Scan.ApplicationRoot + "images/btn_up.png");
}

Scan.Basket.HideLiveBasket = function () {
    $("#live-basket").hide();
    $(".live-basket-switch").attr("src", Scan.ApplicationRoot + "images/btn_down.png");
}

Scan.Basket.ToggleLiveBasket = function () {
    $("#live-basket").toggle();
    if ($("#live-basket").is(":visible")) {
        $(".live-basket-switch").attr("src", Scan.ApplicationRoot + "images/btn_up.png");
    }
    else {
        $(".live-basket-switch").attr("src", Scan.ApplicationRoot + "images/btn_down.png");
    }
}

Scan.Basket.UpdateLiveBasket = function () {
	var basketContainer = $(".basket-container");
	var categoryList = $(".basket-container ul.categories");
	var totalQty = 0;

	var handleBasketLine = function (basketLine, basketCategoryId) {
		var listClass = 'live-basket-products';
		var basketLineList = null;

		if (basketCategoryId < 0) {
			//Standard
			basketLineList = $('.' + listClass, basketContainer);
			if (basketLineList.length == 0) {
				basketLineList = $('<ul class="' + listClass + '"></ul>');
				basketContainer.append(basketLineList);
			}
		}
		else {
			//Categorised
			$.each($("li.live-basket-category", basketContainer), function (index, categoryListItem) {
				if ($.hasData(categoryListItem)) {
					if ($.data(categoryListItem, "BasketCategoryId") == basketCategoryId) {
						basketLineList = $("." + listClass, categoryListItem);
						if (basketLineList.length == 0) {
							basketLineList = $('<ul class="' + listClass + '"></ul>');
							$(categoryListItem).append(basketLineList);
						}
					}
				}
			});
		}

		var itemClass = 'live-basket-product';
		var listItems = $('.' + itemClass, basketLineList);
		var itemFound = false;

		totalQty += basketLine.Quantity;

		$.each(listItems, function (index, listItem) {
			if ($.hasData(listItem)) {
				if ($.data(listItem, "WebProductId") == basketLine.WebProductId) {
					$(".qty", listItem).removeClass("changed");
					$("input.qty", listItem).val(basketLine.Quantity);
					$("a.description", listItem).text(basketLine.WebDescription).attr("href", basketLine.ProductLink);
					$("span.price", listItem).text("£" + parseFloat(basketLine.Quantity * basketLine.PriceIncVat).toFixed(2));
					if (basketLine.LinkNumber > 0) $("span.link-number", listItem).text("LN" + basketLine.LinkNumber);
					itemFound = true;
				}
			}
		});

		if (!itemFound) {
			var listItem = $('<li class="' + itemClass + '"></li>');
			$(basketLineList).append(listItem);
			$.data(listItem[0], 'WebProductId', basketLine.WebProductId);

			var descriptionHtml = '<div class="product"><p>';
			if (basketLine.IsNew) descriptionHtml += '<span class="pListNew">NEW</span> ';
			if (basketLine.IsHot) descriptionHtml += '<span class="hotproduct">HOT SELLER</span> ';
			descriptionHtml = descriptionHtml + '<a class="description"></a></p></div>';

			listItem.append('<div class="image"><a href="#" class="drag-handle"><img src="' + basketLine.ImagePath + '" width="43" height="43" /><img class="dragme" width="43" height="43" src="' + Scan.ApplicationRoot + 'images/product-dragme-st.gif" /></a></div>');
			listItem.append('<div class="LN"><p><span class="link-number"></span></p></div>');
			listItem.append(descriptionHtml);
			listItem.append('<div class="price"><span class="price"></span> <span class="small">inc VAT</span></div>');
			listItem.append('<div class="web-product wpid-' + basketLine.WebProductId + '"><div class="buy-button"></div></div>');

			$("div.image a", listItem).attr('href', basketLine.ProductLink);
			$("a.description", listItem).text(basketLine.WebDescription).attr("href", basketLine.ProductLink);
			$("span.price", listItem).text("£" + parseFloat(basketLine.Quantity * basketLine.PriceIncVat).toFixed(2));
			if (basketLine.LinkNumber > 0) $("span.link-number", listItem).text("LN" + basketLine.LinkNumber);
		}
	}

	var handleBasketCategory = function (basketCategory) {
		var listClass = 'live-basket-categories';
		var categoryList = $('.' + listClass, basketContainer);

		if (categoryList.length == 0) {
			categoryList = $('<ul class="' + listClass + '"></ul>');
			basketContainer.append(categoryList);
		}

		var itemClass = 'live-basket-category';
		var listItems = $('.' + itemClass, categoryList);
		var itemFound = false;

		$.each(listItems, function (index, listItem) {
			if ($.hasData(listItem)) {
				if ($.data(listItem, 'BasketCategoryId') == basketCategory.BasketCategoryId) {
					itemFound = true;
					if (basketCategory.WebProductIds.length == 0) {
						$("p.no-basket-lines", listItem).show();
					}
					else {
						$("p.no-basket-lines", listItem).hide();
					}
				}
			}
		});

		if (!itemFound) {
			var listItem = $('<li class="' + itemClass + '"></li>');
			categoryList.append(listItem);
			$.data(listItem[0], 'BasketCategoryId', basketCategory.BasketCategoryId);

			listItem.append('<div><span class="title"></span><p class="no-basket-lines" style="display: none;">None in basket.</p></div>');
			$("span.title", listItem).text(basketCategory.Title);
			if (basketCategory.WebProductIds.length == 0) {
				$("p", listItem).show();
			}
			else {
				$("p", listItem).hide();
			}
		}
	}

	if (Scan.Basket.BasketObject) {
		var basket = Scan.Basket.BasketObject;
		var ReceivedBasketType = basket.Categories ? 1 : 0;

		//Clear table rows if BasketType has changed
		var clearContainer = true;
		if ($.hasData(basketContainer[0], "BasketType")) {
			if ($.data(basketContainer[0], "BasketType") == ReceivedBasketType) clearContainer = false;
		}
		if (clearContainer) $(basketContainer).children().remove();

		//Set BasketType
		$.data(basketContainer[0], "BasketType", ReceivedBasketType)

		//Set BasketOptions tab
		$(".basket-options div").removeClass("on")
		if (ReceivedBasketType == 0)
			$(".basket-options .basket-option-standard").addClass("on");
		else
			$(".basket-options .basket-option-categorised").addClass("on");


		if (basket.Categories == null) {
			//Standard
			$.each(basket.Lines, function (index, basketLine) {
				handleBasketLine(basketLine, -1);
			});
		}
		else {
			//Categorised
			$.each(basket.Categories, function (categoryIndex, basketCategory) {
				handleBasketCategory(basketCategory);
				$.each(basketCategory.WebProductIds, function (index, WebProductId) {
					$.each(basket.Lines, function (index, basketLine) {
						if (basketLine.WebProductId == WebProductId) {
							handleBasketLine(basketLine, basketCategory.BasketCategoryId);
						}
					});
				});
			});
		}

		//Remove html table rows for deleted products
		$.each($(".basket-container  li.live-basket-product"), function (index, listItem) {
			if ($.hasData(listItem)) {
				var WebProductId = parseInt($.data(listItem, "WebProductId"));
				if (WebProductId > 0) {
					var productFound = false;
					$.each(basket.Lines, function (index, basketLine) {
						if (WebProductId == basketLine.WebProductId) {
							productFound = true;
						}
					});
					if (!productFound) {
						$(listItem).remove();
					}
				}
			}
		});

		$(".live-basket-product-count").html(totalQty);
		$(".live-basket-products-gross").html(parseFloat(basket.ProductsGross).toFixed(2));
		$(".live-basket-carriage-gross").html(parseFloat(basket.CarriageGross).toFixed(2));
		$(".live-basket-total-gross").html(parseFloat(basket.TotalGross).toFixed(2));
	}
}

Scan.Basket.Setup = function () {
	if (Scan.Basket.EnableLiveBasket == true) {
		$(".web-product .drag-handle").liveDraggable({
			appendTo: "body",
			cursor: "move",
			helper: function () {
				var webproduct = $(this).parents(".web-product")
				var o = $('<div class="draggable-product"><span></span><p></p></div>');
				$('span', o).text($(".link-number", webproduct).text());
				$('p', o).text($(".description", webproduct).text());
				return o;
			},
			start: function () {
				$("#drop-basket").show().center();
			},
			stop: function () {
				$("#drop-basket").hide();
			}
		});

		$("#drop-basket-qty-1, #drop-basket-qty-2, #drop-basket-qty-3, #drop-basket-qty-4, #drop-basket-qty-5").droppable({
			activeClass: "drop-basket-active",
			hoverClass: "drop-basket-hover",
			accept: ".drag-handle",
			drop: function (event, ui) {
				var webproduct = ui.draggable.parents(".web-product");
				if (webproduct) {
					var reFindNumber = new RegExp("[0-9]{1,10}");
					var regexMatches = null;

					var wpid = 0;
					$.each(webproduct.attr("class").split(" "), function (index, className) {
						if (className.match(/^wpid-[0-9]{1,10}$/)) {
							regexMatches = reFindNumber.exec(className);
							if (regexMatches) {
								wpid = parseInt(regexMatches[0]);
							}
						}
					});

					var qty = 0;
					regexMatches = reFindNumber.exec($(this).attr("id"));
					if (regexMatches) {
						qty = parseInt(regexMatches[0]);
					}

					Scan.Basket.AddProductQty(wpid, qty);
				}
			}
		});

		$(".live-basket-product .drag-handle").liveDraggable({
			appendTo: "body",
			cursor: "move",
			helper: function () {
				var livebasketproduct = $(this).parents(".live-basket-product")
				var o = $('<div class="draggable-product"><span></span><p></p></div>');
				$('span', o).text($(".link-number", livebasketproduct).text());
				$('p', o).text($(".description", livebasketproduct).text());
				return o;
			},
			start: function () {
				$("#drop-bin").show().center();
			},
			stop: function () {
				$("#drop-bin").hide();
			}
		});

		$("#drop-bin-icon").droppable({
			activeClass: "drop-bin-active",
			hoverClass: "drop-bin-hover",
			accept: ".drag-handle",
			drop: function (event, ui) {
				var liveBasketProduct = ui.draggable.parents(".live-basket-product")[0];
				if ($.data(liveBasketProduct, "WebProductId")) {
					Scan.Basket.ChangeQty($.data(liveBasketProduct, "WebProductId"), 0);
				}
			}
		});

		$(".add-product").keypress(function (e) {
			if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
				$("#add-product-button", this).click();
				return false;
			}
		});

		$("#add-product-button").click(function () {
			var linkNumber = $("#add-product-ln").val().toLowerCase().replace("ln", "");
			if (linkNumber.match(/^[0-9]{1,10}$/)) {
				Scan.Basket.AddProductByLN(linkNumber);
			}
			else {
				alert("Invalid link number");
			}
		});

		$(".basket-options .basket-option-standard a").click(function () {
			Scan.Basket.SetBasketType(0);
			Scan.Basket.Refresh();
		});

		$(".basket-options .basket-option-categorised a").click(function () {
			Scan.Basket.SetBasketType(1);
			Scan.Basket.Refresh();
		});

		/* Live basket */
		$("#add-new-line").click(function () {
			var ln = $("#new-ln").val();
			Scan.Basket.AddProductByLN(ln);
		});

		$(".web-product .buy-button .buy-button-add").live("click", function () {
			var WebProductId = Scan.ProductList.GetWebProductIdFromWebProductContainer(this);
			if (WebProductId > 0) {
				Scan.Basket.AddProduct(WebProductId);
			}
			else {
				alert("Product could not be found.");
			}
		});

		$(".web-product .buy-button .buy-button-inc").live("click", function () {
			var WebProductId = Scan.ProductList.GetWebProductIdFromWebProductContainer(this);
			if (WebProductId > 0) {
				Scan.Basket.AddProduct(WebProductId);
			}
			else {
				alert("Product could not be found.");
			}
		});

		$(".web-product .buy-button .buy-button-dec").live("click", function () {
			var WebProductId = Scan.ProductList.GetWebProductIdFromWebProductContainer(this);
			var Quantity = 0;

			if (WebProductId > 0) {
				if (Scan.Basket.BasketObject) {
					$.each(Scan.Basket.BasketObject.Lines, function (index, basketLine) {
						if (basketLine.WebProductId == WebProductId) {
							Quantity = basketLine.Quantity - 1;
						}
					});
				}
				Scan.Basket.ChangeQty(WebProductId, Quantity);
			}
			else {
				alert("Product could not be found.");
			}
		});

		$(".web-product .buy-button p").live("click", function () {
			if ($("input", this).length == 0) {
				var currentQty = $(this).text();
				$(this).html('<input type="textbox" maxlength="3" value="' + currentQty + '" />');

				$("input", this).blur(function () {
					var qtyChanged = false;
					if ($(this).val().match(/^[0-9]{1,3}$/)) {
						var WebProductId = Scan.ProductList.GetWebProductIdFromWebProductContainer(this);
						if (WebProductId > 0) {
							var Qty = parseInt($(this).val());
							if (Qty != currentQty) {
								Scan.Basket.ChangeQty(WebProductId, Qty);
								qtyChanged = true;
							}
						}
					}
					if (!qtyChanged) $(this).parent().text(currentQty);
				}).keypress(function (e) {
					switch (e.keyCode) {
						case 13:
							$(this).blur();
							return false;
						case 27:
							$(this).val(currentQty).blur();
							return false;
					}
				}).focus().select();
			}
		});

		$(document).keypress(function (e) {
			if (e.keyCode == 27) { //esc
				Scan.Basket.HideLiveBasket();
			}
		});

		Scan.Basket.Refresh();
	}
	else {
		$(".BasketMenBlock").hide();
	}
}

/* Scan.ImagePreview */
Scan.ImagePreview = {};
Scan.ImagePreview.Visible = 0;

Scan.ImagePreview.Show = function (tb, imagepath) {
    if ($("#PopupImage").attr("src") == imagepath && Scan.ImagePreview.Visible == 1) {
        Scan.ImagePreview.Hide();
    }
    else {
        Scan.ImagePreview.Visible = 1;
        $("#PopupImage").attr("src", imagepath);

        $("#PopupImageHolder").show();
        $("#PopupImageHolder").css("top", $(tb).offset().top);
        $("#PopupImageHolder").css("left", $(tb).offset().left + 44);
    }
}

Scan.ImagePreview.HidePreviewImage = function () {
    Scan.ImagePreview.Visible = 0;
    $("#PopupImage").attr("src", "/images/blank.gif");
    $("#PopupImageHolder").hide();
}

/* Scan.ProductList */
Scan.ProductList = {};
//Scan.ProductList.EarliestDeliveryDate = null;
//Scan.ProductList.ProductFilterString = null;

Scan.ProductList.SetEarliestDeliveryDate = function (year, month, day) {
    Scan.ProductList.EarliestDeliveryDate = new Date(year, month - 1, day)
}

Scan.ProductList.SetProductFilter = function (EncStr) {
    Scan.ProductList.ProductFilterString = EncStr;
}

Scan.ProductList.GetWebProductIdFromWebProductContainer = function (WebProductContainerOrChild) {
	var WebProductId = 0;

	if (!$(WebProductContainerOrChild).hasClass("web-product")) {
		//find parent
		WebProductContainerOrChild = $(WebProductContainerOrChild).parents(".web-product").first();
	}

	if ($(WebProductContainerOrChild).length > 0) {
		var reFindNumber = new RegExp("[0-9]{1,10}");
		var regexMatches = null;

		$.each(WebProductContainerOrChild.attr("class").split(" "), function (index, className) {
			if (className.match(/^wpid-[0-9]{1,10}$/)) {
				regexMatches = reFindNumber.exec(className);
				if (regexMatches) {
					WebProductId = parseInt(regexMatches[0]);
				}
			}
		});	
	}

	return WebProductId;
}

Scan.ProductList.CompareProductList = function (Control, Url, LocationHash) {
    var Container = $(Control).parent();
    while (!$(Container).hasClass("CategoryContainer")) {
        Container = $(Container).parent();
    }

    if ($("input:checked[name='ProductId']", Container).length == 0) {
        alert("Select a product to compare");
    }
    else {
        var PID = "";

        $.each($("input:checked[name='ProductId']", Container), function (indexCategoryId, val) {
            if (indexCategoryId > 0) PID = PID + ",";
            PID = PID + $(val).val();
        });

        $.ajax({ type: 'POST',
            url: Url,
            data: { "PF": Scan.ProductList.ProductFilterString, "PID": PID },
            contentType: "application/x-www-form-urlencoded ; charset=utf-8",
            dataType: "html",
            success: function (data, textStatus) {
                $(Container).html(data);
                location.hash = LocationHash;
            },
            error: function (request, error) {
                alert("error: " + error);
            }
        });
    }
}

Scan.ProductList.RefreshProductList = function (Control, Url) {
    var Container = $(Control).parent();
    while (!$(Container).hasClass("CategoryContainer")) {
        Container = $(Container).parent();
    }

    $.ajax({ type: 'POST',
        url: Url,
        data: { PF: Scan.ProductList.ProductFilterString },
        contentType: "application/x-www-form-urlencoded ; charset=utf-8",
        dataType: "html",
        success: function (data, textStatus) {
            $(Container).html(data);
            Scan.Basket.UpdateProductLists();
        },
        error: function (request, error) {
            alert("error: " + error);
        }
    });
}

Scan.ProductList.GetEarliestDeliveryDateText = function () {
    if (Scan.ProductList.EarliestDeliveryDate) {
        var Days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
        var Months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
        var Sup = "";

        switch (Scan.ProductList.EarliestDeliveryDate) {
            case 1, 21, 31:
                Sup = "st";
                break;
            case 2, 22:
                Sup = "nd";
                break;
            case 3, 23:
                Sup = "rd";
                break;
            default:
                Sup = "th";
        }

        return Days[Scan.ProductList.EarliestDeliveryDate.getDay()] + " " + Scan.ProductList.EarliestDeliveryDate.getDate() + "<sup>" + Sup + "</sup> " + Months[Scan.ProductList.EarliestDeliveryDate.getMonth()] + " " + Scan.ProductList.EarliestDeliveryDate.getFullYear();
    }
}

Scan.ProductList.ShowStockMessage = function (inStock, StockMessage, img) {
    if (inStock) {
        var EarliestDeliveryDateText = Scan.ProductList.GetEarliestDeliveryDateText();
        var Message;
        Message = "This item is in stock and ready for shipping. ";
        if (EarliestDeliveryDateText) Message += "This product can be delivered to you on <b>" + EarliestDeliveryDateText + "</b>.";
        Message += "<br /><br />Feel free to place your order and if there are any stock issues we will contact you immediately. ";
        Scan.ProductList.ShowMessageBox(Message, img);
    }
    else {
        if ((StockMessage == "") || (StockMessage == null)) {
            Scan.ProductList.ShowMessageBox('Item is currently out of stock.<br /><br />The item is on order. An ETA will be provided as soon as the manufacturer has confirmed a delivery date.<br /><br />Any orders placed will be on back order and we will ship on a first come first served</b> basis. We will contact you should there be further delays.', img);
        }
        else {
            Scan.ProductList.ShowMessageBox('Item is currently out of stock.<br /><br />' + StockMessage + '<br /><br />Any orders placed will be on back order and we will ship on a <b>first come first served</b> basis. We will contact you should there be further delays.', img);
        }
    }
}

Scan.ProductList.ShowMessageBox = function (html, img) {
    $("#StockMessage").html(html);
    $("#StockMessage").css({ "left": $(img).position().left + "px", "top": ($(img).position().top + 15) + "px" });
    $("#StockMessage").show();
    //MoveStockMessage()
}

Scan.ProductList.MoveStockMessage = function () {
    if (document.getElementById("StockMessage").style.visibility == "visible") {
        var msg = document.getElementById("StockMessage")
        msg.style.left = xMousePos;
        msg.style.top = yMousePos + 15;

        while ((parseInt(msg.style.left.replace("px", "")) + parseInt(msg.offsetWidth)) > xMousePosMax) {
            msg.style.left = parseInt(msg.style.left) - 1;
        }
        while ((parseInt(msg.style.top.replace("px", "")) + parseInt(msg.offsetHeight)) > yMousePosMax) {
            msg.style.top = parseInt(msg.style.top) - 1;
        }

        window.setTimeout('Scan.ProductList.MoveStockMessage()', 10);
    }
}

Scan.ProductList.HideStockMessage = function () {
    $("#StockMessage").hide();
}

Scan.ProductList.ToggleCollapsibleArea = function (a) {
    if ($(a).hasClass("show")) {
        $(a).removeClass("show").addClass("hide").text("Hide").parents("div.collapsible-area").first().children(".body").show();
    }
    else {
    	$(a).removeClass("hide").addClass("show").text("Show").parents("div.collapsible-area").first().children(".body").hide();
    }
}

Scan.ProductList.ToggleCompare = function (a, id) {
	//var Checkbox = $("input:checkbox[name=\"ProductId\"][value=\"" + id + "\"]");
	var Checkbox = $(".compare-" + id);
	$(Checkbox).prop('checked', !$(Checkbox).is(':checked'));
	Scan.ProductList.UpdateCompareContainer(Checkbox);
}

Scan.ProductList.UpdateCompareContainer = function (checkbox) {
    if ($(checkbox).is(":checked")) {
        $(checkbox).parents(".web-product").first().addClass("compare-selected");
    }
    else {
        $(checkbox).parents(".web-product").first().removeClass("compare-selected");
    }
}

/* Scan.Mouse */
Scan.Mouse = {};

Scan.Mouse.GetAbsoluteLeft = function (o) {
    oLeft = o.offsetLeft
    while (o.offsetParent != null) {
        oParent = o.offsetParent
        oLeft += oParent.offsetLeft
        o = oParent
    }
    return oLeft
}

Scan.Mouse.GetAbsoluteTop = function (o) {
    oTop = o.offsetTop
    while (o.offsetParent != null) {
        oParent = o.offsetParent
        oTop += oParent.offsetTop
        o = oParent
    }
    return oTop
}


/* Scan.Layout */
Scan.Layout = {};
Scan.Layout.Tabs = {};
Scan.Layout.Tabs.TabDefinitions = new Array();

Scan.Layout.Tabs.RegisterTab = function (TabGroup, TabId, SelectorId, SelectorOff, SelectorOn) {
    var Index;
    Index = Scan.Layout.Tabs.TabDefinitions.length;
    Scan.Layout.Tabs.TabDefinitions[Index] = new Array(4);
    Scan.Layout.Tabs.TabDefinitions[Index][0] = TabGroup;
    Scan.Layout.Tabs.TabDefinitions[Index][1] = TabId;
    Scan.Layout.Tabs.TabDefinitions[Index][2] = SelectorId;
    Scan.Layout.Tabs.TabDefinitions[Index][3] = SelectorOff;
    Scan.Layout.Tabs.TabDefinitions[Index][4] = SelectorOn;
}

Scan.Layout.Tabs.SelectTab = function (TabId) {
    var TabGroup;

    //Find TabGroup related to TabId
    for (i = 0; i < Scan.Layout.Tabs.TabDefinitions.length; i++) {
        if (Scan.Layout.Tabs.TabDefinitions[i][1] == TabId) {
            TabGroup = Scan.Layout.Tabs.TabDefinitions[i][0];
            break;
        }
    }

    //Iterate through TabDefnitions ignoring any tabs not belonging to the current TabGroup
    for (i = 0; i < Scan.Layout.Tabs.TabDefinitions.length; i++) {
        if (Scan.Layout.Tabs.TabDefinitions[i][0] == TabGroup) {
            if (Scan.Layout.Tabs.TabDefinitions[i][1] == TabId) {
                $("#" + Scan.Layout.Tabs.TabDefinitions[i][1]).show();
                document.getElementById(Scan.Layout.Tabs.TabDefinitions[i][2]).className = Scan.Layout.Tabs.TabDefinitions[i][4];
            }
            else {
                $("#" + Scan.Layout.Tabs.TabDefinitions[i][1]).hide();
                document.getElementById(Scan.Layout.Tabs.TabDefinitions[i][2]).className = Scan.Layout.Tabs.TabDefinitions[i][3];
            }
        }
    }
}

/* Live Search */
Scan.Search = {};

Scan.Search.AddLink = function (WebProductId, LinkType) {
    var params = { "WebProductId": WebProductId, "LinkType": LinkType };

    $.ajax({ type: "POST",
        url: Scan.ApplicationRoot + "Scan.asmx/AddSearchLink",
        data: JSON.stringify(params),
        dataType: "json",
        contentType: "application/json; charset=utf-8"
    });
}


/* Site Navigation */
Scan.Navigation = {};
Scan.Navigation.MainMenu = {};
Scan.Navigation.MainMenu.MenuStructure = null;

var SCA = new Array();

Scan.Navigation.MainMenu.PopulateFromWebService = function (MsaId, SaId) {
    $.ajax({ type: "POST",
        url: Scan.ApplicationRoot + "SiteNavigationWebService.asmx/GetMenuStructure",
        data: "{\"MsaId\":\"" + MsaId + "\",\"SaId\":\"" + SaId + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            Scan.Navigation.MainMenu.SetMenuStructure(result);
        }
    });
}

Scan.Navigation.MainMenu.SetMenuStructure = function (o) {
    Scan.Navigation.MainMenu.MenuStructure = eval(o);
}

Scan.Navigation.MainMenu.RefreshLinksFromMenuStructure = function () {
    if (Scan.Navigation.MainMenu.MenuStructure) {
        $.each(Scan.Navigation.MainMenu.MenuStructure, function (index, MSA) {
            $.each(MSA.c, function (index, SA) {
                $.each(SA.c, function (index, MC) {
                    $("a.mc" + MC.id).attr("href", "javascript:ClickStaticMC(" + MSA.id + "," + SA.id + "," + MC.id + ",\"" + MC.t + "\",\"" + MSA.ut + "/" + SA.ut + "/" + MC.ut + "/all\");");

                    $.each(MC.c, function (index, CG) {
                        $.each(CG.c, function (index, C) {
                            SCA[SCA.length] = new Array(MSA.id, SA.id, MC.id, C.id, C.t, MSA.ut + "/" + SA.ut + "/" + MC.ut + "/" + C.ut);
                        });
                    });

                });
            });
        });
    }
    else {
        alert("Menu object has not been loaded");
    }
}

Scan.Navigation.MainMenu.SetMenuButtons = function () {
    Scan.Navigation.MainMenu.SetViewSelection();
    Scan.Navigation.MainMenu.SetCheckAll();
}

Scan.Navigation.MainMenu.SetViewSelection = function () {
    if ($("#divCategoryListing input:[type=checkbox][checked=true]").length > 0) {
        $("#ViewSelectedCategories").not(".on").addClass("on");
    }
    else {
        $("#ViewSelectedCategories.on").removeClass("on");
    }
}

Scan.Navigation.MainMenu.SetCheckAll = function () {
    if ($("#divCategoryListing input:checkbox").length == $("#divCategoryListing input:[type=checkbox][checked=true]").length) {
        $("#MenuCheckAll").not(".on").addClass("on");
    }
    else {
        $("#MenuCheckAll.on").removeClass("on");
    }
}

Scan.Navigation.MainMenu.ToggleCheck = function () {
    if ($("#divCategoryListing input:[type=checkbox][checked=true]").length != $("#divCategoryListing input:[type=checkbox]").length) {
        $("#divCategoryListing input:[type=checkbox]").prop("checked", true);
    }
    else {
        $("#divCategoryListing input:[type=checkbox]").prop("checked", false);
    }
    Scan.Navigation.MainMenu.SetMenuButtons();
    UpdateViewSelectedCategoriesLink();
 }

 Scan.Video = {
   	Width: 320,
   	Height: 240,
   	Show: function (el, flvPath, mp4Path, webmPath, poster) {
   		if (Modernizr.video.mp4 && mp4Path) {
   			Scan.Video.ShowMP4(el, mp4Path);
   		}
   		else if (Modernizr.video.webm && webmPath) {
   			Scan.Video.ShowWebM(el, webmPath);
   		}
   		else if (flvPath) {
   			Scan.Video.ShowFlash(el, flvPath);
   		}
   		else {
   			Scan.Video.ShowNoVideo(el);
   		}
   	},
   	ShowFlash: function (el, flvPath) {
   		el.empty().append(Scan.Video.ToFlash(flvPath));
   	},
   	ShowMP4: function (el, mp4Path, poster) {
   		el.empty().append(Scan.Video.ToHTML5(mp4Path, poster, ''));
   	},
   	ShowWebM: function (el, webmPath, poster) {
   		el.empty().append(Scan.Video.ToHTML5(webmPath, poster, 'video/webm; codecs="vp8, vorbis"'));
   	},
   	ShowNoVideo: function (el, poster) {
   		el.empty().append("<div>Cannot show video</div>");
   	},
	ToHTML5: function (src, poster, codec) {
   		return "<video src='" + src + "' width='" + this.Width + "' height='" + this.Height + "' + '" + +"' type='" + codec + "' poster='" + poster + "' preload controls='true'></video>";
   	},
   	ToFlash: function (src) {
   		return "<div>Flash is currently not support: cannot play '" + src + "'</div>"
   	}
};




var TimeoutInterval = 5000;
var CurrentMasterSpecialistApplicationId = 0;
var CurrentSpecialistApplicationId = 0;
var CurrentMasterCategoryId = 0;
var CurrentMasterSpecialistApplicationTitle;
var CurrentSpecialistApplicationTitle;
var CurrentMasterCategoryTitle;
var CurrentMasterCategorySponsorImage;

var ApplicationUrl;
var BaseUrl;
var UpperMenuId;
var LowerMenuId;
var EmptySpecialistApplicationsDivId;
var MasterCategoryTitleId;

var indexMasterSpecialistApplicationId = 0, indexSpecialistApplicationId = 1, indexMasterCategoryId = 2, indexCategoryId = 3, indexCategoryTitle = 4, indexCategoryUrlText = 5;

function InitialiseMenu(applicationUrl, baseUrl, upperMenuId, lowerMenuId, emptySpecialistApplicationsDivId, masterCategoryTitleId) {
    if (!applicationUrl.match("/$")) applicationUrl += "/";
    ApplicationUrl = applicationUrl;
    BaseUrl = baseUrl;
    UpperMenuId = upperMenuId;
    LowerMenuId = lowerMenuId;
    EmptySpecialistApplicationsDivId = emptySpecialistApplicationsDivId;
    MasterCategoryTitleId = masterCategoryTitleId;
    //SiteNavigationWebService.set_timeout(TimeoutInterval);
}

function InitialiseMenuLocation(currentMasterSpecialistApplicationId, currentSpecialistApplicationId, currentMasterCategoryId, currentMasterSpecialistApplicationTitle, currentSpecialistApplicationTitle, currentMasterCategoryTitle) {
    CurrentMasterSpecialistApplicationId = currentMasterSpecialistApplicationId;
    CurrentSpecialistApplicationId = currentSpecialistApplicationId;
    CurrentMasterCategoryId = currentMasterCategoryId;
    CurrentMasterSpecialistApplicationTitle = currentMasterSpecialistApplicationTitle;
    CurrentSpecialistApplicationTitle = currentSpecialistApplicationTitle;
    CurrentMasterCategoryTitle = currentMasterCategoryTitle;
}

function ClickStaticMC(MasterSpecialistApplicationId, SpecialistApplicationId, MasterCategoryId, MasterCategoryTitle, MasterCategoryUrl, MasterCategorySponsorImage) {
    CurrentMasterCategoryTitle = MasterCategoryTitle;
    CurrentMasterCategorySponsorImage = MasterCategorySponsorImage;

    HideCategoryList();
    ShowCategoryHolder();

    var html = "";
    var ViewAllUrl = ApplicationUrl + "tirupati/" + MasterCategoryUrl;

    $("#" + MasterCategoryTitleId).html("<a href=\"" + ViewAllUrl + "\">" + CurrentMasterCategoryTitle + "</a>");
    $("#ViewAllCategories").attr("href", ViewAllUrl);

    $("#menu-new").attr("href", ViewAllUrl + "/new-arrivals")
    $("#menu-hotseller").attr("href", ViewAllUrl + "/hot-sellers")
    $("#menu-clearance").attr("href", ViewAllUrl + "/clearance")

    var columnCount = 3;
    var columnArray = [columnCount - 1];
    for (columnIndex = 0; columnIndex < columnCount; columnIndex++) {
        columnArray[columnIndex] = $("#divCategoryListing > .column" + (columnIndex + 1));
        $(columnArray[columnIndex]).empty();
    }

    if (Scan.Navigation.MainMenu.MenuStructure) {
        //Get total items (groups and categories)
        var totalItems = 0;
        var showGroups = true;

        $.each(Scan.Navigation.MainMenu.MenuStructure, function (index, MSA) {
            $.each(MSA.c, function (index, SA) {
                $.each(SA.c, function (index, MC) {
                    if (MSA.id == MasterSpecialistApplicationId && SA.id == SpecialistApplicationId && MC.id == MasterCategoryId) {
                        if (MC.c.length == 1 && MC.c[0].id == 0) {
                            totalItems = MC.c[0].c.length;
                            showGroups = false;
                        }
                        else {
                            $.each(MC.c, function (index, CG) {
                                totalItems += 1;
                                $.each(CG.c, function (index, C) {
                                    totalItems += 1;
                                });
                            });
                        }
                    }
                });
            });
        });

        var itemsPerColumn = Math.ceil(totalItems / columnCount);

        $.each(Scan.Navigation.MainMenu.MenuStructure, function (index, MSA) {
            $.each(MSA.c, function (index, SA) {
                $.each(SA.c, function (index, MC) {
                    if (MSA.id == MasterSpecialistApplicationId && SA.id == SpecialistApplicationId && MC.id == MasterCategoryId) {
                        var columnIndex = 0;
                        var itemIndex = 0;

                        $.each(MC.c, function (groupIndex, CG) {
                            var Url = ApplicationUrl;
                            if (!Url.match("/$")) Url += "/";
                            Url += "shop/";

                            var CategoryGroupUrl = Url + MSA.ut + "/" + SA.ut + "/" + MC.ut;

                            $.each(CG.c, function (categoryIndex, C) {
                                CategoryGroupUrl += "/" + C.id;
                            });

                            if (showGroups) {
                                columnIndex = Math.floor(itemIndex / itemsPerColumn);
                                if (CG.t == "") {
                                    $(columnArray[columnIndex]).append("<li class=\"group\"><h2><a href=\"" + CategoryGroupUrl + "\">Other</a></h2></li>");
                                }
                                else {
                                    $(columnArray[columnIndex]).append("<li class=\"group\"><h2><a href=\"" + CategoryGroupUrl + "\">" + CG.t + "</a></h2></li>");
                                }
                                itemIndex += 1;
                            }

                            $.each(CG.c, function (categoryIndex, C) {
                                columnIndex = Math.floor(itemIndex / itemsPerColumn);
                                $(columnArray[columnIndex]).append("<li id=\"menu-cat-" + C.id + "\"><input type=\"checkbox\" name=\"checkboxCategoryId\" value=\"" + MSA.ut + "/" + SA.ut + "/" + MC.ut + "/" + C.ut + "\" onclick=\"if(this.checked == true){ $('#menu-cat-" + C.id + "').addClass('MenuSelected') } else { $('#menu-cat-" + C.id + "').removeClass('MenuSelected') }; UpdateViewSelectedCategoriesLink();\" /><p><a href=\"" + Url + MSA.ut + "/" + SA.ut + "/" + MC.ut + "/" + C.ut + "\">" + C.t + "</a></p></li>");
                                itemIndex += 1;
                            });
                        });
                    }
                });
            });
        });
    }

    ShowCategoryList();
    UpdateViewSelectedCategoriesLink();
}

function NavigateToAllCategories() {
    var NavigationToken
    NavigationToken = CurrentMasterSpecialistApplicationId + "-" + CurrentSpecialistApplicationId + "-" + CurrentMasterCategoryId + "-"

    var CheckboxArray = document.getElementsByName("checkboxCategoryId");
    var FirstItem = true;
    for (var index = 0; index < CheckboxArray.length; index++) {
        if (!FirstItem)
            NavigationToken += ".";
        else
            FirstItem = false;
        NavigationToken += CheckboxArray[index].value;
    }
    NavigationToken += "-0";
    window.location = BaseUrl + "?NT=" + NavigationToken;
}

function UpdateViewSelectedCategoriesLink() {
    var Url = ApplicationUrl + "shop/";

    var CheckboxArray = document.getElementsByName("checkboxCategoryId");
    var NumberOfCheckedItems = 0;
    var FirstCheckedItem = true;

    for (var index = 0; index < CheckboxArray.length; index++) {
        if (CheckboxArray[index].checked == true) NumberOfCheckedItems++;
    }

    for (var index = 0; index < CheckboxArray.length; index++) {
        if (NumberOfCheckedItems > 2) {
            if (CheckboxArray[index].checked == true) {
                var CategoryUrlText = CheckboxArray[index].value;
                var CategoryId = 0;

                if (FirstCheckedItem) Url += CategoryUrlText.substring(0, CategoryUrlText.lastIndexOf("/") + 1);
                for (var SCAIndex = 0; SCAIndex < SCA.length; SCAIndex++) {
                    if (SCA[SCAIndex][indexCategoryUrlText] == CategoryUrlText) {
                        CategoryId = SCA[SCAIndex][indexCategoryId];
                        break;
                    }
                }

                if (!FirstCheckedItem)
                    Url += "/";
                else
                    FirstCheckedItem = false;

                Url += CategoryId;
            }
        }
        else {
            if (CheckboxArray[index].checked == true) {
                var CategoryUrlText = CheckboxArray[index].value;

                if (!FirstCheckedItem) {
                    CategoryUrlText = CategoryUrlText.substring(CategoryUrlText.lastIndexOf("/") + 1)
                    Url += "/";
                }
                else {
                    FirstCheckedItem = false;
                }
                Url += CategoryUrlText;
            }
        }
    }
    if (!FirstCheckedItem) {
        $("#ViewSelectedCategories").attr("href", Url);
    }
    else {
        $("#ViewSelectedCategories").attr("href", "#");
    }

    $("#divCategoryListing input:[type=checkbox][checked=true]").each(function (index, checkbox) {
        $(checkbox).parent().addClass("MenuSelected");
    });

    $("#divCategoryListing input:[type=checkbox][checked=false]").each(function (index, checkbox) {
        $(checkbox).parent().removeClass("MenuSelected");
    });
}

function NavigateToSelectedCategories() {
    var UrlDescription = "";

    var CheckboxArray = document.getElementsByName("checkboxCategoryId");
    var FirstCheckedItem = true;
    for (var index = 0; index < CheckboxArray.length; index++) {
        if (CheckboxArray[index].checked == true) {
            var CategoryUrlText = CheckboxArray[index].value;

            if (!FirstCheckedItem) {
                CategoryUrlText = CategoryUrlText.substring(CategoryUrlText.lastIndexOf("/") + 1)
                UrlDescription += "/";
            }
            else {
                FirstCheckedItem = false;
            }
            UrlDescription += CategoryUrlText;
        }
    }
    if (!FirstCheckedItem) {
        window.location = ApplicationUrl + "shop/" + UrlDescription;
    }
    else {
        var div = $get("divCategoryErrorMessage");
        div.innerHTML = "Please tick the boxes to select the categories you want to display.  To display all categories click View All.";
        $("#divCategoryErrorMessage").show("slow");
    }
}

function FailedCallBack(error, userContext, methodName) {
    if (error !== null)
        alert("Error: " + error.get_message() + "\rMethod: " + methodName + "\rStatus Code: " + error.get_statusCode() + "\rExecution Type: " + error.get_exceptionType() + "\rStack trace: " + error.get_stackTrace());
    alert(SiteNavigationWebService);
}

function ShowCategoryHolder() {
    $("#divCategoryHolder").show();
}

function HideCategoryHolder() {
    $("#divCategoryHolder").hide();
}

function ShowCategoryList() {
    $("#divCategoryErrorMessage").hide();
    $("#divCategoryListing").show();
}

function HideCategoryList() {
    $("#divCategoryListing").hide();
}


function SortMenu() {
    var ListItemHeight = 19;
    var ListItemWidth = 145;
    var ListItemHorizontalMargin = 1;

    var Menu = document.getElementById("SiteNavigation").getElementsByTagName("ul")[0];
    var ListItems = Menu.getElementsByTagName("li");

    var MenuContainer = document.getElementById("divSiteNavigationMeasurement");
    var ContainerWidth = parseInt(MenuContainer.offsetWidth);

    if (ContainerWidth > 0) {
    	var NumberOfColumns = (ContainerWidth / (ListItemWidth + ListItemHorizontalMargin))
    	NumberOfColumns = Math.floor(NumberOfColumns);

    	//var ItemsPerColumn;
    	var ListItemsPerColumn = Math.ceil(ListItems.length / NumberOfColumns)

    	Menu.style.height = (ListItemsPerColumn * ListItemHeight) + "px";

    	var ColumnIndex = 1;
    	var RowIndex = 1;

    	for (var ListIndex = 0; ListIndex < ListItems.length; ListIndex++) {
    		var ListItem = ListItems[ListIndex];

    		ListItem.style.marginLeft = ((ColumnIndex - 1) * ListItemWidth) + "px";

    		if ((RowIndex == 1) && (ColumnIndex > 1))
    			ListItem.style.marginTop = (0 - (ListItemsPerColumn * ListItemHeight)) + "px";
    		else
    			ListItem.style.marginTop = "0px";

    		RowIndex++;
    		if (RowIndex > ListItemsPerColumn) {
    			ColumnIndex++;
    			RowIndex = 1;
    		}
    	}	
	}
}

function SetNT(MasterSpecialistApplicationId, SpecialistApplicationId, MasterCategoryId) {
    var Value = MasterSpecialistApplicationId + '-' + SpecialistApplicationId + '-' + MasterCategoryId;
    document.cookie = "NT=" + Value + "; path=/";
}

window.onresize = SortMenu;

/* Client Validation */
function RegexValidate(Control) {
    if (Control.value.length > 0) {
        var RegexPattern = "^[A-z0-9_\\-\\?'!#\"£\\$%&\\*\\+/=\\?\\^`\\{\\}\\|]*$"
        var Matched = Control.value.match(RegexPattern)

        if (!Matched) {
            alert("The value entered is invalid.");
            var ControlId = Control.id;
            setTimeout("document.getElementById('" + ControlId + "').focus();", 0)
            setTimeout("document.getElementById('" + ControlId + "').select();", 0)
        }
    }
}

function RegexValidateEmail(Control) {
    if (Control.value.length > 0) {
        var RegexPattern = "^[A-z0-9_\\-\\?'!#\\$%&\\*\\+/=\\?\\^`\\{\\}\\|~]{1}[A-z0-9_\\-\\.\\?'!#\\$%&\\*\\+/=\\?\\^`\\{\\}\\|~]*@([A-z0-9_\\-\\.]+)(\\.[A-z]{2,10})+$"
        var Matched = Control.value.match(RegexPattern)

        if (!Matched) {
            alert("Please enter a valid email address.");
            var ControlId = Control.id;
            setTimeout("document.getElementById('" + ControlId + "').focus();", 1)
            setTimeout("document.getElementById('" + ControlId + "').select();", 1)
        }
    }
}

/* Google Tracking */
Scan.GoogleTracking = {};

Scan.GoogleTracking.Setup = function () {
    //Tracking events
    $(".ga-gallery-view").live("click", function () {
        _gaq.push(["_trackEvent", "Product view change", "Gallery"]);
    });

    $(".ga-list-view").live("click", function () {
        _gaq.push(["_trackEvent", "Product view change", "List"]);
    });

    $(".ga-compare-view").live("click", function () {
        var checkedProductCount = $(this).parents(".product-container").find("input:[type=checkbox][checked=true]").length;
        var categoryTitle = $(this).parents(".CategoryContainer").find("h2").text();
        _gaq.push(["_trackEvent", "Product view change", "Compare", categoryTitle, checkedProductCount]);
    });

    //Campaign Tracking
}


/* General */
$(document).ready(function () {
	SortMenu();
	Scan.Basket.Setup();
	Scan.GoogleTracking.Setup();

	$("#divCategoryListing").live("click", function () {
		Scan.Navigation.MainMenu.SetMenuButtons();
	});

	//default buttons
	$(".default-button-container").keypress(function (e) {
		if (e.keyCode == "13") {
			$(this).find("default-button").click();
		}
	});
});


$.extend({ UrlEncode: function (c) {
    var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length) {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != '') {
            o += m[1]; x += m[1].length;
        } else {
            if (c[x] == ' ') o += '+'; else {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
            } x++;
        }
    } return o;
},
    UrlDecode: function (s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});

function getQueryStringParam(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

// Live Search - Start
(function ($) {
    $.fn.ScanLiveSearch = function (searchResultsHolder, ApplicationRoot) {
        return this.each(function () {
            var searchInput = $(this);
			
            var xhr = null;
            var TimeoutId = null;
            var SearchDelay = 250;

            var ResultHeader = $("<div class=\"ResultHeader\"></div>");
            var ResultPages = $("<div class=\"ResultPages\"></div>");
            var LastSearchValue = null;

            $(searchResultsHolder).children().remove();
            $(searchResultsHolder).append("<div class=\"LiveS\"><div class=\"ResultContainer\"><div class=\"Ls-Contain\"></div></div></div>");
            $(".Ls-Contain", searchResultsHolder).append(ResultHeader);
            $(".Ls-Contain", searchResultsHolder).append(ResultPages);

            $(searchInput).keypress(function (event) {
                if (event.keyCode == 13) {
                    var SelectedItem = $("div.ResultPage:visible li.selected:eq(0) a").attr("href");
                    if (SelectedItem != undefined) {
                        window.location.href = SelectedItem;
                    }
                    else {
                        window.location.href = "http://www.scan.co.uk/search.aspx?q=" + $.UrlEncode(searchInput.val());
                    }
                    return false;
                }
            });

            $(searchInput).keydown(function (event) {
                switch (event.keyCode) {
                    case 38: //Up
                        PreviousResult($("div.ResultPage:visible"));
                        break;
                    case 40: //Down
                        NextResult($("div.ResultPage:visible"));
                        break;
                    case 33: //Page Up
                        PreviousPage($("div.ResultPage:visible"), false);
                        break;
                    case 34: //Page Down
                        NextPage($("div.ResultPage:visible"), false);
                        break;
                    case 27: //Esc 
                        Hide();
                        break;
                }
            });

            $(searchInput).keyup(function (event) {
                var Input = $(searchInput).val();
                if (Input == '') {
                    Hide();
                    return;
                }

                if (LastSearchValue != Input) {
                    LastSearchValue = Input;

                    clearTimeout(TimeoutId);

                    if (xhr) {
                        xhr.abort();
                    }

                    TimeoutId = setTimeout(function () {
                        var PostData = { "Query": $(searchInput).val(), "PageSize": 5 };
                        xhr = $.ajax({ type: 'POST',
                            url: ApplicationRoot + "Scan.asmx/Search",
                            data: JSON.stringify(PostData),
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            success: function (result, status) {
                                $(searchInput).focus();
                                var SearchResultContainer = result.d ? result.d : result;

                                if (SearchResultContainer != null) {
                                    var FirstItem = true;

                                    $.each(SearchResultContainer, function (index, item) {
                                        var HeaderItem = $("a.HeaderItem." + item.TypeName, ResultHeader);
                                        if (HeaderItem.length == 0) {
                                            HeaderItem = $("<a href=\"javascript:\" class=\"HeaderItem " + item.TypeName + "\">" + item.TabHeader + " <span class=\"TotalResults\">[" + item.TotalResults + "]</span></a>");
                                            $(ResultHeader).append(HeaderItem);
                                        }
                                        else {
                                            $("span.TotalResults", HeaderItem).html("[" + item.TotalResults + "]");
                                        }
                                        var ResultPage = $("div.ResultPage." + item.TypeName);
                                        if (ResultPage.length == 0) {
                                            ResultPage = $("<div class=\"ResultPage " + item.TypeName + "\" style=\"display: none;\">" + item.TypeName + "</div>");
                                            $(ResultPages).append(ResultPage);
                                            if (FirstItem) {
                                                $("a", ResultHeader).removeClass("on");
                                                $("a." + item.TypeName).addClass("on");
                                                $(ResultPage).show();
                                            }
                                        }
                                        if (FirstItem) FirstItem = false;
                                        SetResultSet(ResultPage, item);
										SetPageIndex(ResultPage, 0);
										DisplayResultPage(ResultPage);
                                        $(".HeaderItem." + item.TypeName, ResultHeader).click(function () {
                                            $("a", ResultHeader).removeClass("on");
                                            $(this).addClass("on");
                                            $("div.ResultPage", ResultPages).hide();
                                            $("div.ResultPage." + item.TypeName, ResultPages).show();
                                            $(searchInput).focus();
                                        });
                                    });

                                    Show();
                                }
                                _gaq.push(["_trackEvent", "Live Search Query", $(searchInput).val()]);
                            }
                        })
                    }, SearchDelay);
                }
            });

            function GetResultSet(ResultPage) {
                return $(ResultPage).data("ResultSet");
            }

            function SetResultSet(ResultPage, ResultSet) {
                return $(ResultPage).data("ResultSet", ResultSet);
            }

            function GetPageIndex(ResultPage, PageIndex) {
                return $(ResultPage).data("PageIndex");
            }

            function SetPageIndex(ResultPage, PageIndex) {
                $(ResultPage).data("PageIndex", PageIndex);
            }

            function DisplayResultPage(ResultPage) {
                var PageIndex = GetPageIndex(ResultPage);
                var ResultSet = GetResultSet(ResultPage);

                if (ResultSet.PageList.length > 0) {
                    if (PageIndex >= 0 && ResultSet.PageList.length > PageIndex) {
                        $(ResultPage).html($("#" + ResultSet.TemplateId).render(ResultSet.PageList[PageIndex]));
                        Scan.Basket.UpdateProductLists();

                        $(".Paging", ResultPage).html("Page " + (PageIndex + 1) + " of " + ResultSet.PageList.length + " - " + (ResultSet.TooManyResults ? "more than " + ResultSet.TotalResults : ResultSet.TotalResults) + " " + ResultSet.NameP.toLowerCase() + " <span class=\"helper\">[Press ENTER to view all " + ResultSet.NameP.toLowerCase() + "]</span>");

                        SelectResult(ResultPage, -1); //Select paging header

                        $(ResultPages).click(function () {
                            $(searchInput).focus();
                        });

                        $("li", ResultPage).mouseover(function () {
                            var index = $("li", ResultPage).index(this);
                            SelectResult(ResultPage, index);
                        });

                        if (PageIndex > 0) {
                            $(".prev", ResultPage).click(function () {
                                PreviousPage(ResultPage, false);
                                $(searchInput).focus();
                            });
                        }
                        else {
                            $(".prev", ResultPage).hide();
                            $(".pagingseperator", ResultPage).hide();
                        }

                        if (PageIndex < ResultSet.PageList.length - 1) {
                            $(".next", ResultPage).click(function () {
                                NextPage(ResultPage, false);
                                $(searchInput).focus();
                            });
                        }
                        else {
                            $(".next", ResultPage).hide();
                            $(".pagingseperator", ResultPage).hide();
                        }

                        $(".close", ResultPage).click(function () {
                            Hide();
                        });
                    }
                    else {
                        alert("PageIndex out of bounds");
                    }
                }
                else {
                    $(ResultPage).html("<p>Your search returned no " + ResultSet.NameP.toLowerCase() + ".</p>");
                }
            }

            function Show() {
                $(searchResultsHolder).show();
            }

            function Hide() {
                $(searchResultsHolder).hide();
            }

            function PreviousPage(ResultPage, SelectLastItem) {
                var ResultSet = GetResultSet(ResultPage);
                var PageIndex = GetPageIndex(ResultPage);

                if (PageIndex > 0 && PageIndex < ResultSet.PageList.length) {
                    PageIndex = PageIndex - 1;
                    SetPageIndex(ResultPage, PageIndex);

                    DisplayResultPage(ResultPage);

                    if (SelectLastItem) {
                        var Results = $("li", ResultPage);
                        var ResultIndex = $(Results).index($("li:last", ResultPage));
                        SelectResult(ResultPage, ResultIndex);
                    }
                }
            }

            function NextPage(ResultPage, SelectFirstItem) {
                var ResultSet = GetResultSet(ResultPage);
                var PageIndex = GetPageIndex(ResultPage);

                if (PageIndex < ResultSet.PageList.length - 1) {
                    PageIndex = PageIndex + 1;
                    SetPageIndex(ResultPage, PageIndex);

                    DisplayResultPage(ResultPage);

                    if (SelectFirstItem) {
                        var Results = $("li", ResultPage);
                        var ResultIndex = $(Results).index($("li:first", ResultPage));
                        SelectResult(ResultPage, ResultIndex);
                    }
                }
            }

            function NextResult(ResultPage) {
                var ResultSet = GetResultSet(ResultPage);
                var PageIndex = GetPageIndex(ResultPage);
                var Results = $("li", ResultPage);
                var SelectedResult = $("li.selected", ResultPage);

                var CurrentIndex = Results.index(SelectedResult);
                CurrentIndex = CurrentIndex + 1;

                if (CurrentIndex < ResultSet.PageList[PageIndex].ResultList.length) {
                    SelectResult(ResultPage, CurrentIndex);
                }
                else if (PageIndex < ResultSet.PageList.length - 1) {
                    NextPage(ResultPage, true);
                }
            }

            function PreviousResult(ResultPage) {
                var PageIndex = GetPageIndex(ResultPage);
                var Results = $("li", ResultPage);
                var SelectedResult = $("li.selected", ResultPage);

                var CurrentIndex = Results.index(SelectedResult);
                CurrentIndex = CurrentIndex - 1;

                if (CurrentIndex >= -1) {
                    SelectResult(ResultPage, CurrentIndex);
                }
                else if (PageIndex > 0) {
                    PreviousPage(ResultPage, true);
                }
                else {
                    //SelectResult(ResultPage, -1);
                }
            }

            function SelectResult(ResultPage, ResultIndex) {
                var ResultSet = GetResultSet(ResultPage);

                var PagingHeader = $("p.Paging", ResultPage);
                PagingHeader.removeClass("selected");

                var Results = $("li", ResultPage);
                Results.removeClass("selected");

                if (ResultIndex == -1) {
                    PagingHeader.addClass("selected");
                    if (ResultSet.PromptAllResults) {
                        $("span.helper", PagingHeader).html("[Press ENTER to view all " + ResultSet.NameP.toLowerCase() + "]");
                    }
                    else {
                        $("span.helper", PagingHeader).html("");
                    }
                }
                else {
                    Results.eq(ResultIndex).addClass("selected");
                    $("span.helper", PagingHeader).html("[Press ENTER to view highlighted " + ResultSet.NameS.toLowerCase() + "]");
                }
            }

        });
    }
})(jQuery);
// Live Search - End


// misc plugins
(function ($) {
    $.fn.center = (function () {
        this.css("position", "absolute");
        this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
        this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
        return this;
    });
})(jQuery);

(function ($) {
    jQuery.fn.liveDraggable = function (opts) {
        this.live("mouseover", function () {
            if (!$(this).data("init")) {
                $(this).data("init", true).draggable(opts);
            }
        });
    };
})(jQuery);


