/*
	JavaScript for Sysnet.co.uk
	Author: Jackie McGhee (jackie DOT mcghee AT sysnet DOT co DOT uk)
	Date Created: 29/04/2004
	Date Changed: 13/10/2004
*/

function cryWolf()
/*
	This function is only here to give an alert to let you know that the
	file has been found.
	
	USE: <body onload="cryWolf()">
*/
{
	alert("Script file found.");
}

// WINDOW OPENERS

function navigateParent(location)
{
	self.parent.opener.location.href = location;
	window.parent.close();
}

function launchZoom(assetLocation, width, height)
{
	var winName = "zoomerBoomer";
	var screenWidth = screen.width;
	var screenHeight = screen.height;
	var top = (screenHeight - height) / 2;
	var left = (screenWidth - width) / 2;
	var winProps = "top=" + top  + ", left=" + left + ", width=" + width + ", height=" + height + ", toolbar=no, scrollbars=yes, status=yes";
	var newWin = window.open(assetLocation, winName, winProps);
	newWin.focus();
}

function spawn(location)
/*
	Opens a small window for diplaying Penmail, Penpoint forms and Legal & Privacy notices.
	Rarely used on it's own, it tends to be called from other functions like getPenpoint
	
	USE: <a href="url-to-thing.html" onclick="spawn(this.href); return false">blah</a>
	
	IMPORTANT: the "return false" is important as this prevents the clicked link from opening in the new window
	However, if JavaScript is switched off, the requested page will open in the current window and so is more
	accessible.
*/
{
	var winName = "gonzo";
	var winProps = "top=16, left=16, width=340, height=360, toolbar=no, scrollbars=yes, status=yes";
	var newWin = window.open(location, winName, winProps);
	newWin.focus();
}

function spawnSite(location)
/*
	Opens a regular window usually for a page request on another domain
	
	USE: <a href="url-to-thing.html" onclick="spawnSite(this.href); return false">blah</a>
	
	IMPORTANT: the "return false" is important as this prevents the clicked link from opening in the new window
	However, if JavaScript is switched off, the requested page will open in the current window and so is more
	accessible.
*/
{
	var winName = "monkey";
	var newWin = window.open(location, winName);
	newWin.focus();
}

function getDirectionsGlasgow()
/*
	Sends the entered postcode to mapquest to retrieve directions
	
	Uses spawnSite()
*/
/*
	Sends the entered postcode to google maps to retrieve directions
	
	Uses spawnSite()
*/
{
	if (document.getElementById) {
		var sourcePostCode = document.getElementById("dPostCode");
		if (sourcePostCode.value == "") {
			alert("You must supply a postcode");
			return;
		}
		sourcePostCode.value = sourcePostCode.value.toUpperCase();
		var sourcePostCodePair = sourcePostCode.value.split(" ");
		var loc1 = "http://maps.google.co.uk/maps?f=d&hl=en&geocode=&saddr="
		var loc2 = "&daddr=G23LG&hl=en&geocode=&mra=ls&sll=53.800651,-4.064941&sspn=14.223239,37.617188&ie=UTF8&z=11";
		var mapLocation = loc1 + sourcePostCodePair[0] + loc2;
		spawnSite(mapLocation);
	}
}


function getDirectionsHillington()
/*
	Sends the entered postcode to google maps to retrieve directions
	
	Uses spawnSite()
*/
{
	if (document.getElementById) {
		var sourcePostCode = document.getElementById("dPostCode");
		if (sourcePostCode.value == "") {
			alert("You must supply a postcode");
			return;
		}
		sourcePostCode.value = sourcePostCode.value.toUpperCase();
		var sourcePostCodePair = sourcePostCode.value.split(" ");
		var loc1 = "http://maps.google.co.uk/maps?f=d&hl=en&geocode=&saddr="
		var loc2 = "&daddr=Hillington+innovation+centre&sll=55.826552,-4.494781&sspn=0.133641,0.299721&ie=UTF8&ll=55.860547,-4.361213&spn=0.001043,0.002342&t=h&z=19";
		var mapLocation = loc1 + sourcePostCodePair[0] + loc2;
		spawnSite(mapLocation);
	}
}

