// JavaScript Document
function setAttributes()
{
	//Set selected vals from cart and/or from query string
	var attVal = getArgs()["AttDetID"];
	if(attVal)
	{
		for(var i = 0; i < groups.length(); i++)
		{
			var selID = groups.groups[i].selID;
			var ddl = document.forms[0][selID];
			if(ddl)
			{
				for(var j = 0; j < ddl.options.length; j++)
				{
					if(ddl.options[j].value == attVal)
					{
						ddl.selectedIndex = j;
						onSelChange();						
						return;
					}
				}
			}
		}		
	}
}
function roundPrice(p)
{	
	var pound = String.fromCharCode(163);
	var price = pound + (new Number(p)).toFixed(2);
	return price;
}
function CookieItem(id, qty, price)
{
	this.getValue = function()
	{
		return this.cartID + "_" + this.qty + "_" + this.price;
	}
	
	var p = price;
	var i = 0;
	while(isNaN(parseInt(p)) && p.length)
		p = p.substr(++i);
			
	if(isNaN(p))
	{
		alert("An unexpected error occurred");
		return;
	}
			
	this.cartID = id;
	this.qty = qty;
	this.price = p;
}
function Cart()
{
	this.toString = function()
	{
		var str = "";
		var count = 0;
		for(var i = 0; i < this.cookieItems.length; i++)
		{
			if(this.cookieItems[i].qty > 0)
			{
				if(count++ > 0)
					str += "*";
				
				str += this.cookieItems[i].getValue();
			}
		}
		return str;
	}
	this.getItemIndex = function(cartID)
	{
		if(this.cookieItems.length)
			for(var i = 0; i < this.cookieItems.length; i++)
				if(this.cookieItems[i].cartID == cartID)
					return i;
			
		return -1;
	}
	this.addItem = function(cookieItem)
	{
		var nIndex = this.getItemIndex(cookieItem.cartID);
		if(nIndex == -1)
			this.cookieItems.push(cookieItem);
		
		else
			this.cookieItems[nIndex] = cookieItem;		
	}
	this.removeItem = function(cartID)
	{
		var nIndex = this.getItemIndex(cartID);
		if(nIndex != -1)
			this.cookieItems[nIndex].qty = 0;
	}
	//3.0.10
	this.removeAll = function()
	{
//	    for(var i = 0; i < this.cookieItems.length; i++)    //removed 3.0.29
//		    this.cookieItems[i].qty = 0;                    //ditto
		    
		this.remove();
	}
	//end 3.0.10
	this.count = function()
	{
		var nCount = 0;
		for(var i = 0; i < this.cookieItems.length; i++)
			if(this.cookieItems[i].qty > 0)
				++nCount;
				
		return nCount;
	}
	this.load = function()
	{
		this.cookie = new Cookie(document, "cart");
		if(this.cookie.load())
		{			
			var items = this.cookie["cart"].split("*");
			for(var i = 0; i < items.length; i++)
			{
				var vals = items[i].split("_");
				this.addItem(new CookieItem(vals[0], vals[1], vals[2]));
			}
		}
	}
	this.save = function()
	{
		var val = this.toString();
		if(val.length)
		{
			this.cookie["cart"] = val;
			this.cookie.store();
		}
	}
	this.remove = function()
	{
	    for(var i = 0; i < this.cookieItems.length; i++)	//3.0.29		
		    this.cookieItems[i].qty = 0;                    //3.0.29
		    
		this.cookie.remove();
	}
	//Aug 07
	this.isEmpty = function()
	{
		return this.count() == 0;
	}
	this.cookieItems = new Array();
	this.cookie = null;
	this.load();
}
function Group(selID, name)
{
	this.selID = selID;
	this.name = name;
	this.getValue = function()
	{
		return document.forms[0][this.selID].value;
	}
}
function Groups()
{
	this.add = function(selID, name)
	{
		this.groups.push(new Group(selID, name));
	}
	this.getGrpID = function(index)
	{
		var selID = this.groups[index].selID;
		while(isNaN(parseInt(selID)) && selID.length)
			selID = selID.substr(1);
			
		return parseInt(selID);
	}
	this.getGrpName = function(index)
	{
		return this.groups[index].name;
	}
	this.getSelID = function(index)
	{
		return this.groups[index].getValue();
	}
	this.getSelText = function(index)
	{
		var sel = this.groups[index].selID;
		sel = document.forms[0][sel];
		var selIndex = sel.selectedIndex;
		return sel.options[selIndex].text;
	}
	this.verify = function()
	{
		for(var i = 0; i < this.groups.length; i++)
		{
			if(this.groups[i].getValue() == -1)
			{
				alert("Please select a value for all atributes [" + this.groups[i].name + "]");
				return false;
			}
		}
		return true;
	}
	this.getPriceModifier = function(details)
	{
		var pMod = 0;
		for(var i = 0; i < this.groups.length; i++)
		{
			var detID = this.groups[i].getValue();
			if(detID != -1)
				pMod += details.getPriceModifier(detID);
		}
		return pMod;
	}
	this.getValue = function()
	{
		var sel = "";
		for(var i = 0; i < this.groups.length; i++)
			sel += "-" + this.getSelID(i);
			
		return sel;
	}
	this.toString = function()
	{
		var sel = "";
		for(var i = 0; i < this.groups.length; i++)
		{
			var grpName = this.getGrpName(i);
			var selText = this.getSelText(i);
			
			if(sel.length)
				sel += "\n";

			sel += grpName + " : " + selText;
		}
		return sel;
	}
	this.length = function()
	{
		return this.groups.length;
	}
	this.groups = new Array();
}
function Detail(grpID, detID, dText, pMod)
{
	this.grpID = grpID;
	this.detID = detID;
	this.detText = dText;
	this.pMod = pMod;
}
function Details()
{
	this.add = function(grpID, detID, dText, pMod)
	{
		this.details.push(new Detail(grpID, detID, dText, pMod));
	}
	this.getPriceModifier = function(detID)
	{
		for(var i = 0; i < this.details.length; i++)
			if(this.details[i].detID == detID)
				return this.details[i].pMod;

		return 0;
	}
	this.details = new Array();
}
function CartItem()
{
	this.getUnitPrice = function()
	{
		var p = this.price;
		var i = 0;
		while(isNaN(parseInt(p)) && p.length)
			p = p.substr(++i);
			
		return p / this.qty;
	}
	this.toString = function()
	{
		var tStr = this.serialNo + " : " + this.prodName;
		tStr += "\n------------------------------------------------------------------------------------\n";	
								
		if(this.qty > 1)
			tStr += "These items have been added to your shopping cart";
		
		else
			tStr += "This item has been added to your shopping cart";
			
		if(this.attribStr.length)
			tStr += "\n";
		tStr += "\n" + this.attribStr;
		if(this.attribStr.length)
			tStr += "\n";
		
		tStr += "\nQuantity : " + this.qty;
		tStr += "\nTotal charge : " + this.price;
		tStr += "\n------------------------------------------------------------------------------------";					
		tStr += "\nClick on 'Shopping cart' at the top of the page to review your selection";
		return tStr;
	}	
	
	this.qty = document.forms[0]["qty"].value;
	this.prodID = document.forms[0]["ProdID"].value;;
	this.prodName = document.forms[0]["ProdName"].value;
	this.serialNo = document.forms[0]["ProdSerialNo"].value;
	this.price = document.forms[0]["Price"].value;
	if(document.forms[0]["DiscountedPrice"] && document.forms[0]["DiscountedPrice"].value)
		this.price = document.forms[0]["DiscountedPrice"].value;
	this.attribStr = groups.toString(); 
	this.attribVal = groups.getValue();
	this.itemID = this.prodID + this.attribVal;
	this.unitPrice = this.getUnitPrice();
}
function addToCart()
{
	if(!verifyCookies() || !(checkQty() && groups.verify()))
		return;
	 
	var item = new CartItem();
	alert(item.toString());
	
	setCartCookie(item.itemID, item.qty, item.unitPrice);
	setTotalCartItems();
}
function setCartCookie(itemID, itemQty, itemPrice)
{
	if(itemQty == 0)
		cart.removeItem(itemID);
	
	else
	{		
		var cookieItem = new CookieItem(itemID, itemQty, itemPrice);
		cart.addItem(cookieItem);
	}
	
	if(cart.count() > 0)
		cart.save();
	
	else
		cart.remove();
}
function onSelChange()
{
	setTotalPrice();
}
function getQty()
{
	var qty = document.forms[0]["qty"].value;		
	return isNaN(qty) ? 0 : qty;
}
function checkQty()
{
	var qty = document.forms[0]["qty"];
	if(isNaN(qty.value) || parseInt(qty.value) != qty.value) //3.0
	{
		alert("Incorrect quantity entered");
		qty.focus();
		qty.select();
		return false;
	}	
	return true;
}
function onQtyChange()
{
	checkQty();
	setTotalPrice();
}
function setDiscountedPrice(listPrice)
{
	if(document.forms[0]["DiscountPCent"])
	{
		var disc = document.forms[0]["DiscountPCent"].value;
		if(disc && disc > 0)
		{
			document.forms[0]["Price"].className = "listPrice";
			document.forms[0]["DiscountedPrice"].style.display = "inline";
			var discountedPrice = listPrice * (1 - disc/100);
			document.forms[0]["DiscountedPrice"].value = roundPrice(discountedPrice);
		}
	}
}
function setTotalCartItems()
{
	if(document.forms[0]["CartSummary"])
	{
		var text = "...";
		var count = cart.count();
		if(count == 1)
			text = count + " item";
		if(count > 1)
			text = count + " items";
			
		document.forms[0]["CartSummary"].value = text;
	}
}
function getBulkQtyPrice(price)
{
	var qty = getQty();	
	if(volQuant && volQuant.length)
	{
		var nIndex = -1;
		for(var i = 0; i < volQuant.length; i++)
			if(qty >= volQuant[i])
				nIndex = i;
			
		if(nIndex != -1)
			price += volPrice[nIndex];
	}
	
	return price * qty;
}
function setTotalPrice()
{
	var price = (basePrice + groups.getPriceModifier(details));		//2.4.5
	price = getBulkQtyPrice(price);									//2.4.5
	document.forms[0]["Price"].value = roundPrice(price);
	setDiscountedPrice(price);
	setVAT(price);                                                  //3.0.6
}
//3.0.6
var VAT_NOT_APPLICABLE = 0;
var VAT_INCLUDED = 1;
var VAT_EXCLUDED = 2;
function roundUp(n, numPlaces)
{
	var num = Math.pow(10, numPlaces);
	return parseInt(n * num + 0.999999) / num;
}
function setVAT(price)
{
	if(vatMethod == VAT_NOT_APPLICABLE)
		return;
		
    var vat = vatRate * price / 100;
    if(vatMethod == VAT_INCLUDED)
		vat = price * vatRate / (100 + vatRate);

	if(!setDiscountedVAT(vat))
	{				
		vat = roundUp(vat, 2);
		document.forms[0]["VATAmount"].value = roundPrice(vat);
    }
}
function setDiscountedVAT(vat)
{
	if(document.forms[0]["DiscountPCent"])
	{
		var disc = document.forms[0]["DiscountPCent"].value;
		if(disc && disc > 0)
		{		    
			var discountedVAT = vat * (1 - disc/100);	
			discountedVAT = roundUp(discountedVAT, 2);		
			document.forms[0]["VATAmount"].value = roundPrice(discountedVAT);
			return true;
		}
	}
	return false;
}
//3.0.6 end
function registerDetail(grpID, detID, text, pMod)
{
	details.add(grpID, detID, text, pMod);
}
function registerGroup(selID, name)
{
	groups.add(selID, name);
}
function onCartQuantityChanged(field, cartID, itemPrice)
{
//	itemPrice is the unit price discounted as appropriate
	var qty = field.value;
	if(isNaN(qty) || qty.indexOf(".") != -1)
	{
		alert("Error in the specified quantity [must be numeric]");
		field.value = lastQty;
		return;
	}
	
	setCartCookie(cartID, qty, itemPrice);
	location.href = "Cart.aspx";
}
//2.4.8
function removeCartItem(cartID)
{
	setCartCookie(cartID, 0, 0);
	location.href = "Cart.aspx";
}
function onCartQuantityFocus(field)
{
	lastQty = field.value;
}
function recalculate()
{
}
function verifyCookies()
 {
	var tmpcookie = new Date();
	var chkcookie = (tmpcookie.getTime() + '');
	document.cookie = "chkcookie=" + chkcookie + "; path=/";
    if(document.cookie.indexOf(chkcookie, 0) == -1) 
	{
		var msg = "Cookies are not enabled....\n\n";
		msg += "This web site uses cookies to track your shopping cart and manage your shopping experience.\n";
		msg += "Please ensure that they are enabled and/or that your security settings are set to 'Medium'.\n\n";
		if(navigator.userAgent.indexOf("MSIE") != -1)
			msg += "(Internet Explorer > Tools > Internet Options > Security > Custom Level > Medium)";

		alert(msg);
		return false;
	}

	return true;
}
//Aug 07
function goCart(url)
{
	if(cart.isEmpty())
		alert("Your shopping cart is empty")
		
	else
		location.href = url;
}

//Aug 07 ends
var cart = new Cart();				//Cart
var groups = new Groups();			//Attribute groups
var details = new Details();		//Attribute details
var basePrice = null;
var lastQty = null;
var volQuant = null;                //3.0
var volPrice = null;                //3.0

//3.0.10 - empty the cart on complete
if(location.pathname.toLowerCase().indexOf("/completey") != -1)
    cart.removeAll();

//3.0.13    
function doSignOut(url)
{
    if(!cart.isEmpty())
        if(!confirm("Please confirm you want to sign out and empty the contents of you shopping cart"))
            return;
            
    location.href = url;
}
if(location.pathname.toLowerCase().indexOf("/signout.aspx") != -1)
    cart.removeAll();