/*
	JavaScript for Sysnet.co.uk
	Author: Jackie McGhee (jackie DOT mcghee AT sysnet DOT co DOT uk)
	Date Created: 29/04/2004
	Date Changed: 03/06/2004 1519
*/

function 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)
{
	var winName = "gonzo";
	var winProps = "top=16, left=16, width=300, height=300, toolbar=no, scrollbars=yes, status=yes";
	var newWin = window.open(location, winName, winProps);
	newWin.focus();
}

function spawnSite(location)
{
	var winName = "monkey";
	var newWin = window.open(location, winName);
	newWin.focus();
}

function getDirections()
{
	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://www.mapquest.com/directions/europe.adp?go=1&do=nw&un=m&2tabval=address&cl=EN&ct=EU&1v=ZIP&1tabval=address&1y=GB&1a=&1c=&1z="
		var loc2 = "&2ex=1&2y=GB&2aa=PPyJOmZCrwVplJ2%252feHpK3Y38jHmjZViN9YWjI%252bKp7I81P4cMix35VtlT2gaRGDvUDjaTfRQrfeMko5VnaZlrrt3TuDVdmL%252bF%252fJl5PrJ3Q1c%253d&2c=GLASGOW&2z=G2+3&idx=0&id=40976d4c-001cd-04d1c-400c3310&aid=40976d4c-001ce-04d1c-400c3310";
		var mapLocation = loc1 + sourcePostCodePair[0] + "+" + sourcePostCodePair[1] + loc2;
		spawnSite(mapLocation);
	}
}

// FORM HELPERS

function setupShipping()
{
	if (document.getElementById) {
		var bAddress1 = document.getElementById("address1");
		var bAddress2 = document.getElementById("address2");
		var bCity = document.getElementById("city");
		var bPostCode = document.getElementById("postCode");
		var bCountry = document.getElementById("country");
		
		var sAddress1 = document.getElementById("shippingAddress1");
		var sAddress2 = document.getElementById("shippingAddress2");
		var sCity = document.getElementById("shippingCity");
		var sPostCode = document.getElementById("shippingPostCode");
		var sCountry = document.getElementById("shippingCountry");
		
		sAddress1.value = bAddress1.value;
		sAddress2.value = bAddress2.value;
		sCity.value = bCity.value;
		sPostCode.value = bPostCode.value;
		sCountry.options.selectedIndex = bCountry.options.selectedIndex;
	}
}