function getDirectionsAlba()
/*
	Sends the entered postcode to google maps to retrieve directions
	
	Uses spawnSite()
*/
{
	if (document.getElementById) {
		var sourcePostCode = document.getElementById("dPostCode");
		if (sourcePostCode.value == "") {
			alert("You must supply a postcode");
			return;
		}
		sourcePostCode.value = sourcePostCode.value.toUpperCase();
		var sourcePostCodePair = sourcePostCode.value.split(" ");
		var loc1 = "http://maps.google.co.uk/maps?f=d&hl=en&geocode=&saddr="
		var loc2 = "&daddr=55.873963,-3.549206&mra=mi&mrsp=0&sz=16&sll=55.874107,-3.549271&sspn=0.007728,0.017037&ie=UTF8&z=16";
		var mapLocation = loc1 + sourcePostCodePair[0] + loc2;
		spawnSite(mapLocation);
		
	}
}



// FORM HELPERS

function setupShipping()
/*
	Copies billing address into shipping address fields on payment form
*/
{
	if (document.getElementById) {
		var bAddress1 = document.getElementById("address1");
		var bAddress2 = document.getElementById("address2");
		var bCity = document.getElementById("city");
		var bPostCode = document.getElementById("postCode");

		var sAddress1 = document.getElementById("shippingAddress1");
		var sAddress2 = document.getElementById("shippingAddress2");
		var sCity = document.getElementById("shippingCity");
		var sPostCode = document.getElementById("shippingPostCode");

		sAddress1.value = bAddress1.value;
		sAddress2.value = bAddress2.value;
		sCity.value = bCity.value;
		sPostCode.value = bPostCode.value;
	}
}

function checkAgreement(formId, boxId)
/*
	Checks that the "I agree to t's&c's" checkbox is set and alerts use if it isn't
*/
{
	if (document.getElementById) {
		theForm = document.getElementById(formId);
		theBox = document.getElementById(boxId);
		if (theBox.checked) {
			return true;
		} else {
			alert("You MUST agree to the terms and conditions before you are allowed to start using your pen.");
			return false;
		}
	}
}

function getOrderConfirmation()
/*
	NO LONGER USED
	
	Checks that the user had confirmed their order at checkout 1
*/
{
	if (document.getElementById) {
		var theBox = document.getElementById("orderConfirm");
		if (!theBox.checked) {
			alert("You must confirm your order to proceed");
			return false;
		}
	}
}

// SHOPPING BASKET STUFF

try {
	var theCookie = document.cookie; // Load the cookie
} catch(err) {
	alert("You must enable cookies for the shop to work.");
}

var pairs = theCookie.split(";"); // Split into name=value pairs
var numberOfPenpoints = 0;

function emptyBasket()
/*
	Function to clear the basket of all items
	
	Distinct from clearBasket() due to context. This one is automatically called
	after an order is complete.
*/
{
	var itemsArray = new Array();
	for (n = 0; n < pairs.length; n++) {
		var bits = pairs[n].split("=");
		itemsArray[n] = bits[0];
	}

	for (var k = 0; k < itemsArray.length; k++) {
		killAllCookies(itemsArray[k], "kill", "No");
	}
}

function clearBasket()
/*
	Function to clear the basket of all items.
	
	Differs from emptyBasket() because this one has to be called manually from the basket page
*/
{
	if (confirm("Are you sure you want to clear your whole basket?\n\nYou cannot undo this operation once it has been carried out.")) {
		var itemsArray = new Array();
		for (n = 0; n < pairs.length; n++) {
			var bits = pairs[n].split("=");
			itemsArray[n] = bits[0];
		}

		for (var k = 0; k < itemsArray.length; k++) {
			killCookie(itemsArray[k], "kill", "No");
		}
	}
}

function clearBasketSilent()
/*
	Function to clear the basket of all items. DOES not ask user for confirmation
	
	Differs from emptyBasket() because this one has to be called manually from the license page
*/
{
		var itemsArray = new Array();
		for (n = 0; n < pairs.length; n++) {
			var bits = pairs[n].split("=");
			itemsArray[n] = bits[0];
		}

		for (var k = 0; k < itemsArray.length; k++) {
			killCookie(itemsArray[k], "kill", "No");
		}
		
}

function collectAndSet()
/*
	Pulls together all the information gathered in /sales/penpointinfo/index.jsp
	and writes them to cookies
*/
{
	if (document.getElementById) {
		var productId = document.getElementById("productId").value;
		var productName = document.getElementById("productName").value;
		var productPrice = document.getElementById("productPrice").value;
		var productWeight = 0;
		var quantity = 1;
		var penId = document.getElementById("penId").value;
		var mobilePhoneNumber = document.getElementById("mobilePhoneNumber").value;
		var mobileOperator = document.getElementById("mobileOperator").options[document.getElementById("mobileOperator").options.selectedIndex].value;

		var cookieValueString = productName + "|" + productPrice + "|" + quantity + "|" + productWeight + "|No";

		setCookie(productId, cookieValueString, false);
		setCookie("penId", penId, false);
		setCookie("mobilePhoneNumber", mobilePhoneNumber, false);
		setCookie("mobileOperator", mobileOperator, false);
		window.opener.location.reload(true);
		self.close();
	}
}

