// JavaScript Document
function Cookie(document,name,hours,path,domain,secure)
{
	this.$document = document;
	this.$name = name;
	if(hours) this.$expiration = new Date((new Date()).getTime() + hours * 3600000);
	else this.$expiration = null;
	if(path) this.$path = path; else this.$path = null;
	if(domain) this.$domain = domain; else this.$domain = null;
	if(secure) this.$secure = true; else this.$secure = false;
}

Cookie.prototype.store = function()
{
	var cookieval = "";
	for(var prop in this){
		if(prop.charAt(0) == '$' || ((typeof this[prop]) == 'function'))
			continue;
		if(cookieval != "")
			cookieval += '&';
		cookieval += prop + ':' + escape(this[prop]);
	}
	
	var cookie = this.$name + '=' + cookieval;

	if(this.$expiration) cookie += '; expires=' + this.$expiration.toGMTString();
	if(this.$path) cookie += '; path=' + this.$path;
	if(this.$domain) cookie += '; domain=' + this.$domain;
	if(this.$secure) cookie += '; secure';
	
	this.$document.cookie = cookie;
}

Cookie.prototype.load = function()
{
	var allcookies = this.$document.cookie;
	if(allcookies == "")
		return false;
	
	var start = allcookies.indexOf(this.$name + '=');
	if(start == -1)
		return false;

	start += this.$name.length + 1;
	
	var end = allcookies.indexOf(';', start);
	if(end == -1)
		end = allcookies.length;
		
	var cookieval = allcookies.substring(start,end);
	
	var a = cookieval.split('&');
	for(var i = 0; i < a.length; i++)
		a[i] = a[i].split(':');
		
	for(var i = 0; i < a.length; i++)
		this[a[i][0]] = unescape(a[i][1]);
		
	return true;
}

Cookie.prototype.remove = function()
{
	var cookie;
	cookie = this.$name + '=';
	
	if(this.$path)
		cookie += this.$path;
	if(this.$domain)
		cookie += '; domain=' + this.$domain;
	
	cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';
	
	this.$document.cookie = cookie;
}

function getArgs()
{
	var args = new Object();
	var query = location.search.substring(1);
	var pairs = query.split(",");
	for(var i = 0; i < pairs.length; i++){
		var nIndex = pairs[i].indexOf('=');
		if(nIndex == -1)
			continue;
		var name = pairs[i].substring(0,nIndex);
		var val = pairs[i].substring(nIndex + 1);
		args[name] = unescape(val);
	}

	return args;
}

function inBounds(cookieString)
{
	if(cookieString.length > 4050){		//max cookie size is 4096
		alert("Too many items!\n\nYour shopping basket is overflowing.\nPlease proceed to the checkout.");
		return false;
	}
	
	return true;
}

function switchItems(cartArray, j, i)
{
	var temp = new Array(4);
	for(var k = 0; k < 4; k++){
		temp[k] = cartArray[i + k];
		cartArray[i + k] = cartArray[j + k];
		cartArray[j + k] = temp[k];
	}
}

function sortCart(cartArray)
{
	for(var i = 0; i < cartArray.length; i += 4)
		for(var j = i; j < cartArray.length; j += 4)
			if(cartArray[j] > cartArray[i])
				switchItems(cartArray, j, i);

	return cartArray;
}

function cleanCart(cartArray)
{
	var temp = new Array();
	var k = 0;
	for(var i = 0; i < cartArray.length; i += 4)
		if(cartArray[i + 1] + cartArray[i + 2] + cartArray[i + 3] > 0)
			for(var j = 0; j < 4; j++)
				temp[k++] = cartArray[i + j];
				
	return temp;
}

function storeCart(cartCookie, cartArray)
{
	cartArray = cleanCart(cartArray);
	sortCart(cartArray);
	
	cartCookie["cart"] = "";
	for(var i = 0; i < cartArray.length; i ++){
		cartCookie["cart"] += cartArray[i];
		if(i < cartArray.length - 1)
			cartCookie["cart"] += "*";
	}
	
	if(cartCookie["cart"].length)
		cartCookie.store();
	
	else 
		cartCookie.remove();
}

function getIDIndex(ID, cartArray)
{
	var nLen = cartArray.length;
	for(var i = 0; i < nLen ; i += 4)
		if(cartArray[i] == ID)
			return i;
			
	for(var i = nLen; i < nLen + 4; i++)
		cartArray[i] = "";
	
	return cartArray.length - 4;
}

function emptyCart()
{		
	var cartCookie = new Cookie(document,"cart");
	if(cartCookie.load())
		cartCookie.remove();
}