function checkAgreement(formId, boxId)
{
	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()
{
	if (document.getElementById) {
		var theBox = document.getElementById("orderConfirm");
		if (!theBox.checked) {
			alert("You must confirm your order to proceed");
			return false;
		}
	}
}

// SHOPPING BASKET STUFF

var theCookie = document.cookie; // Load the cookie
var pairs = theCookie.split(";"); // Split into name=value pairs
var numberOfPenpoints = 0;

function clearBasket()
{
	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 collectAndSet()
{
	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 getPenpoint(productId, productName, weight)
{
	var locationWithQuery = "/sales/penpointinfo/?productId=" + productId + "&productName=" + productName + "&price=" + weight;
	spawn(locationWithQuery);
}

function showBasket() 

/*
	bits[0] = productId;
	bits[1] = value string
	
	vals[0] = productDesc
	vals[1] = unitPrice
	vals[2] = quantity
	vals[3] = weight
	vals[4] = isPen
*/

{
	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 killSwitch = "false";
	
	if (index == -1) {
		with (document)	{
			write('<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;
			}
			
			var vals = bits[1].split("|");
			
			orderString += unescape(vals[2]) + " x " + unescape(vals[0]) + " (" + bits[0] + ")<br />";
			killSwitch = (vals[4] == "Yes") ? "Yes" : "No";
			orderContainsPen = (vals[4] == "Yes") ? true : false;
			
			with (document) {
				write('<tr>\n');
				write('<td class=\"odd\">' + bits[0] + '<input type=\"hidden\" id=\"productId_' + n + '\" name=\"productId_' + n + '\" value=\"' + bits[0] + '\" /></td>\n');
				write('<td class=\"odddesc\">' + unescape(vals[0]) + '</td>\n');
				write('<td class=\"odd\">' + unescape(vals[1]) + '</td>\n');
				write('<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');
				write('<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');
				write('<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]) + '\', \'' + killSwitch + '\')\" /></td>\n');
				write('</tr>\n');
			}
			runningTotal += Number(vals[1]) * Number(vals[2]);
			weight += Number(vals[3]);
			numberOfRows = n;
		}
		with (document) {
			write('<tr><td colspan=\"5\" class=\"totals\"><table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" width=\"100%\">');
			write('<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');
			write('</table><input type=\"hidden\" id=\"totalWeight\" name=\"totalWeight\" value=\"' + weight + '\">');
			write('<input type=\"hidden\" name=\"numberOfRows\" id=\"numberOfRows\" value=\"' + numberOfRows + '\" />');
			write('<input type=\"hidden\" name=\"orderContainsPen\" id=\"orderContainsPen\" value=\"' + orderContainsPen + '\" />');
			write('<input type=\"hidden\" name=\"orderContainsPenpoint\" id=\"orderContainsPenpoint\" value=\"' + orderContainsPenpoint + '\">');
			write('<input type=\"hidden\" name=\"penId\" id=\"penId\" value=\"' + penId + '\"><br />');
			write('<input type=\"hidden\" name=\"mobilePhoneNumber\" id=\"mobilePhoneNumber\" value=\"' + mobilePhoneNumber + '\">');
			write('<input type=\"hidden\" name=\"mobileOperator\" id=\"mobileOperator\" value=\"' + mobileOperator + '\">');
			write('<input type=\"hidden\" name=\"orderString\" id=\"orderString\" value=\"' + orderString + '\" /></td></tr>');
		}
	}
}

function confirmOrder() 
{
	var runningTotal = 0;
	var weight = 0;
	var postage = 0;
	var index = theCookie.indexOf("=");
	if (index == -1) {
		with (document)	{
			write('<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("=");
			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;
			}

			var vals = bits[1].split("|");
			
			document.write('<tr>');
			document.write('<td>' + vals[2] + '</td>');
			document.write('<td width=\"100%\">' + vals[0] + '</td>');
			document.write('<td>@</td>');
			document.write('<td align="right"><strong>&pound;' + vals[1] + '</strong></td>');
			document.write('<td>each</td>');
			document.write('</tr>');
			runningTotal += Number(vals[1]) * Number(vals[2]);
			weight += Number(vals[3]);
		}
		var vat = (runningTotal / 100) * 17.5;
		//document.write('<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.write('<tr><td colspan=\"5\"><input type=\"hidden\" name=\"weight\" value=\"' + weight + '\"></td></tr>\n');
	}
}
// --

// 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
// --

// Delete the cookie
function killCookie(name, value, isPen) 
{	
	if (value != null && value != "") {
		if (isPen == "true") {
			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);
	}
}
// --

// Add the cookie
function setCookie(name, value, express, isPen) 
{
	if (isPen == "Yes") {
		setCookie(name, value, false, false);
		setCookie("orderContainsPen", true, false, false);
	}
	
	var index = theCookie.indexOf("=");
	if (index == -1) {
		if (value != null && value != "") {
			document.cookie = name + "=" + value + ";path=/; expires=" + expiryLive.toGMTString();
			theCookie = document.cookie;
			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) {
				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 != "") {
				document.cookie = name + "=" + value + ";path=/; expires=" + expiryLive.toGMTString();
				theCookie = document.cookie;
				if (express == false) {
					self.location.reload(true);
				} else {
					self.location.href = "/sales/checkout/";
				}
			}
		}
	}
}

// Update the cookie
function updateCookie(name, value, weight, itemNumber) 
{
	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 + "|" + (numVal.value * weight) + ";path=/; expires=" + expiryLive.toGMTString();
		theCookie = document.cookie;
		self.location.reload(true);
	}
}

function isCookied()
{
	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.write(rString);
	} else {
		rString = '<td>&nbsp;</td><td>&nbsp;</td>';
		document.write(rString);
	}
}

function basketWay() 
{
	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>';
		document.write(rString);
	} else {
		rString = '<img src=\"/p/basket-empty.gif\" width=\"180\" height=\"60\" border=\"0\" />';
		document.write(rString);
	}
}

// FORM VALIDATORS

function isEmpty(elementValue) {
	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) {
	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;
	}
}


function popWin(fileName, winName, width, height, tool, status)

		{

			var winLeft = (screen.width - width) / 2;
		
			var winTop = (screen.height - height) / 2;
		
			winProps = "height=" + height + ",width=" + width + ",top=" + winTop + ",left=" + winLeft + ",toolbar=" + tool + ",status=" + status;
		
			win = window.open(fileName, winName, winProps);
		
			if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }

		}

/*** END FORM VALIDATION ***/