function collectAndSett()
/*
	Pulls together all the information gathered in /sales/penpointinfo/index.jsp
	and writes them to cookies
*/
{
	if (document.getElementById) {
		var productId = document.getElementById("productId").value;
		var productName = document.getElementById("productName").value;
		var productPrice = document.getElementById("productPrice").value;
		var productWeight = 0;
		var quantity = 1;
		var penId = document.getElementById("penId").value;
		var mobilePhoneNumber = document.getElementById("mobilePhoneNumber").value;
		var mobileOperator = document.getElementById("mobileOperator").value;

		var cookieValueString = productName + "|" + productPrice + "|" + quantity + "|" + productWeight + "|No";

		setCookie(productId, cookieValueString, false);
		setCookie("penId", penId, false);
		setCookie("mobilePhoneNumber", mobilePhoneNumber, false);
		setCookie("mobileOperator", mobileOperator, false);
		window.opener.location.reload(true);
		self.close();
	}
}

function getPenpoint(productId, productName, price)
/*
	Opens a small window to collect Penpoint info
	
	Uses spawn()
*/
{
	var locationWithQuery = "/sales/penpointinfo/?productId=" + productId + "&productName=" + productName + "&price=" + price;
	spawn(locationWithQuery);
}

function getPenmail(productId, productName, price)
/*
	Same as above except for Penmail
	
	Uses spawn()
*/
{
	var locationWithQuery = "/sales/penmailinfo/?productId=" + productId + "&productName=" + productName + "&price=" + price;
	spawn(locationWithQuery);
}