function isCartEmpty()
{
	var cartCookie = new Cookie(document,"cart");
	if(!cartCookie.load())
		return true;
			
	var cartArray = cartCookie["cart"].split("*");
	var total = 0;
	for(var i = 0; i < cartArray.length; i += 4)
		for(var j = i + 1; j < i + 4; j++)			
			total += cartArray[j];		
			
	return total == 0;
}

function addToCart(ID,q1,q2,q3)
{
	this.q1 = arguments.length > 1 ? q1 : "1";
	this.q2 = arguments.length > 2 ? q2 : "";
	this.q3 = arguments.length > 3 ? q3 : "";
	
	var cartCookie = new Cookie(document,"cart");				
	
	var IDIndex = 0;
	var cartArray = null;
	
	if(cartCookie.load()){
		if(!inBounds(cartCookie["cart"]))
			return;
			
		cartArray = cartCookie["cart"].split("*");
	}
	else
		cartArray = new Array();
		
	IDIndex = getIDIndex(ID, cartArray);
	
	cartArray[IDIndex] = ID.toString();
	
	if(this.q1.toString() != "")
		cartArray[IDIndex + 1] = this.q1.toString();
		
	if(this.q2.toString() != "")
		cartArray[IDIndex + 2] = this.q2.toString();
		
	if(this.q3.toString() != "")
		cartArray[IDIndex + 3] = this.q3.toString();
	
	storeCart(cartCookie, cartArray);
}

function setFormItem(elem, val /* val in pennies */)
{
	val = parseInt(val);
	
	if(val == 0)
		val = "0.00";

	if(val < 10)
		val = "0.0" + val.toString();
	
	else if(val < 100)
		val = "0." + val.toString();
		
	else{
		val = val.toString();
		val = val.substring(0, val.length - 2) + "." + val.substring(val.length - 2);
	}
	
	elem.value = val;
}

function calcSalesTax(subTotal)
{
	var taxRate = document.forms[0]["taxRate"].value;
	return parseInt(Math.round(subTotal * taxRate));
}

function calculate(id)
{		
	var itemTotal = document.forms[0]["Cost" + id].value * 100;
	var subTotal = document.forms[0]["subTotal"].value * 100 - itemTotal;
	
	var qty = document.forms[0]["Qty" + id].value;
	if(isNaN(qty) || qty < 0){
		qty = 1;
		document.forms[0]["Qty" + id].value = 1;
	}
	
	var itemCount = document.forms[0]["itemCount"].value;
	var unitPrice = document.forms[0]["Price" + id].value * 100;
	
	if(qty == 0){
		var name = document.forms[0]["Name" + id].value;
		if(confirm("Please confirm you want to completely remove to following item...\n\n" + name + "\n")){
			document.getElementById("item" + id).style.display = "none";
			--itemCount;
		}
		else{
			qty = Math.round(itemTotal / unitPrice);
			document.forms[0]["Qty" + id].value = qty;
		}
	}
	
	itemTotal = parseInt(Math.round(unitPrice * qty));
	
	subTotal += itemTotal;
	
	var salesTax = calcSalesTax(subTotal);
	var grandTotal = subTotal + salesTax;

	setFormItem(document.forms[0]["Cost" + id], itemTotal);
	setFormItem(document.forms[0]["subTotal"], subTotal);
	setFormItem(document.forms[0]["salesTax"], salesTax);
	setFormItem(document.forms[0]["grandTotal"], grandTotal);
	
	addToCart(id, qty, "", "");
			
	if(itemCount > 0)
		document.forms[0]["itemCount"].value = itemCount;
		
	else
		location.reload(true);
}

function update()
{
//	do nothing - the onchange event takes care of everything
}

function quickBuy(id, name, price)
{
	addToCart(id,"1");
	var val = String.fromCharCode(163) + price;
	var msg = name + " - Quantity 1 - " + val + "\n\nThis item has been added to your shopping basket.\nClick the \"View Basket\" button to check your order and make any changes.";
	alert(msg);
	
	if(location.pathname.indexOf("Cart.aspx") != -1)
		location.reload();
}

//Checks for a url in the 'ref' cookie and, if found,
//navigates to that url. Otherwise steps back in history.
function goBack()
{
	var refCookie = new Cookie(document, "ref");
	
	if(refCookie.load() && refCookie["ref"]){
		refCookie.remove();
		location = refCookie["ref"];
	}
	
	else
		history.back();
}

//Appends 'ref=Cart.aspx' to detail url query string so that
//future calls to 'goBack()' will cause a page refresh to update
//the cart details on display
function goDetail(id)
{	
	if(location.pathname.toLowerCase().indexOf("cart.aspx") != -1){
		var refCookie = new Cookie(document, "ref");
		refCookie["ref"] = "Cart.aspx";
		refCookie.store();
	}
	
	location = "Detail.aspx?ProductID=" + id;
}