function showBasket()
/*
	Function to display the shopping basket
	
	USE:						
	<table border="0" cellpadding="3" cellspacing="1" width="100%" class="basketDisplay">
		<tr>
			<th>Code</th>
			<th width="100%">Item Description</th>
			<th>Price (&pound;)</th>
			<th>Quantity</th>
			<th>&nbsp;</th>
		</tr>
		<script type="text/javascript">showBasket();</script>
	</table>
*/
{
	var runningTotal = 0;
	var weight = 0;
	var index = theCookie.indexOf("=");
	var orderString = "";
	var orderContainsPen = false;
	var orderContainsPenpoint = false;
	var penId = "";
	var mobilePhoneNumber = "";
	var mobileOperator = "";
	var numberOfRows = 0;

	var penmailFlag = false;
	var killPenSwitch = "false";

	if (index == -1) {
		document.writeln('<tr><td colspan="5" class="nope">Your basket is currently empty.<div class="huge">*</div></td></tr>');
	} else {
		cookiecount:
		for (n = 0; n < pairs.length; n++) {
			var bits = pairs[n].split("=");
			if (bits[0].indexOf("JSESSIONID") != -1) {
				continue cookiecount;
			}

			if (bits[0].indexOf("penId") != -1) {
				penId = bits[1];
				orderContainsPenpoint = true;
				continue cookiecount;
			}

			if (bits[0].indexOf("mobilePhoneNumber") != -1) {
				mobilePhoneNumber = bits[1];
				orderContainsPenpoint = true;
				continue cookiecount;
			}

			if (bits[0].indexOf("mobileOperator") != -1) {
				mobileOperator = bits[1];
				orderContainsPenpoint = true;
				continue cookiecount;
			}

			if (bits[0].indexOf("orderContainsPen") != -1) {
				orderContainsPen = true;
				continue cookiecount;
			}

			if (bits[0].indexOf("orderHasPenmail") != -1) {
				continue cookiecount;
				penmailFlag = true;
			}
			
			/*
				These if()s allow the function to skip over cookie items which are not basket items
				
				Also setting certain flags for use in payment and UK Shipping
			*/

			var vals = bits[1].split("|");

			orderString += unescape(vals[2]) + " x " + unescape(vals[0]) + " (" + bits[0] + ") / ";
			killPenSwitch = (vals[4] == "Yes") ? "Yes" : "No";
			orderContainsPen = (vals[4] == "Yes") ? true : false;

			with (document) {
				// This is the bit that actually prints out the table 
				writeln('<tr>\n');
				writeln('<td class=\"odd\">' + bits[0] + '<input type=\"hidden\" id=\"productId_' + n + '\" name=\"productId_' + n + '\" value=\"' + bits[0] + '\" /></td>\n');
				writeln('<td class=\"odddesc\">' + unescape(vals[0]) + '</td>\n');
				writeln('<td class=\"odd\">' + unescape(vals[1]) + '</td>\n');
				writeln('<td class=\"odd\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"1\"><tr><td width=\"100%\"><input size=\"2\" maxlength=\"2\" id=\"quantity_' + n + '\" name=\"quantity_' + n + '\" type=\"text\" class=\"shop\" value=\"' + unescape(vals[2]) + '\"></td> \n');
				writeln('<td><img src=\"/p/icon-update.gif\" class=\"fButton\" title=\"Enter desired amount in the text box and click here\" onclick=\"updateCookie(\'' + bits[0] + '\', \'' + vals[0] + '|' + vals[1] + '|\',\'' + vals[3] + '\',\'' + n + '\')\" /></td></tr></table></td>\n');
				writeln('<td align=\"center\" class=\"odd\"><img src=\"/p/icon-kill2.gif\" title=\"Remove ' + vals[0] + ' from basket\" class=\"fButton\" onclick=\"killCookie(\'' + bits[0] + '\', \'' + unescape(vals[0]) + '\', \'' + killPenSwitch + '\')\" /></td>\n');
				writeln('</tr>\n');
			}
			runningTotal += (((Number(vals[1]) * Number(vals[2])) * 100) / 100);
			weight += Number(vals[2]) * Number(vals[3]);
			numberOfRows = n;
		}
		with (document) {
			//Prints out the running total and also creates hidden fields containing info DM needs at the backend 
			writeln('<tr><td colspan=\"5\" class=\"totals\"><table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" width=\"100%\">');
			writeln('<tr><td align=\"right\"><div class=\"total\"><strong>Running Total</strong> (ex VAT + Shipping):  &pound;' + runningTotal + '<input type=\"hidden\" name=\"RUNNING_TOTAL\" id=\"runningTotal\" value=\"' + runningTotal +'\" /></div></td></tr>\n');
			writeln('</table><input type=\"hidden\" id=\"totalWeight\" name=\"totalWeight\" value=\"' + weight + '\" />');
			writeln('<input type=\"hidden\" name=\"numberOfRows\" id=\"numberOfRows\" value=\"' + numberOfRows + '\" />');
			writeln('<input type=\"hidden\" name=\"orderContainsPen\" id=\"orderContainsPen\" value=\"' + orderContainsPen + '\" />');
			writeln('<input type=\"hidden\" name=\"orderContainsPenpoint\" id=\"orderContainsPenpoint\" value=\"' + orderContainsPenpoint + '\" />');
			writeln('<input type=\"hidden\" name=\"penId\" id=\"penId\" value=\"' + penId + '\" />');
			writeln('<input type=\"hidden\" name=\"mobilePhoneNumber\" id=\"mobilePhoneNumber\" value=\"' + mobilePhoneNumber + '\" />');
			writeln('<input type=\"hidden\" name=\"mobileOperator\" id=\"mobileOperator\" value=\"' + mobileOperator + '\" />');
			writeln('<input type=\"hidden\" name=\"orderString\" id=\"orderString\" value=\"' + orderString + '\" />');
			writeln('</td></tr>');
		}
	}
}

function confirmOrder()
/*
	Function to display the order table
	
	USE:
	<table border="0" cellpadding="3" cellspacing="1" width="100%">
		<script type="text/javascript">confirmOrder();</script>
		<tr> ...
		</tr>
	</table>

*/
{
	var runningTotal = 0;
	var weight = 0;
	var postage = 0;
	var index = theCookie.indexOf("=");
	var penmailFlag = false;

	if (index == -1) {
		document.writeln('<tr><td colspan="5">You haven&#8217;t completed an order yet.</td></tr>');
	} else {
		cookiecount:
		for (n = 0; n < pairs.length; n++) {
			var bits = pairs[n].split("=");
			
			// Skips the cookie items which are not basket items
			
			if (bits[0].indexOf("JSESSIONID") != -1) {
				continue cookiecount;
			}

			if (bits[0].indexOf("penId") != -1) {
				continue cookiecount;
			}

			if (bits[0].indexOf("mobilePhoneNumber") != -1) {
				continue cookiecount;
			}

			if (bits[0].indexOf("mobileOperator") != -1) {
				continue cookiecount;
			}

			if (bits[0].indexOf("orderContainsPen") != -1) {
				continue cookiecount;
			}

			if (bits[0].indexOf("orderHasPenmail") != -1) {
				penmailFlag = true;
				continue cookiecount;
			}

			var vals = bits[1].split("|");

			with (document) {
				writeln('<tr>');
				writeln('<td>' + vals[2] + '</td>');
				writeln('<td width=\"100%\">' + vals[0] + '</td>');
				writeln('<td>@</td>');
				writeln('<td align="right"><strong>&pound;' + vals[1] + '</strong></td>');
				writeln('<td>each</td>');
				writeln('</tr>');
			}
			runningTotal += Number(vals[1]) * Number(vals[2]);
			weight += Number(vals[3]);
		}
		var vat = (runningTotal / 100) * 17.5;
		if (penmailFlag == true) {
			weight = 20;
			document.writeln('<tr><td colspan=\"5\"><input type=\"hidden\" name="orderHasPenmail" value=\"' + penmailFlag + '\" /></td></tr>');
		}
		//document.writeln('<tr><td colspan=\"2\" align=\"right\" valign=\"bottom\">Running Total</td><td valign=\"bottom\">:</td><td align=\"right\"><strong>&pound;' + runningTotal + '</strong></td><td>&nbsp;</td></tr>\n');
		//document.writeln('<tr><td colspan=\"5\"><input type=\"hidden\" name=\"OVERALL_WEIGHT\" value=\"' + weight + '\" /></td></tr>\n');
		document.writeln('<tr><td colspan=\"5\"><input type=\"hidden\" name=\"test\" value=\"' + weight + '\" /></td></tr>\n');
	}
}

function migrateBasket()
/*
	Function to create the hidden fields that are passed to gondor for Overseas Delivery
	
	USE:
	<form action="http://gondor.sysnet.co.uk/sysnet/website/overseas-purchases.nsf/CreateDoc?OpenAgent" method="post" id="ospForm">
		<script type="text/javascript">migrateBasket()</script>
	</form>
	
	For more info see the function submitOSP() in /sales/checkout/index.jsp
*/
{
	var runningTotal = 0;
	var weight = 0;
	var index = theCookie.indexOf("=");
	var orderString = "";
	var orderContainsPen = false;
	var orderContainsPenpoint = false;
	var penId = "";
	var mobilePhoneNumber = "";
	var mobileOperator = "";
	var numberOfRows = 0;

	var penmailFlag = false;
	var killPenSwitch = "false";

	if (index == -1) {
		document.location.href = "http://www.sysnet.co.uk/";
	} else {
		cookiecount:
		for (n = 0; n < pairs.length; n++) {
			var bits = pairs[n].split("=");
			
			// Skips cookie items which are not basket items
			
			if (bits[0].indexOf("JSESSIONID") != -1) {
				continue cookiecount;
			}

			if (bits[0].indexOf("penId") != -1) {
				penId = bits[1];
				orderContainsPenpoint = true;
				continue cookiecount;
			}

			if (bits[0].indexOf("mobilePhoneNumber") != -1) {
				mobilePhoneNumber = bits[1];
				orderContainsPenpoint = true;
				continue cookiecount;
			}

			if (bits[0].indexOf("mobileOperator") != -1) {
				mobileOperator = bits[1];
				orderContainsPenpoint = true;
				continue cookiecount;
			}

			if (bits[0].indexOf("orderContainsPen") != -1) {
				orderContainsPen = true;
				continue cookiecount;
			}

			if (bits[0].indexOf("orderHasPenmail") != -1) {
				continue cookiecount;
				penmailFlag = true;
			}

			var vals = bits[1].split("|");

			orderString += unescape(vals[2]) + " x " + unescape(vals[0]) + " (" + bits[0] + ")\r\n";
			killPenSwitch = (vals[4] == "Yes") ? "Yes" : "No";
			orderContainsPen = (vals[4] == "Yes") ? true : false;

			runningTotal += (((Number(vals[1]) * Number(vals[2])) * 100) / 100);
			weight += Number(vals[2]) * Number(vals[3]);
		}
		with (document) {
			writeln('<input type=\"hidden\" id=\"totalWeight\" name=\"totalWeight\" value=\"' + weight + '\" />');
			writeln('<input type=\"hidden\" id=\"runningTotal\" name=\"runningTotal\" value=\"' + runningTotal + '\" />');
			writeln('<input type=\"hidden\" id=\"orderString\" name=\"orderString\" value=\"' + orderString + '\" />');
		}
	}
}

// --

// Date vars for expiry times. To delete cookie set an expiry time that is already past.
var today = new Date();
var expiryLive = new Date(today.getTime() + (28 * 24 * 60 * 60 * 1000)); // 28 Days
var expiryDead = new Date(today.getTime() - (28 * 24 * 60 * 60 * 1000)); // -28 Days
// --

function killAllCookies(name, value)
/*
	Used to clear the basket automatically after an order is processed
*/
{
		document.cookie = name + "=" + value + ";path=/; expires=" + expiryDead.toGMTString();
		theCookie = document.cookie;
}

// Delete the cookie
function killCookie(name, value, isPen)
/*
	Kills cookies and reloads the page to redisplay the basket
*/
{
	if (value != null && value != "") {
		if (isPen == "Yes") {
			document.cookie = "orderContainsPen=kill;path=/; expires=" + expiryDead.toGMTString();
			theCookie = document.cookie;
			self.location.reload(true);
		}

		if (value.indexOf("Penpoint") != -1) {
			document.cookie = "penId=kill;path=/; expires=" + expiryDead.toGMTString();
			document.cookie = "mobilePhoneNumber=kill;path=/; expires=" + expiryDead.toGMTString();
			document.cookie = "mobileOperator=kill;path=/; expires=" + expiryDead.toGMTString();
			theCookie = document.cookie;
			self.location.reload(true);
		}

		if (value.indexOf("isPen") != -1) {
			//alert('this is a pen');
			document.cookie = "orderContainsPen=kill;path=/; expires=" + expiryDead.toGMTString();
			theCookie = document.cookie;
			self.location.reload(true);
		}

		document.cookie = name + "=" + value + ";path=/; expires=" + expiryDead.toGMTString();
		theCookie = document.cookie;
		self.location.reload(true);
	}
}
// --

function cookieTester(name, value)
/*
	Just a wee function to set an arbitrary cookie to test that cookies can be written
	
	USE: <a href="#" onclick="cookieTester('monkey', 'true'); return false">blah</a>
*/
{
	document.cookie = name + "=" + value + ";path=/; expires=" + expiryLive.toGMTString();
}

// Add the cookie
function setCookie(name, value, express, isPen)
{
	if (isPen == "Yes") {
		/*
			Intercepts a setCookie request where isPen is Yes
			
			Sets the cookie for the pen and sets the orderContainsPen cookie
		*/
		setCookie(name, value, false, false);
		setCookie("orderContainsPen", true, false, false);
	}

	var index = theCookie.indexOf("=");
	
	if (index == -1) {
	
		// If there are no cookies, set the cookie 
	
		if (value != null && value != "") {
			document.cookie = name + "=" + value + ";path=/; expires=" + expiryLive.toGMTString();
			theCookie = document.cookie;
			
			// express is always false so don't worry about this bit 
			if (express == false) {
				self.location.reload(true);
			} else {
				self.location.href = "/sales/checkout/";
			}
		}
	} else {
		for (n = 0; n < pairs.length; n++) {
			bits = pairs[n].split("=");
			if (bits[0] == name) {
			
				// Checks to see if it is already in the basket and adds one 
				
				inVals = bits[1].split("|");
				passVals = value.split("|");
				quantity = Number(inVals[2]) + Number(passVals[2]);
				document.cookie = name + "=" + inVals[0] + "|" + inVals[1] + "|" + quantity + ";path=/; expires=" + expiryLive.toGMTString();
				theCookie = document.cookie;
				if (express == false) {
					self.location.reload(true);
					return;
				} else {
					self.location.href = "/sales/checkout/";
					return;
				}
			}
			if (value != null && value != "") {
				
				// Set the cookie 
			
				document.cookie = name + "=" + value + ";path=/; expires=" + expiryLive.toGMTString();
				theCookie = document.cookie;
				if (express == false) {
					self.location.reload(true);
				} else {
					self.location.href = "/sales/checkout/";
				}
			}
		}
	}
}

function setThisCookie(name, value)
/*
	FIXME: what does this do?
*/
{
	var index = theCookie.indexOf("=");
	if (index == -1) {
		if (value != null && value != "") {
			document.cookie = name + "=" + value + ";path=/; expires=" + expiryLive.toGMTString();
			theCookie = document.cookie;
		}
	} else {
		for (n = 0; n < pairs.length; n++) {
			bits = pairs[n].split("=");
			if (bits[0] == name) {
				inVals = bits[1].split("|");
				passVals = value.split("|");
				quantity = Number(inVals[2]) + Number(passVals[2]);
				document.cookie = name + "=" + inVals[0] + "|" + inVals[1] + "|" + quantity + ";path=/; expires=" + expiryLive.toGMTString();
				theCookie = document.cookie;
			}
			if (value != null && value != "") {
				document.cookie = name + "=" + value + ";path=/; expires=" + expiryLive.toGMTString();
				theCookie = document.cookie;
			}
		}
	}
}

// Update the cookie
function updateCookie(name, value, weight, itemNumber)
/*
	Function to reset the item quantity with the desired number
	
	Is triggered from rows produced by displayBasket()
	
	If quantity is 0 (zero) it kills the item
*/
{
	//alert(value);
	var quantity = "quantity_" + itemNumber;
	numVal = document.getElementById(quantity);
	if (isNaN(numVal.value)) {
		alert("Please use numbers when specifying your quantity");
		self.location.href = self.location.href;
		return;
	}
	if ((numVal.value != 0) && (numVal.value < 1)) {
		numVal.value = 1;
	}
	if (numVal.value == 0) {
		killCookie(name, value);
	} else if (value != null && value != "") {
		document.cookie = name + "=" + value + numVal.value + "|" + weight + ";path=/; expires=" + expiryLive.toGMTString();
		theCookie = document.cookie;
		self.location.reload(true);
	}
}

function isCookied()
/*
	obsolete function to display basket in use notification
*/
{
	var rString = "";
	var singularPlural = ((pairs.length - 1) == 1) ? "item" : "items";
	if (theCookie.indexOf("P0") != -1) {
		rString = '<td class="basketNotice" valign=\"top\" align=\"right\" width=\"100%\">&nbsp; <a href="/sales/basket/" style=\"font-weight:bold\">You have items in your basket</a></td>';
		rString += '<td valign=\"top\" align=\"right\"><a href="/sales/basket/"><img src="/p/icon-basket.gif" alt="" width="26" height="15" border="0" /></a></td>';
		document.writeln(rString);
	} else {
		rString = '<td>&nbsp;</td><td>&nbsp;</td>';
		document.writeln(rString);
	}
}

function basketWay()
/*
	Function to diplay basket in use notification
	
	Supercedes isCookied()
	
	USE:					
	<div class="widgetContainer">
		<script type="text/javascript">basketWay();</script>
	</div> 
*/
{
	var rString = "";
	if (theCookie.indexOf("P0") != -1) {
		rString = '<a href=\"/sales/basket/\"><img src=\"/p/basket-full.gif\" width=\"180\" height=\"60\" border=\"0\" /></a>';
	} else {
		rString = '<img src=\"/p/basket-empty.gif\" width=\"180\" height=\"60\" border=\"0\" />';
	}
	document.writeln(rString);
}

// FORM VALIDATORS

function isEmpty(elementValue) 
/*
	Function to check that text field is not just control chars
	
	Called from validateTextBox()
*/
{
	for (var i = 0; i < elementValue.length; i++) {
		c = elementValue.charAt(i);
		if ((c != " ") && (c != "/n") && (c != "/t")) {
			return false;
		}
	}
	return true
}

// Function to check the validity of an <input type="text"> field or <textarea>
function validateTextBox(element) 
/*
	checks for an empty field or one with control chars
	
	calls isEmpty()
*/
{
	if ((element.value == null) || (element.value == "") || (isEmpty(element.value))) {
		return false;
	} else {
		return true;
	}
}

// Function to check if any checkbox or radio button group is unused
function validateElementGroup(groupName)
{
	var elementCounter = 0;
	var elementGroup = document.getElementsByName(groupName);
	var groupLength = elementGroup.length;

	for (var i = 0; i < groupLength; i++) {
		if (!elementGroup[i].checked) {
			elementCounter++;
		}
	}
	if (elementCounter == groupLength) {
		return false;
	} else {
		return true;
	}
}

// Function to validate Select lists
function validateSelectLists(listBox) {
	if ((listBox.options[listBox.selectedIndex].value == "") || (listBox.options[listBox.selectedIndex].value == null)) {
		return false;
	} else {
		return true;
	}
}

// Honking big validation function
function validateFormElements(formObj) {
    //alert("Validation Start");
	var numBoxes = 0;
	var numPasswords = 0;
	var numChecks = 0;
	var checkArray = new Array();
	var checkArrayCounter = 0;
	var numRadio = 0;
	var radioArray = new Array();
	var radioArrayCounter = 0;
	var numButton = 0;
	var numSubmit = 0;
	var numAreas = 0;
	var numSelects = 0;
	var elementsArray = new Array();
	var elementsArrayCounter = 0;

	var invalidElementsArray = new Array;
	var invalidElementsArrayCounter = 0;

	var optionalArray = new Object();

	if (!document.getElementById("optional")) {
		optionalArray.value = "";
	} else {
		optionalArray = document.getElementById("optional");
	}

	var msg = "";

	var inputs = formObj.getElementsByTagName("input");
	var textBoxes = formObj.getElementsByTagName("textarea");
	var selectLists = formObj.getElementsByTagName("select");

	for (var i = 0; i < inputs.length; i++) {
		var inputAttribute = inputs[i].getAttribute("type");
		if (!inputs[i].optional) {
			switch (inputAttribute) {
				case "text" :
					numBoxes++;
					if ((!validateTextBox(inputs[i])) && (optionalArray.value.indexOf(inputs[i].id) == -1)) {
						invalidElementsArray[invalidElementsArrayCounter] = inputs[i].id;
						invalidElementsArrayCounter++;
					}
					break;
				case "password" :
					numPasswords++;
					if ((!validateTextBox(inputs[i])) && (optionalArray.value.indexOf(inputs[i].id) == -1)) {
						invalidElementsArray[invalidElementsArrayCounter] = inputs[i].id;
						invalidElementsArrayCounter++;
					}
					break;
				case "checkbox" :
					numChecks++;
					var checkboxGroupName = inputs[i].getAttribute("name");
					if (checkboxGroupName != checkArray[checkArrayCounter - 1]) {
						checkArray[checkArrayCounter] = checkboxGroupName;
						checkArrayCounter++;
					}
					if (!validateElementGroup(checkboxGroupName)) {
						var checkbox = document.getElementById(inputs[i].id);
						var groupName = checkbox.getAttribute("name");
						if (optionalArray.value.indexOf(groupName) == -1) {
							if (invalidElementsArray[invalidElementsArrayCounter - 1] != checkbox.id) {
								invalidElementsArray[invalidElementsArrayCounter] = checkbox.id;
								invalidElementsArrayCounter++;
							}
						}
					}
					break;
				case "radio" :
					numRadio++;
					var radioGroupName = inputs[i].getAttribute("name");
					if (radioGroupName != radioArray[radioArrayCounter - 1]) {
						radioArray[radioArrayCounter] = radioGroupName;
						radioArrayCounter++;
					}
					if (!validateElementGroup(radioGroupName)) {
						var radioButton = document.getElementById(inputs[i].id);
						var groupName = radioButton.getAttribute("name");
						if (optionalArray.value.indexOf(groupName) == -1) {
							if (invalidElementsArray[invalidElementsArrayCounter - 1] != radioButton.id) {
								invalidElementsArray[invalidElementsArrayCounter] = radioButton.id;
								invalidElementsArrayCounter++;
							}
						}
					}
					break;
				case "button" :
					numButton++;
					break;
				case "submit" :
					numSubmit++;
					break;
			}
		}
	}

	for (var k = 0; k < textBoxes.length; k++) {
		numAreas++;
		if ((!validateTextBox(textBoxes[k])) && (optionalArray.value.indexOf(textBoxes[k].id) == -1)) {
			invalidElementsArray[invalidElementsArrayCounter] = textBoxes[k].id;
			invalidElementsArrayCounter++;
		}
	}

	for (var j = 0; j < selectLists.length; j++) {
		numSelects++;
		if ((!validateSelectLists(selectLists[j])) && (optionalArray.value.indexOf(selectLists[j].id) == -1)) {
			invalidElementsArray[invalidElementsArrayCounter] = selectLists[j].id;
			invalidElementsArrayCounter++;
		}
	}

	if (invalidElementsArray.length == 0) {
		return true;
	} else {
		msg = "There has been a problem with your form: some information was missing.\n\nPlease make changes to the highlighted errors.";
		for (var p = 0; p < invalidElementsArray.length; p++) {
			var elle = document.getElementById(invalidElementsArray[p]);
			if (elle.getAttribute("type") == "checkbox") {
                elle.className = "goRedBox";
            } else {
                elle.value += " Error";
            }
		}
		alert(msg);
		return false;
	}
}

function basicEmailCheck()
{
	var eMsg = "Invalid email addresses found, please check all email addresses";
	if (document.getElementById) {
		var inputsArray = document.getElementsByTagName("input");
		var addressCount = 0;
		var addressesArray = new Array();
		for (var i = 0; i < inputsArray.length; i++) {
			if (inputsArray[i].id.indexOf("cc") != -1) {
				addressesArray[addressCount] = inputsArray[i];
				addressCount++;
			}
		}

		for (var k = 0; k < addressesArray.length; k++) {
			 if (addressesArray[k].value.indexOf("@") != -1) {
			 	alert(eMsg);
			 	return false;
			 	break;
			 }
			 return true;
		}
	}
}

function verify(formID) {
	var f = document.getElementById(formID);

	if (f) {
		return validateFormElements(f);
	} else {
		return true;
	}
}

/*** END FORM VALIDATION ***/