//
// JSON class for generic DOM functions.
// ****************************************************************************
// Developer notes ::
// ** MDC : Initial creation.
//
var headscapeDOM = {
	//
	// Generic getElementsByClassName function.
	//
	// Developer notes ::
	// ** MDC : Courtesy of Dustin Diaz (http://www.dustindiaz.com/getelementsbyclass/).
	//
	getElementsByClassName : function(searchClass, node, tag) {
		var classElements = new Array();
		if (node == null)
			node = document;
		if (tag == null)
			tag = '*';
		var els = node.getElementsByTagName(tag);
		var elsLen = els.length;
		var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
		for (i = 0, j = 0; i < elsLen; i++) {
			if (pattern.test(els[i].className)) {
				classElements[j] = els[i];
				j++;
			}
		}
		return classElements;
	},
	// ----------------------------------------------------------------------------



	//
	// Generic addEvent function.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	addEvent : function(obj, evType, fn, useCapture) {
		if (obj.addEventListener){
			obj.addEventListener(evType, fn, useCapture);
			return true;
		} else if (obj.attachEvent){
			var r = obj.attachEvent("on"+evType, fn);
			return r;
		} else {
			//alert("Handler could not be attached");
		}
	},
	// ----------------------------------------------------------------------------



	//
	// Generic Trim function to remove leading and trailing spaces.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	trim : function(strString) {
		while (strString.substring(0,1) == ' ') {
			strString = strString.substring(1, strString.length);
		}
		while (strString.substring(strString.length-1, strString.length) == ' ') {
			strString = strString.substring(0,strString.length-1);
		}
		return strString;
	},
	// ----------------------------------------------------------------------------



	//
	// Generic read cookie function.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	getCookie : function(strName) {
		var aryCookies = document.cookie.split(";");
		var nameEQ = strName + "=";
		for(var i=0; i < aryCookies.length; i++) {
			aryCookies[i] = this.trim(aryCookies[i]);
			if (aryCookies[i].indexOf(nameEQ) == 0) return aryCookies[i].substring(nameEQ.length, aryCookies[i].length);
		}
		return null;
	},
	// ----------------------------------------------------------------------------



	//
	// Reads a sub cookie (URL Encoded) from a cookie.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	getSubCookie : function(strName, strSubName) {
		var strReturnValue = null;
		var strFullCookie = this.getCookie(strName);
		if (strFullCookie) {
			var arySubCookies = strFullCookie.split("&");
			var nameEQ = strSubName + "=";
			for (var i=0; i < arySubCookies.length; i++) {
				arySubCookies[i] = this.trim(arySubCookies[i]);
				if (arySubCookies[i].indexOf(nameEQ) == 0) {
					strReturnValue = arySubCookies[i].substring(nameEQ.length, arySubCookies[i].length);
					break;
				}
			}
		}
		return strReturnValue;
	},
	// ----------------------------------------------------------------------------



	//
	// Generic write cookie function.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	setCookie : function(strName, strValue, intExpiryDays) {
		var aryCookies = document.cookie.split(";");
		var nameEQ = strName + "=";
		var strNewCookieFull = "";
		var intThisCookie = -1;
		var strExpires = "";

		if (intExpiryDays) {
			var date = new Date();
			date.setTime(date.getTime()+(intExpiryDays*24*60*60*1000));
			strExpires = "; expires="+date.toGMTString();
		}

		strNewCookieFull = nameEQ + strValue + strExpires + "; path=/";

		for(var i=0; i < aryCookies.length; i++) {
			aryCookies[i] = this.trim(aryCookies[i]);
			if (aryCookies[i].indexOf(nameEQ) == 0) {
				// We have a match
				intThisCookie = i;
				aryCookies[i] = strNewCookieFull;
				break;
			}
		}

		// Check if we need to add the cookie
		if (intThisCookie == -1) {
			aryCookies.push(strNewCookieFull);
			intThisCookie = aryCookies.length - 1;
		}

		// Write this cookie back - not the full cookie list as this is not what JS expects
		document.cookie = aryCookies[intThisCookie];
	},
	// ----------------------------------------------------------------------------



	//
	// Updates a sub cookie.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	setSubCookie : function(strCookieName, strSubCookieName, strValue) {
		var strFullCookie = this.getCookie(strCookieName);
		if (strFullCookie) {
			var arySubCookies = strFullCookie.split("&");
			var nameEQ = strSubCookieName + "=";
			var strNewCookieFull = nameEQ + strValue;
			var intThisSubCookie = -1;

			for(var i=0; i < arySubCookies.length; i++) {
				arySubCookies[i] = this.trim(arySubCookies[i]);
				if (arySubCookies[i].indexOf(nameEQ) == 0) {
					// We have a match
					intThisSubCookie = i;
					break;
				}
			}

			// Check if we need to add or update the cookie
			if (intThisSubCookie == -1) {
				arySubCookies.push(strNewCookieFull)
			} else {
				// Update our found cookie
				arySubCookies[intThisSubCookie] = strNewCookieFull;
			}

			// Write the full cookie back
			this.setCookie(strCookieName, arySubCookies.join("&"), 365);
		}
	},
	// ----------------------------------------------------------------------------

	isInteger : function(sInteger) {
		var deccount = 0;
		var isInt = true;
		var inputStr;
		inputStr = sInteger.toString(); // in case sInteger is not a string
		for (var i = 0; i < inputStr.length; i++) {
			var oneChar = inputStr.charAt(i);
			if (oneChar < "0" || oneChar > "9" || oneChar == ".") {
				isInt = false;
				i = inputStr.length;
			}
		}
		return isInt;
	},
	// ----------------------------------------------------------------------------



	externalLinks : function() {
		if (document.getElementsByTagName) {
			var links = this.getElementsByClassName("externalLink");
			for (var i=0; i < links.length; i++) {
				if (links[i].title == "") {
					links[i].title = "(new window)";
				} else {
					links[i].title = links[i].title + " (new window)";
				}
				links[i].onclick = function(e) {
					if (!e) e=window.event;
					if (e.shiftKey || e.ctrlKey || e.altKey) return;
					window.open(this.href);
					return false;
				}
			}
		}
	}
}
// ****************************************************************************




//
// Generic Hash table implementation.
// ****************************************************************************
// Developer notes ::
// ** MDC : Initial creation.
//
function HashTable() {
	this.length = 0;
	this.items = new Array();
	for (var i = 0; i < arguments.length; i += 2) {
		if (typeof(arguments[i + 1]) != 'undefined') {
			this.items[arguments[i]] = arguments[i + 1];
			this.length++;
		}
	}

	this.removeItem = function(in_key) {
		var tmp_value;
		if (typeof(this.items[in_key]) != 'undefined') {
			this.length--;
			var tmp_value = this.items[in_key];
			delete this.items[in_key];
		}

		return tmp_value;
	}

	this.getItem = function(in_key) {
		return this.items[in_key];
	}

	this.setItem = function(in_key, in_value) {
		if (typeof(in_value) != 'undefined') {
			if (typeof(this.items[in_key]) == 'undefined') {
				this.length++;
			}

			this.items[in_key] = in_value;
		}

		return in_value;
	}

	this.hasItem = function(in_key) {
		return typeof(this.items[in_key]) != 'undefined';
	}
}
// ****************************************************************************




//
// JSON class for WFF basket product. Used to handle display updates.
// ****************************************************************************
// Developer notes ::
// ** MDC : Initial creation.
//
var wffBasketProduct = {
	cINBASKETCLASS : "inBasket",
	cINBASKETDETAILCLASS : "inBasketDetail",
	cADDCLASS : "prodAdd",
	cUPDATECLASS : "changeQuan",
	cADDTXT : "Add to basket",
	cUPDATETXT : "Change quantity",
	cPRODADDEDTITLE : "This product has been added to your shopping basket",

	intPid : -1,
	intQty : 1,
	blnFirstTimeAdded : false,
	mnyTotal : "0.00",
	mnyLineTotal : "0.00",
	mnyMinOrderValue : "9999.00",
	strFranchisePhone : "",
	strProdClass : "",


	//
	// ***DEPENDS ON PROTOTYPE***
	// Redraw all occurrences of the product (class).
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	redrawProduct : function() {
		var aryProds = null;
		var aryHPProds = null;
		var arySEOProds = null;
		var eltProdDetails = null;

		if (location.href.indexOf("all_products.asp", 1) != -1) {
			arySEOProds = document.getElementsByTagName("tr");
		}
		else if (((location.href.indexOf("/frozen-ready-meals/", 1) != -1) && (location.href.indexOf("-ready-meals.asp", 1) == -1)) || (location.href.indexOf("product_details.asp", 1) != -1)) {
			eltProdDetails = document.getElementById("adding");

			// Pick up the products in the main body of the page
			aryProds = headscapeDOM.getElementsByClassName(this.strProdClass, $("prodList"), "li");
		}
		else {
			// Pick up the products in the main body of the page
			aryProds = headscapeDOM.getElementsByClassName(this.strProdClass, null, "li");

			// Pick up products in hp promo tables
			aryHPProds = headscapeDOM.getElementsByClassName(this.strProdClass, $("contentContainer"), "tr");
		}


		// Assume we are not on basket.asp by default
		var blnIsBasketPage = false;

		// We need to reverse the display if the user has set the qty to 0
		if (this.intQty == 0) {
			// For each instance of the product on this page, update the display
			if (aryProds != null) {
				for (var i=0; i < aryProds.length; i++) {
					// Check if this item is in the basket.asp main list
					var eleRowPrice = null;
					var aryChildDivs = aryProds[i].getElementsByTagName("div");
					for (var z=0; z < aryChildDivs.length; z++) {
						if (Element.hasClassName(aryChildDivs[z], "rowTotal")) {
							eleRowPrice = aryChildDivs[z];
							break;
						}
					}

					// Check child node for price
					if (eleRowPrice) {
						blnIsBasketPage = true;

						// Update the following rows' alt colouring
						for (var cell = aryProds[i].nextSibling; cell != null; cell = cell.nextSibling) {
							if (cell.nodeType == 1) {
								if (Element.hasClassName(cell, "alt")) {
									Element.removeClassName(cell, "alt");
								} else {
									Element.addClassName(cell, "alt");
								}
							}
						}

						// Delete this li
						if (aryProds[i].parentNode) aryProds[i].parentNode.removeChild(aryProds[i]);

					} else {
						// Change li class
						Element.removeClassName(aryProds[i], this.cINBASKETCLASS)

						// Remove title from product title H3
						var aryProdTitles = aryProds[i].getElementsByTagName("h3");
						if (aryProdTitles.length == 1) {
							aryProdTitles[0].title = "";
						}

						// Change value in qty input and rename submit button
						var aryInputs = aryProds[i].getElementsByTagName("input");
						for (var x=0; x < aryInputs.length; x++) {
							if (aryInputs[x].name == "qty") aryInputs[x].value = "";
							if ((aryInputs[x].name == "add") || (aryInputs[x].name == "add" + this.intPid)) {
								Element.removeClassName(aryInputs[x].parentNode, this.cUPDATECLASS);
								Element.addClassName(aryInputs[x].parentNode, this.cADDCLASS);
								aryInputs[x].value = this.cADDTXT;
								aryInputs[x].blur();
							}
						}
					}
				}
			}


			// Update the homepage promo product(s) too if they exist
			if (aryHPProds != null) {
				for (i=0; i < aryHPProds.length; i++) {
					// Get a handle on the product title
					var aryCells = aryHPProds[i].getElementsByTagName("td");
					var eleTitleCell = aryCells[0];
					var eleTitleSpan = eleTitleCell.getElementsByTagName("span")[0];
					var eleQtyCell = aryCells[aryCells.length-1];

					if (eleTitleCell && eleTitleSpan) {
						var strProdTitle = eleTitleSpan.innerHTML;
						Element.update(eleTitleCell, strProdTitle);
					}

					if (eleQtyCell) {
						// Update the input box number
						var aryInputs = eleQtyCell.getElementsByTagName("input");
						aryInputs[0].value = "";

						// Update the submit button text
						aryInputs[1].value = this.cADDTXT;
					}
				}
			}


			// SEO
			if (arySEOProds != null) {
				if (document.getElementById("pr" + this.intPid)) {

					document.getElementById("pr" + this.intPid).className = "prod pr" + this.intPid;
					//document.getElementById("pr" + this.intPid).setAttribute("class", "prod pr" + this.intPid);

					//alert(document.getElementById("pr" + this.intPid).getAttribute('class'));


					// Change value in qty input and rename submit button
					var aryInputs = document.getElementById("pr" + this.intPid).getElementsByTagName("input");
					for (var x=0; x < aryInputs.length; x++) {
						if (aryInputs[x].name == "qty") aryInputs[x].value = "";
						if ((aryInputs[x].name == "add") || (aryInputs[x].name == "add" + this.intPid)) {
							aryInputs[x].value = "Add to basket";
							aryInputs[x].blur();
						}
					}


				}

				for (i=0; i < arySEOProds.length; i++) {

					if (this.intPid == arySEOProds[i].getAttribute("title")) {

						Element.removeClassName(arySEOProds[i], this.cINBASKETCLASS);

						var eltA = arySEOProds[i].childNodes[0].childNodes[0];
						var eltInputAdd = arySEOProds[i].childNodes[2].childNodes[0].childNodes[1].childNodes[0];
						var eltInputQty = arySEOProds[i].childNodes[2].childNodes[0].childNodes[0].childNodes[1];

						eltA.title = '';
						eltInputAdd.value = 'Add to basket';
						eltInputQty.value = '';

					}
				}

			}


			// Product details
			if (eltProdDetails != null) {
				var eltInputAdd = eltProdDetails.childNodes[2].childNodes[0];
				var eltInputQty = eltProdDetails.childNodes[1].childNodes[0].childNodes[1];

				eltInputQty.value = ''
				eltInputAdd.value = this.cADDTXT;

				document.getElementById("productSummary").className = "";

				document.getElementById("productSummary").removeAttribute("class");
			}


		} else {
			// Product has been added/updated
			if (aryProds != null) {
				for (var i=0; i < aryProds.length; i++) {
					// Check if this is in the main basket list
					var eleRowPrice = null;
					var aryChildDivs = aryProds[i].getElementsByTagName("div");
					for (var z=0; z < aryChildDivs.length; z++) {

						if (Element.hasClassName(aryChildDivs[z], "rowTotal")) {
							eleRowPrice = aryChildDivs[z];
							break;
						}
					}

					// Check child node for price - if it exists we are in the basket
					if (!eleRowPrice) {
						// Change li class
						if (!Element.hasClassName(aryProds[i], this.cINBASKETCLASS)) {
							Element.addClassName(aryProds[i], this.cINBASKETCLASS)
						}

						// Add title to product title H3
						var aryProdTitles = aryProds[i].getElementsByTagName("h3");
						if (aryProdTitles.length == 1) {
							aryProdTitles[0].title = this.cPRODADDEDTITLE;
						}

						// If we have added a new product from a recc/chef's choice etc then add it to the list
						if (this.blnFirstTimeAdded) {
							// Check if we are on basket.asp
							if (location.pathname == "/basket.asp") {
								
								// Duplicate this product li for use in the basket list
								var eleNewProdClone = aryProds[i].cloneNode(true);


								// Change the ID and remove extraneous classes
								eleNewProdClone.removeAttribute("id");
								eleNewProdClone.setAttribute("id", "basket" + this.strProdClass);
								Element.removeClassName(eleNewProdClone, "inBasket");
								Element.removeClassName(eleNewProdClone, "alt");


								// Change "add to basket" to "change quantity"
								var eleSubmit = headscapeDOM.getElementsByClassName(this.cADDCLASS, eleNewProdClone, "div")[0];
								if (eleSubmit) {
									Element.removeClassName(eleSubmit, this.cADDCLASS);
									Element.addClassName(eleSubmit, this.cUPDATECLASS);

									var eleSubmitButton = eleSubmit.childNodes[0];
									eleSubmitButton.value = this.cUPDATETXT;
								}


								// Change the image size
								var eleProdImg = eleNewProdClone.firstChild.firstChild.firstChild.firstChild;
								eleProdImg.src = eleProdImg.src.replace("&t=120x109", "&t=59x54");
								eleProdImg.setAttribute("width", "59");
								eleProdImg.setAttribute("height", "54");


								// Write the quantity to the input box
								var eleQty = headscapeDOM.getElementsByClassName("qtyInput", eleNewProdClone, "input")[0];
								if (eleQty) {
									eleQty.value = this.intQty;
								}


								// Create the row total element and add it to the HTML
								var eleRowTotal = document.createElement("div");
								Element.addClassName(eleRowTotal, "rowTotal");
								Element.update(eleRowTotal, "Total price paid: <strong>£" + this.mnyLineTotal + "</strong>");
								var eleProdInfo = headscapeDOM.getElementsByClassName("prodInfo", eleNewProdClone, "div")[0];
								var eleProdDiet = headscapeDOM.getElementsByClassName("prodDiet", eleNewProdClone, "div")[0];
								if (eleProdInfo && eleProdDiet) {
									eleProdInfo.insertBefore(eleRowTotal, eleProdDiet);
								}


								// Create the remove link
								var eleRemove = document.createElement("a");
								Element.addClassName(eleRemove, "remove");
								eleRemove.setAttribute("href", "?pid=" + this.intPid + "&qty=0&_basket=1");
								eleRemove.setAttribute("title", "Remove this item from the basket");
								Element.update(eleRemove, "Remove");
								var eleProdDesc = headscapeDOM.getElementsByClassName("prodDesc", eleNewProdClone, "div")[0];
								if (eleProdInfo && eleProdDesc) {
									eleProdInfo.insertBefore(eleRemove, eleProdDesc);
								}


								// Write it to the basket list
								var eleBasketList = $("prodList");
								eleBasketList.appendChild(eleNewProdClone);

								// Set the row colour (class=alt) of our new row

								// Add the event watcher
								wffBasket.watch();
							}
						}
					} else {
						blnIsBasketPage = true;

						// Update row total
						Element.update(eleRowPrice, "Total price paid: <strong>£" + this.mnyLineTotal + "</strong>");
					}

					var aryInputs = aryProds[i].getElementsByTagName("input");
					for (var x=0; x < aryInputs.length; x++) {
						// Change value in qty input
						if (aryInputs[x].name == "qty") aryInputs[x].value = this.intQty;

						// Change submit button text and class
						if ((aryInputs[x].name == "add") || (aryInputs[x].name == "add" + this.intPid)) {
							Element.removeClassName(aryInputs[x].parentNode, this.cADDCLASS);
							Element.addClassName(aryInputs[x].parentNode, this.cUPDATECLASS);
							aryInputs[x].value = this.cUPDATETXT;
							aryInputs[x].blur();
						}
					}
				}
			}


			// Update the homepage promo product(s) too if they exist
			if (aryHPProds != null) {
				for (i=0; i < aryHPProds.length; i++) {
					// Get a handle on the product title and quantity cells
					var aryCells = aryHPProds[i].getElementsByTagName("td");
					var eleTitleCell = aryCells[0];
					var eleQtyCell = aryCells[aryCells.length-1];

					if (eleTitleCell) {
						// Make sure the span isn't already there
						if (eleTitleCell.getElementsByTagName("span").length == 0) {
							var strProdTitle = eleTitleCell.innerHTML;
							Element.update(eleTitleCell, "<span class=\"inBasketTitle\" title=\"" + this.cPRODADDEDTITLE + "\">" + strProdTitle + "</span>");
						}
					}

					if (eleQtyCell) {
						// Update the input box number
						var aryInputs = eleQtyCell.getElementsByTagName("input");
						aryInputs[0].value = this.intQty;

						// Update the submit button text
						aryInputs[1].value = this.cUPDATETXT;
					}
				}
			}


			// SEO
			if (arySEOProds != null) {

				if (document.getElementById("pr" + this.intPid)) {
					document.getElementById("pr" + this.intPid).className = "prod pr" + this.intPid + " inBasket";

					// Change value in qty input and rename submit button
					var aryInputs = document.getElementById("pr" + this.intPid).getElementsByTagName("input");
					for (var x=0; x < aryInputs.length; x++) {
						if (aryInputs[x].name == "qty") aryInputs[x].value = this.intQty;
						if ((aryInputs[x].name == "add") || (aryInputs[x].name == "add" + this.intPid)) {
							aryInputs[x].value = "Change quantity";
							aryInputs[x].blur();
						}
					}

				}

				for (i=0; i < arySEOProds.length; i++) {

					if (this.intPid == arySEOProds[i].getAttribute("title")) {

						arySEOProds[i].className = "inBasket";

						var eltA = arySEOProds[i].childNodes[0].childNodes[0];
						var eltInputAdd = arySEOProds[i].childNodes[2].childNodes[0].childNodes[1].childNodes[0];
						var eltInputQty = arySEOProds[i].childNodes[2].childNodes[0].childNodes[0].childNodes[1];

						eltA.removeAttribute("title");
						Element.addClassName(eltA, "This product has been added to your shopping basket");
						eltInputAdd.value = 'Change Quantity';
						eltInputQty.value = this.intQty;

					}
				}

			}


			// Product details
			if (eltProdDetails != null) {
				var eltInputAdd = eltProdDetails.childNodes[2].childNodes[0];
				var eltInputQty = eltProdDetails.childNodes[1].childNodes[0].childNodes[1];

				eltInputQty.value = this.intQty
				eltInputAdd.value = this.cUPDATETXT;

				Element.addClassName(document.getElementById("productSummary"), this.cINBASKETDETAILCLASS);

			}

		}


		// Either way, if we are on the basket page we need to change the display of other elements too
		var eleGrandTotal = $("grdTotal");
		if (eleGrandTotal) {
			// Get handles on any existing elements
			var aryCheckoutLinks = headscapeDOM.getElementsByClassName("checkout", $("contentContainer"), "div");
			var aryWarnings = headscapeDOM.getElementsByClassName("warningDialog", $("contentContainer"), "div");
			// Check if the basket is empty
			if ((+this.mnyTotal) == 0) {
				// Hide the warning dialog
				for (var z=0; z < aryWarnings.length; z++) {
					if (aryWarnings[z].parentNode) aryWarnings[z].parentNode.removeChild(aryWarnings[z]);
				}

				// Remove the checkout link
				for (var z=0; z < aryCheckoutLinks.length; z++) {
					if (aryCheckoutLinks[z].parentNode) aryCheckoutLinks[z].parentNode.removeChild(aryCheckoutLinks[z]);
				}

				// Hide the grand total
				var eleGrandTotal = $("grdTotal");
				if (eleGrandTotal) eleGrandTotal.parentNode.removeChild(eleGrandTotal);

				// Change the WYSIWYG message to say the basket is empty
				var eleWYSIWYG = $("wysiwygMain").lastChild;
				if (eleWYSIWYG) {
					Element.update(eleWYSIWYG, "<p><strong>Your shopping basket is currently empty.</strong> To add items to your basket select a method below:</p><ul><li>Select a category from the <a href=\"#pNavigation\">main menu</a></li><li><a href=\"#search\">Search for a meal</a> using the search box provided</li><li>Select an item from your <a href=\"favourites.asp\">favourites list</a></li><li>Reorder a previous purchase by visiting <a href=\"account_details.asp\">your account section</a></li><li>Call your local franchisee on: <span class=\"tel\">" + this.strFranchisePhone + "</span></li></ul>");
				}
			} else {
				// Update the grand total
				Element.update(eleGrandTotal, "<p>Total price to pay <em>(free delivery)</em>: £" + this.mnyTotal + "</p>");

				// Add/remove checkout link or min price message
				if ((+this.mnyTotal) >= (+this.mnyMinOrderValue)) {
					// Show checkout link if it's not already there
					if (aryCheckoutLinks.length == 0) {
						var eleNewWarning = document.createElement("div");
						Element.addClassName(eleNewWarning, "checkout");
						Element.update(eleNewWarning, "<div class=\"corner1\"><div class=\"corner2\"><div class=\"corner3\"><div class=\"checkoutInst\"><strong>Ready to pay?</strong><p>Then click the button:</p></div><p class=\"checkoutButton\"><a href=\"https://" + location.host + "/user_login.asp\">Proceed to checkout</a></p></div></div></div>");

						var eleProdList = $("accountMan").nextSibling;
						if (eleProdList) eleProdList.parentNode.insertBefore(eleNewWarning, eleProdList);
					}

					// Hide the warning dialog
					for (var z=0; z < aryWarnings.length; z++) {
						if (aryWarnings[z].parentNode) aryWarnings[z].parentNode.removeChild(aryWarnings[z]);
					}
				} else {
					// Value is too low, show warning dialog if it's not already there
					if (aryWarnings.length == 0) {
						var eleNewWarning = document.createElement("div");
						Element.addClassName(eleNewWarning, "warningDialog");
						Element.update(eleNewWarning, "<div class=\"warning1\"><div class=\"warning2\"><h3>Minimum order not met</h3><p>Your <strong>minimum order value of £" + this.mnyMinOrderValue + "</strong> has not been reached. Please continue shopping.</p><p class=\"buttonY\"><a href=\"index.asp\">Continue shopping</a></p></div></div>");

						var eleProdList = $("prodList");
						eleProdList.parentNode.insertBefore(eleNewWarning, eleProdList);

						// Remove the checkout link
						for (var z=0; z < aryCheckoutLinks.length; z++) {
							if (aryCheckoutLinks[z].parentNode) aryCheckoutLinks[z].parentNode.removeChild(aryCheckoutLinks[z]);
						}
					}
				}
			}
		}
	}
	// ----------------------------------------------------------------------------
}
// ****************************************************************************






//
// JSON class for WFF Basket.
// ****************************************************************************
// Developer notes ::
// ** MDC : Initial creation
//
var wffBasket = {
	//
	// Get all the prod <form>s and attach new onSubmit event
	// to them.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	watch : function() {
	    var validNav  = navigator.appVersion.indexOf('MSIE') >0 ? (parseFloat(navigator.appVersion.substring(navigator.appVersion.indexOf('MSIE')+4,navigator.appVersion.indexOf(';',navigator.appVersion.indexOf('MSIE')))) >5.5 ? true : false)  : true;
		if ((document.getElementById) && (validNav)) {
			if (document.getElementById("prodList") || document.getElementById("productSummary") || document.getElementById("allProducts")) {
				var aryAddForms = headscapeDOM.getElementsByClassName("prodForm", document.getElementById("contentContainer"), "form");

				for (var i=0; i < aryAddForms.length; i++) {
					// Check the form action is not #postcodeEntry - this would mean we are not logged in
					if (aryAddForms[i].getAttribute("action") != "#postcodeEntry") {
						// Add an event observer to this form onsubmit
						headscapeDOM.addEvent(aryAddForms[i], 'submit', this.add, false);
					}
				}
			}
		}
	},
	// ----------------------------------------------------------------------------


	//
	// ***DEPENDS ON PROTOTYPE***
	// If the postcode entry box is displayed flash it orange.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	flashPostcode : function() {
		if (document.getElementById) {
			var eleMiniBasket = $("basket");
			var elePostcodeEntry = $("postcodeEntry");
			if (elePostcodeEntry) {
				// Turn the basket orange
				Element.addClassName(eleMiniBasket, "active");

				// Wait a bit then turn it back to green
				setTimeout("wffBasket.flashPostcodeOff()", 1000)
			}
		}
	},
	// ----------------------------------------------------------------------------


	flashPostcodeOff : function() {
		if (document.getElementById) {
			var eleMiniBasket = $("basket");
			if (eleMiniBasket) {
				// Turn it green again
				Element.removeClassName(eleMiniBasket, "active");
			}
		}
	},


	//
	// ***DEPENDS ON PROTOTYPE***
	// Add/update a product or menu pack in the basket. Uses an Ajax call.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	add : function(e) {
		var frmAddForm;
		var intBid = 0;
		var intPid = 0;
		var intMid = 0;
		var strIP = "";
		var strZip = "";
		var strPage = "";

		// Get a handle on the form that was submitted
		if (window.event) {
			frmAddForm = window.event.srcElement;
		}
		else {
			if (e.target) {
				frmAddForm = e.target;
			}
			else {
				//fix on the homepage for Firefox
				frmAddForm = e.currentTarget;
			}
		}

		if (frmAddForm) {
			intBid = frmAddForm.bid.value;
			intPid = frmAddForm.pid.value;
			wffBasketProduct.intPid = intPid;
			intMid = frmAddForm.mid.value;
			intSid = frmAddForm.sid.value;
			intFid = frmAddForm.fid.value;
			wffBasketProduct.intQty = frmAddForm.qty.value;
			strIP = frmAddForm.ip.value;
			strZip = frmAddForm.zip.value;
			strPage = frmAddForm._page.value;

			// Ensure valid quantity
			if (!headscapeDOM.isInteger(wffBasketProduct.intQty)) wffBasketProduct.intQty = 1;
			if (wffBasketProduct.intQty.length == 0) wffBasketProduct.intQty = 1;
			if (isNaN(wffBasketProduct.intQty)) wffBasketProduct.intQty = 1;
			if (wffBasketProduct.intQty > 99) wffBasketProduct.intQty = 99;

			// Store the class name for later use
			var eleFormParentNode = frmAddForm.parentNode; // that's the <li> node
			if (eleFormParentNode.parentNode.className == "pr" + intPid) {
				eleFormParentNode = eleFormParentNode.parentNode;
			}
			
			//SG on 20070713:(fix added to change the logic)
			//qty = 0 and item in basket = > remove the item
			//qty = 0 and item not in basket = > qty = 1
			if (eleFormParentNode.className.indexOf("inBasket")) {
				if (wffBasketProduct.intQty == 0) {
					//nothing, keep the qty to 0
				}
			}
			else {
				if (wffBasketProduct.intQty == 0) {
					wffBasketProduct.intQty = 1;
				}
			}
				



			if (eleFormParentNode.getAttribute("id")) {
				wffBasketProduct.strProdClass = headscapeDOM.trim(eleFormParentNode.className.replace(" alt", "").replace("prod ", "").replace(" inBasket", ""));

			}

			// Check if this product is new to the basket
			//SG (15/02/2007): fix for the home page which has different "ADD" id value
			if (frmAddForm.add) {
				var strSubmitText = frmAddForm.add.value;
			}
			else {
				eval("var strSubmitText = frmAddForm.add" + intPid + ".value");
			}

			if (strSubmitText == "Add to basket") {
				wffBasketProduct.blnFirstTimeAdded = true;
			} else {
				wffBasketProduct.blnFirstTimeAdded = false;
			}



			// Flash the basket while we do the Ajax to show something is happening
			Element.addClassName($("basket"), "active");

			// Call the API using XHT (PROTOTYPE)
			var strURL = location.protocol + "//" + location.host + "/api/basket.api.asp";
			var strParams = "action=add&bid=" + intBid + "&pid=" + intPid + "&mid=" + intMid + "&sid=" + intSid + "&fid=" + intFid + "&qty=" + wffBasketProduct.intQty + "&ip=" + strIP + "&zip=" + strZip + "&_page=" + strPage;
			var objAjax = new Ajax.Request(strURL, {method: "post", parameters: strParams, onComplete: wffBasket.redraw});

			// Stop the form submitting
			if (window.event) {
				window.event.cancelBubble = true;
				window.event.returnValue = false;
			}
			if (e && e.stopPropagation && e.preventDefault) {
				e.stopPropagation();
				e.preventDefault();
			}

			return false;
		}
	},
	// ----------------------------------------------------------------------------


	//
	// ***DEPENDS ON PROTOTYPE***
	// Redraw the basket based on the Ajax call. Cannot be called directly.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	redraw : function(objResponse) {
		if (document.getElementById) {
			// Collect the JSON object from the API call
			eval("var wffAPIResponse = " + objResponse.responseText);

			// For some reason (content encoding?) the £ sign comes back as a weird character which we need to strip
			wffAPIResponse.mnyTotal = wffAPIResponse.mnyTotal.substring(1, wffAPIResponse.mnyTotal.length).replace(",", "");
			wffAPIResponse.mnyLineTotal = wffAPIResponse.mnyLineTotal.substring(1, wffAPIResponse.mnyLineTotal.length);
			wffAPIResponse.mnyMinOrderValue = wffAPIResponse.mnyMinOrderValue.substring(1, wffAPIResponse.mnyMinOrderValue.length);

			// Remember the totals for later use
			wffBasketProduct.mnyLineTotal = wffAPIResponse.mnyLineTotal;
			wffBasketProduct.mnyTotal = wffAPIResponse.mnyTotal;
			wffBasketProduct.mnyMinOrderValue = wffAPIResponse.mnyMinOrderValue;
			wffBasketProduct.strFranchisePhone = wffAPIResponse.strFranchisePhone;
			wffBasketProduct.intQty = wffAPIResponse.intLineQty;

			// Get a handle on divs we need to update
			var eleBasket = $("basket");

			// IE does not count text as DOM element but FF does! So for IE it's 1-0 and FF is 3-1
			if (eleBasket.childNodes.length == 2) {
				var eleBasketText = eleBasket.childNodes[1].childNodes[0]; // Get the first LI of the list
				//var eleBasketCheckoutLink = eleBasket.childNodes[1].childNodes[2].childNodes[0];
			} else {
				var eleBasketText = eleBasket.childNodes[3].childNodes[1]; // Get the first LI of the list
				//var eleBasketCheckoutLink = eleBasket.childNodes[3].childNodes[5].childNodes[0];
			}
			//SG (15/02/2007): fix for safari, get the checkout link by id instead of getting it by browsing the dom tree
			//...and add an id in the _basket.asp file
			var eleBasketCheckoutLink = $("eleBasketCheckoutLink");

			// Rewrite the descriptive text - not very "DOM" but so much simpler!
			var strItems = "items";
			if (wffAPIResponse.intProdCount == 1) strItems = "item"
			Element.update(eleBasketText, "<strong>" + wffAPIResponse.intProdCount + "</strong> " + strItems + " [<strong>£" + wffAPIResponse.mnyTotal + "</strong>] in your basket");

			// Change checkout href if min order value is reached/breached
			var dblTotal = (+wffAPIResponse.mnyTotal); // Cast as number in the fastest way possible
			var dblMin = (+wffAPIResponse.mnyMinOrderValue);
			if (dblTotal < dblMin) {
				eleBasketCheckoutLink.href = "/basket.asp"
			} else {
				eleBasketCheckoutLink.href = "https://" + location.host + "/user_login.asp"
			}

			// Update the basket cookie (ID and count) from encrypted API return values
			headscapeDOM.setSubCookie("WFF", "B", wffAPIResponse.strBidEnc);
			headscapeDOM.setSubCookie("WFF", "I", wffAPIResponse.strProdCountEnc);

			// Update all hidden basket ID fields on this page with returned ID
			var aryBasketIDFields = headscapeDOM.getElementsByClassName("bid", null, "input");
			for (var i=0; i < aryBasketIDFields.length; i++) {
				aryBasketIDFields[i].value = wffAPIResponse.intBid;
			}

//alert('1. Not bad');

			// Update the display of the prod/MP. The prod could display more than once on this page.
			wffBasketProduct.redrawProduct();

//alert('2. Not bad');

			// Un-flash the basket
			setTimeout("wffBasket.flashOff()", 1000)
		}
	},
	// ----------------------------------------------------------------------------

	flashOff : function() {
		Element.removeClassName($("basket"), "active");
	}
}
// ****************************************************************************

















//
// JSON class for WFF FAQ.
// Deals with the expanding and collapsing of FAQs
// ****************************************************************************
// Developer notes ::
// ** SG : Initial creation
//
var wffFAQ = {
	//
	// This does the initial hiding of the answers
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	hideanswers : function() {
		if (document.getElementById) {
			var aryFaqAnswers = headscapeDOM.getElementsByClassName("lAnswer", document.getElementById("rsList"), "div");
			for (var i=0; i < aryFaqAnswers.length; i++) {
				aryFaqAnswers[i].style.display = 'none';
			}
		}
	},
	// ----------------------------------------------------------------------------


	//
	// Hide or show the given FAQ.
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	expandOrCollapse : function(e) {
		if (window.event) {
			var whichlink = window.event.srcElement;
		}
		else
		{
			var whichlink = e.target;
		}

		while (whichlink.nodeName.toLowerCase() != 'a' && whichlink.nodeName.toLowerCase() != 'body') {
			whichlink = whichlink.parentNode;
		}

		var findanswer = whichlink.parentNode.getElementsByTagName("div");
		for (var i=0; i < findanswer.length; i++) {
			if (findanswer[i].className.match("lAnswer"))  {
				if (findanswer[i].style.display.match("none"))  {
					findanswer[i].style.display = 'block';
				}
				else  {
					findanswer[i].style.display = 'none';
				}
			}
		}

		if (window.event) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		if (e && e.stopPropagation && e.preventDefault) {
			e.stopPropagation();
			e.preventDefault();
		}

	},
	// ----------------------------------------------------------------------------


	//
	// Call the handler function when an FAQ is clicked.
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	watch : function(e) {
		var blnReturnValue = false;
		if (document.getElementById) {
			var aryFaqQuestions = headscapeDOM.getElementsByClassName("lQuestion", document.getElementById("rsList"), "a");
			for (var i=0; i < aryFaqQuestions.length; i++) {
				headscapeDOM.addEvent(aryFaqQuestions[i], 'click', wffFAQ.expandOrCollapse, false);
				blnReturnValue = true;
			}
		}
		return blnReturnValue;
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************




//
// JSON class for WFF Menu Pack.
// Deals with the expanding and collapsing of Menu Packs
// ****************************************************************************
// Developer notes ::
// ** SG : Initial creation
//
var wffMenuPack = {
	//
	// This does the initial hiding of the answers
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	hide : function() {
		if (document.getElementById) {
			var aryMenuPackDetails = headscapeDOM.getElementsByClassName("prodBox", document.getElementById("prodList"), "div");
			for (var i=0; i < aryMenuPackDetails.length; i++) {
				aryMenuPackDetails[i].style.display = 'none';
			}
		}
	},
	// ----------------------------------------------------------------------------


	//
	// This controls what happens when a click occurs
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	expandOrCollapse : function (e) {
		if (window.event) {
			var whichlink = window.event.srcElement;
		}
		else
		{
			var whichlink = e.target;
		}

		while (whichlink.nodeName.toLowerCase() != 'a' && whichlink.nodeName.toLowerCase() != 'body') {
			whichlink = whichlink.parentNode;
			//alert('whichlink.nodeName.toLowerCase() = ' + whichlink.nodeName.toLowerCase());
		}
		whichlink = whichlink.parentNode;
		whichlink = whichlink.parentNode;

		var findanswer = whichlink.parentNode.getElementsByTagName("div");

		for (var i=0; i < findanswer.length; i++) {
			if (findanswer[i].className.match("prodBox"))  {
				if (findanswer[i].style.display.match("none"))  {
					findanswer[i].style.display = 'block';
				}
				else  {
					findanswer[i].style.display = 'none';
				}
			}
		}

		if (window.event) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		if (e && e.stopPropagation && e.preventDefault) {
			e.stopPropagation();
			e.preventDefault();
		}

	},
	// ----------------------------------------------------------------------------


	//
	// This listens for the click using the addEvent function
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	watch : function(e) {
		var blnReturnValue = false;
		if (document.getElementById) {
			var aryMenuPackNames = headscapeDOM.getElementsByClassName("prodExpand", document.getElementById("prodList"), "div");
			for (var i=0; i < aryMenuPackNames.length; i++) {
				headscapeDOM.addEvent(aryMenuPackNames[i].firstChild, 'click', wffMenuPack.expandOrCollapse, false);
				blnReturnValue = true;
			}
		}
		return blnReturnValue;
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************




//
// JSON class for WFF Account Payment.
// Deals with the CC issue number
// ****************************************************************************
// Developer notes ::
// ** SG : Initial creation
//
var wffAccountPayment = {

	//
	// check the length of the value type in the <input> element ID "cIssue" and alert the user if > 1
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	checkLength : function(e) {
		if (window.event) {
			var whichlink = window.event.srcElement;
		}
		else
		{
			var whichlink = e.target;
		}

		if (document.getElementById("cIssue").value.length > 2) {
			alert('Please note that the Issue number on maestro cards will be shown on the front of your Maestro card.\r\nYou do not need to enter the digit CV2 security number for your card to place an order with Wiltshire Farm Foods');
		}

		if (window.event) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		if (e && e.stopPropagation && e.preventDefault) {
			e.stopPropagation();
			e.preventDefault();
		}

	},
	// ----------------------------------------------------------------------------


	//
	// Call the handler function when an the <input> element ID "cIssue" is found on the page.
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	watch : function(e) {
		var blnReturnValue = false;
		if (document.getElementById("cIssue")) {
			headscapeDOM.addEvent(document.getElementById("cIssue"), 'keyup', wffAccountPayment.checkLength, false);
			blnReturnValue = true;
		}
		return blnReturnValue;
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************




















































//
// JSON class for Order Confirmation
// Prevents the user clicking submit more than once
// ****************************************************************************
// Developer notes ::
// ** MDC : Initial creation
//
var wffOrderConf = {
	blnHasSubmitted : false,


	//
	// Listens for the form submission.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	watch : function(e) {
		if (document.getElementById) {
			var eleConfirmForm = document.getElementById("specialF");
			if (eleConfirmForm) {
				headscapeDOM.addEvent(eleConfirmForm, 'submit', this.stopSubmission, false);
			}
		}
	},
	// ----------------------------------------------------------------------------


	//
	// Prevents form submission when the form has been submitted once already.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	stopSubmission : function(e) {
		// Check if we've submitted the form before
		if (!this.blnHasSubmitted) {
			// Allow the submission
			this.blnHasSubmitted = true;
			return true;
		} else {
			// Stop the form submitting
			if (window.event) {
				window.event.cancelBubble = true;
				window.event.returnValue = false;
			}
			if (e && e.stopPropagation && e.preventDefault) {
				e.stopPropagation();
				e.preventDefault();
			}
			return false;
		}
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************



//
// JSON class for User Login
// Prevents the user clicking submit more than once
// ****************************************************************************
// Developer notes ::
// ** MDC : Initial creation
//
var wffUserLogin = {
	blnHasSubmitted : false,


	//
	// Listens for the form submission.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	watch : function(e) {
		if (document.getElementById) {
			var eleConfirmForm = document.getElementById("existCustForm");
			if (eleConfirmForm) {
				headscapeDOM.addEvent(eleConfirmForm, 'submit', this.stopSubmission, false);
			}
		}
	},
	// ----------------------------------------------------------------------------


	//
	// Prevents form submission when the form has been submitted once already.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	stopSubmission : function(e) {
		// Check if we've submitted the form before
		if (!this.blnHasSubmitted) {
			// Allow the submission
			this.blnHasSubmitted = true;
			return true;
		} else {
			// Stop the form submitting
			if (window.event) {
				window.event.cancelBubble = true;
				window.event.returnValue = false;
			}
			if (e && e.stopPropagation && e.preventDefault) {
				e.stopPropagation();
				e.preventDefault();
			}
			return false;
		}
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************





//
// JSON class for Contact us
// Prevents the user clicking submit more than once
// ****************************************************************************
// Developer notes ::
// ** MDC : Initial creation
//
var wffContactUs = {
	blnHasSubmitted : false,


	//
	// Listens for the form submission.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	watch : function(e) {
		if (document.getElementById) {
			var eleConfirmForm = document.getElementById("feedback");
			if (eleConfirmForm) {
				headscapeDOM.addEvent(eleConfirmForm, 'submit', this.stopSubmission, false);
			}
		}
	},
	// ----------------------------------------------------------------------------


	//
	// Prevents form submission when the form has been submitted once already.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	stopSubmission : function(e) {
		// Check if we've submitted the form before
		if (!this.blnHasSubmitted) {
			// Allow the submission
			this.blnHasSubmitted = true;
			return true;
		} else {
			// Stop the form submitting
			if (window.event) {
				window.event.cancelBubble = true;
				window.event.returnValue = false;
			}
			if (e && e.stopPropagation && e.preventDefault) {
				e.stopPropagation();
				e.preventDefault();
			}
			return false;
		}
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************



//
// JSON class for Send to a Friend
// Prevents the user clicking submit more than once
// ****************************************************************************
// Developer notes ::
// ** MDC : Initial creation
//
var wffSendFriend = {
	blnHasSubmitted : false,


	//
	// Listens for the form submission.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	watch : function(e) {
		if (document.getElementById) {
			var eleConfirmForm = document.getElementById("sendFriend");
			if (eleConfirmForm) {
				headscapeDOM.addEvent(eleConfirmForm, 'submit', this.stopSubmission, false);
			}
		}
	},
	// ----------------------------------------------------------------------------


	//
	// Prevents form submission when the form has been submitted once already.
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	stopSubmission : function(e) {
		// Check if we've submitted the form before
		if (!this.blnHasSubmitted) {
			// Allow the submission
			this.blnHasSubmitted = true;
			return true;
		} else {
			// Stop the form submitting
			if (window.event) {
				window.event.cancelBubble = true;
				window.event.returnValue = false;
			}
			if (e && e.stopPropagation && e.preventDefault) {
				e.stopPropagation();
				e.preventDefault();
			}
			return false;
		}
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************




//
// JSON class for input field behaviour
// ****************************************************************************
// Developer notes ::
// ** MDC : Initial creation
//
var headscapeInputs = {

	cFOCUSCLASS : "sffocus",

	//
	// Assigns event handlers to text input fields - just for IE
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	watch : function(e) {
		if (document.getElementsByTagName && document.all) {
			var aryInputs = document.getElementsByTagName("input");

			for (var i=0; i<aryInputs.length; i++) {
				if (aryInputs[i].getAttribute("type") == "text") {
					headscapeDOM.addEvent(aryInputs[i], 'focus', this.toggleFocus, false);
					headscapeDOM.addEvent(aryInputs[i], 'blur', this.toggleFocus, false);
				}
			}
		}
	},
	// ----------------------------------------------------------------------------


	//
	// ***DEPENDS ON PROTOTYPE***
	// Switches the focus style of an input
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	toggleFocus : function(e) {
		// Get a handle on the input that was focussed/blurred
		if (window.event) {
			var eleInput = window.event.srcElement;
		}
		else {
			var eleInput = e.target;
		}
		e = e || window.event;
		var eventType = e.type;

		if (eleInput) {
			if (!Element.hasClassName(eleInput, "postcode")) {
				if (eventType == "blur") {
					Element.removeClassName(eleInput, headscapeInputs.cFOCUSCLASS);
				} else {
					Element.addClassName(eleInput, headscapeInputs.cFOCUSCLASS);
				}
			}
		}
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************




//
// JSON class for "shop by diet" filtering
// ****************************************************************************
// Developer notes ::
// ** MDC : Initial creation
//
var wffDietFilter = {

	cDIETCOOKIE : "WFFHideDiet",
	hshDietNames : new HashTable("fDietDiabetic", "suitable for diabetics", "fDietLowFat", "low fat", "fDietGlutenFree", "gluten-free", "fDietVeg", "vegetarian", "fDietRedSalt", "reduced salt", "fDietModSalt", "moderate salt", "fDietOther", ""),
	hshDietCookies : new HashTable("suitable for diabetics", "Diabetic", "low fat", "LowFat", "gluten-free", "Gluten", "vegetarian", "Veg", "reduced salt", "RedSalt", "moderate salt", "ModSalt", "", "Other"),
	hshDietIndexes : new HashTable("suitable for diabetics", 0, "low fat", 1, "gluten-free", 2, "vegetarian", 3, "reduced salt", 4, "moderate salt", 5, "", 6),
	aryCookies : new Array("", "", "", "", "", "", ""),

	blnImRunning : false,



	//
	// Initialises local cookie mirror array
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	init : function() {
		// Set a local array to store the cookie values to save us looking them up every time
		this.aryCookies[0] = headscapeDOM.getSubCookie(this.cDIETCOOKIE, "Diabetic");
		this.aryCookies[1] = headscapeDOM.getSubCookie(this.cDIETCOOKIE, "LowFat");
		this.aryCookies[2] = headscapeDOM.getSubCookie(this.cDIETCOOKIE, "Gluten");
		this.aryCookies[3] = headscapeDOM.getSubCookie(this.cDIETCOOKIE, "Veg");
		this.aryCookies[4] = headscapeDOM.getSubCookie(this.cDIETCOOKIE, "RedSalt");
		this.aryCookies[5] = headscapeDOM.getSubCookie(this.cDIETCOOKIE, "ModSalt");
		this.aryCookies[6] = headscapeDOM.getSubCookie(this.cDIETCOOKIE, "Other");

		// Assign event handlers
		this.watch();
	},
	// ----------------------------------------------------------------------------



	//
	// Assigns event handlers to diet filter checkboxes
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	watch : function(e) {
		if (document.getElementById) {
			var eleFilter = $("filter");
			var eleUpdateButton = $("updateWrapper");

			if (eleFilter) {
				var aryCheckboxes = eleFilter.getElementsByTagName("input");

				for (var i=0; i<aryCheckboxes.length; i++) {
					if (aryCheckboxes[i].getAttribute("type") == "checkbox") {
						headscapeDOM.addEvent(aryCheckboxes[i], 'click', this.toggleVisible, false);
					}
				}

				if (eleUpdateButton) {
					Element.hide(eleUpdateButton);
				}
			}
		}
	},
	// ----------------------------------------------------------------------------




	getDietsArray : function(strTitle) {
		var aryReturn = new Array(false, false, false, false, false, false, false);

		if (strTitle.length > 0) {
			var aryTitles = strTitle.split(", ");
			for (var i=0; i<aryTitles.length; i++) {
				aryReturn[this.hshDietIndexes.getItem(aryTitles[i])] = true;
			}
		}

		return aryReturn;
	},



	toggleVisible : function(e) {
		if (!wffDietFilter.blnImRunning) {
			wffDietFilter.blnImRunning = true;

			// Get a handle on the checkbox that was clicked
			if (window.event) {
				var eleInput = window.event.srcElement;
			}
			else {
				var eleInput = e.target;
			}

			if (eleInput) {
				var strCheckboxName = eleInput.getAttribute("name");
				var blnJustChecked = eleInput.checked;
				var strTitle = wffDietFilter.hshDietNames.getItem(strCheckboxName);
				var strSubCookie = wffDietFilter.hshDietCookies.getItem(strTitle);
				var intSubCookieIndex = wffDietFilter.hshDietIndexes.getItem(strTitle);
				var eleInputLi = eleInput.parentNode;
				var eleNotification = $("notification")

				// Set the cookie and our local array store to remember this preference
				var strCookieValue = 1;
				if (blnJustChecked) strCookieValue = "";
				headscapeDOM.setSubCookie(wffDietFilter.cDIETCOOKIE, strSubCookie, strCookieValue);
				wffDietFilter.aryCookies[intSubCookieIndex] = strCookieValue;

				// Pick up all the products which now need to be shown or hidden
				var aryProducts = $("prodList").childNodes;
				for (var x=0; x<aryProducts.length; x++) {
					// Skip text nodes
					if (aryProducts[x].nodeType != 1) continue;
					// Skip the error msg list item
					if (!Element.hasClassName(aryProducts[x], "prod")) continue;

					var blnShowOrHide = false;
					var strProdTitle = aryProducts[x].getAttribute("title");
					if (strProdTitle == null) strProdTitle = "";

					if (strTitle == strProdTitle) {
						// Other/single diet
						blnShowOrHide = true;
					} else if (strProdTitle.indexOf(", ")) {
						// Multiple diets
						var aryTitles = wffDietFilter.getDietsArray(strProdTitle);

						// Compare titles with cookies to see if we need to show or hide this prod
						for (var i=0; i<aryTitles.length; i++) {
							if (blnJustChecked) {
								// Showing - just match one
								if (aryTitles[i] && wffDietFilter.aryCookies[i] == "") {
									blnShowOrHide = true;
									break;
								}
							} else {
								// Hiding - match all
								if (aryTitles[i] && wffDietFilter.aryCookies[i] == "") {
									blnShowOrHide = false;
									break;
								} else {
									blnShowOrHide = true;
								}
							}
						}
					}

					// If we need to, show or hide this product
					if (blnShowOrHide) {
						if (blnJustChecked) {
							Element.show(aryProducts[x]);
						} else {
							Element.hide(aryProducts[x]);
						}
					}
				} // End loop

				// Change the style of the checkbox
				if (blnJustChecked) {
					Element.removeClassName(eleInputLi, "unchecked");
					if (!Element.hasClassName(eleInputLi, "checked")) Element.addClassName(eleInputLi, "checked");
				} else {
					Element.removeClassName(eleInputLi,	"checked");
					if (!Element.hasClassName(eleInputLi, "unchecked")) Element.addClassName(eleInputLi, "unchecked");
				}

				// Update the row alt colours and count how many products are still visible
				var intVisibleProdCount = 1;
				for (var y=0; y<aryProducts.length; y++) {
					if (aryProducts[y].nodeType == 1) {
						if (aryProducts[y].style.display != "none" && Element.hasClassName(aryProducts[y], "prod")) {
							if (intVisibleProdCount % 2) {
								Element.addClassName(aryProducts[y], "alt");
							} else {
								Element.removeClassName(aryProducts[y], "alt");
							}
							intVisibleProdCount++;
						}
					}
				}

				var eleProdList = $("prodList");
				var eleNoResults = $("noResults");
				// If there are no products visible, display the message li
				if (intVisibleProdCount == 1) {
					if (!eleNoResults) {
						var eleErrorLi = document.createElement("li");
						Element.addClassName(eleErrorLi, "warningDialog");
						eleErrorLi.setAttribute("id", "noResults");
						Element.update(eleErrorLi, "<div class=\"warning1\"><div class=\"warning2\"><h3>No meals found</h3><p>We cannot find any meals that match your current options. We recommend you try one of the options below:</p><ul><li>Change the options you have selected in <a href=\"#filter\">the dietary box</a> above</li><li>Select from one of the categories listed to the left</li><li>Or call us on <span class=\"tel\">(01225 756019)</span></li></ul></div></div>");

						// Attach the new list item
						eleProdList.appendChild(eleErrorLi);
					}
				} else {
					// Hide the error message
					if (eleNoResults) {
						eleProdList.removeChild(eleNoResults);
					}
				}

				// Notify the user
				if (strTitle.length == 0) strTitle = "No special requirements"
				if (blnJustChecked) {
					Element.update(eleNotification, "<p>The following change has been made: " + strTitle + " now shown</p>");
				} else {
					Element.update(eleNotification, "<p>The following change has been made: " + strTitle + " now hidden</p>");
				}

				// Flash
				eleNotification.style.backgroundColor = "#FDCB5D";
				setTimeout("wffDietFilter.flashOff()", 2000);
			}
			wffDietFilter.blnImRunning = false;
		}
	},
	// ----------------------------------------------------------------------------


	//
	// ***DEPENDS ON PROTOTYPE***
	// Un-flashes the diet filter notification bar
	//
	// Developer notes ::
	// ** MDC : Initial creation
	//
	flashOff : function() {
		$("notification").style.backgroundColor = "#FFFFFF";
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************




//
// JSON class for  Place Order submit button
// ****************************************************************************
// Developer notes ::
// ** SG : Initial creation
//
var wffOrderConfirmation = {

	//
	// show the PAS iframe and hide the rest of content
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	showPAS : function(e) {
		if(document.getElementById("securecode")) {

			document.getElementById('order_confirmation').style.display = 'none';
			document.getElementById('pas').style.display = 'block';

//			document.getElementById('order_confirmation').className='hide';
//			document.getElementById('pas').className='co_bar';
		}
	},
	// ----------------------------------------------------------------------------


	//
	// Call the handler function when the submit button is clicked.
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	
	watch : function(e) {
		var blnReturnValue = false;
		if (document.getElementById('pas')) {
			document.getElementById('pas').style.display = 'none';
			//document.getElementById('pas').className='hide';
		}

		if (document.getElementById('securecode')) {

			var submit_button = document.getElementById('securecode');
			headscapeDOM.addEvent(submit_button, 'click', wffOrderConfirmation.showPAS, false);

			blnReturnValue = true;
			
		}
		return blnReturnValue;
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************



document.write('<style type="text/css" media="screen">#pas {display:none;}</style>');

//
// Load the functions we need immediately.
//
// Developer notes ::
// ** MDC : Initial creation
//
window.onload = function() {
	// Make sure we have a basket before we add Ajax
	if (headscapeDOM.getSubCookie("WFF", "B")) {
		wffBasket.watch();
	}

	// Flash the postcode entry
	wffBasket.flashPostcode();

	// Account Payment
	wffAccountPayment.watch();
	
	// Order confirmation
	wffOrderConfirmation.watch();

	// FAQs
	if (wffFAQ.watch()) wffFAQ.hideanswers();

	// Menu packs
	if (wffMenuPack.watch()) wffMenuPack.hide();

	// Order confirmation form submission
	wffOrderConf.watch();

	// User login form submission
	wffUserLogin.watch();

	// Input focus
//	headscapeInputs.watch();

	// Diet filter
//	wffDietFilter.init();

	// External links
	headscapeDOM.externalLinks();
}
// ----------------------------------------------------------------------------

var wffReview = {
    addRating : function(customerId, productId, rating) {
	    // Call the API using XHT (PROTOTYPE)
		var strURL = location.protocol + "//" + location.host + "/api/reviews.api.asp";
		var strParams = "a=addrating&c=" + customerId + "&pr=" + productId + "&p=" + rating;
		var objAjax = new Ajax.Request(strURL, {method: "post", parameters: strParams, onComplete: wffReview.redrawRatings});

		// Stop the form submitting
		if (window.event) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
    },
    
 	redrawRatings : function(objResponse) {
		// Collect the JSON object from the API call
		eval("var wffAPIResponse = " + objResponse.responseText);
		if(!wffAPIResponse.Error) {
		    var oResponse = wffAPIResponse.Value;
			if(oResponse.Type=="Redirect") {
				window.location=oResponse.Destination;
			}
			if(oResponse.Type=="Rating") {
				var totalScore=oResponse.TotalScore;
				var totalVotes=oResponse.TotalVotes;
				var newScore = oResponse.NewScore;
				var newStarWidth = oResponse.NewStarWidth;
				var message = oResponse.Message;
				var rating = oResponse.Rating;

				document.getElementById('current-text-rating2').innerHTML = '&nbsp;&nbsp;(' + newScore + ')';
				document.getElementById('current-rating2').style.width = newStarWidth+'px';

				message = newScore + ' star';
				if(newScore!=1) message = message + 's';
				message = message + ' based on an average over ' + totalVotes + ' rating';
				if(totalVotes!=1) message = message + 's';
				message = message + '.';
				document.getElementById('current-text-rating2-description').innerHTML = message;
				document.getElementById('starrating-1').style.visibility='hidden';
				document.getElementById('starrating-2').style.visibility='hidden';
				document.getElementById('starrating-3').style.visibility='hidden';
				document.getElementById('starrating-4').style.visibility='hidden';

				message = 'You have rated this product.  Your rating was : <strong>' + rating + ' Star';
				if(rating!=1) message = message + 's';
				message = message + '.</strong><br /><strong>4 Stars</strong> - Excellent, <strong>3 Stars</strong> - Good, <strong>2 Stars</strong> - Below Average, <strong>1 Star</strong> - Poor';
				document.getElementById('customers-rating').innerHTML = message;
			}
		} else {
		    alert(wffAPIResponse.Error.Message);
		}
	},
	
	submitReview : function(customerId, productId, review) {
	    // Call the API using XHT (PROTOTYPE)
		var strURL = location.protocol + "//" + location.host + "/api/reviews.api.asp";
		var strParams = "a=addcomment&c=" + customerId + "&pr=" + productId + "&p=" + escape(review);
		var objAjax = new Ajax.Request(strURL, {method: "post", parameters: strParams, onComplete: wffReview.redrawReview});
	},
	
	redrawReview : function(objResponse) {
		// Collect the JSON object from the API call
		eval("var wffAPIResponse = " + objResponse.responseText);
		if(!wffAPIResponse.Error) {
		    var oResponse = wffAPIResponse.Value;
			if(oResponse.Type=="Redirect") {
				window.location=oResponse.Destination;
			}
			if(oResponse.Type=="Review") {
			    if(document.getElementById('reviewFormContainer')) {
			        document.getElementById('reviewFormContainer').style.display='none';
			        document.getElementById('reviewFormSent').style.display='block';
					fader.clearElements();
					fader.addElement(document.getElementById('reviewFormSent'));
					fader.waitSeconds = 5;
					fader.hideOnEnd = true;
					fader.fade();
			    }
			}
		} else {
		    alert(wffAPIResponse.Error.Message);
		}
	},
	
	publishReviews : function(strParams) {
	    // Call the API using XHT (PROTOTYPE)
		var strURL = location.protocol + "//" + location.host + "/api/reviews.api.asp";
		var objAjax = new Ajax.Request(strURL, {method: "post", parameters: strParams, onComplete: wffReview.publishComplete});
	},
	
	publishComplete : function(objResponse) {
		// Collect the JSON object from the API call
		eval("var wffAPIResponse = " + objResponse.responseText);
		if(!wffAPIResponse.Error) {
		    var oResponse = wffAPIResponse.Value;
			if(oResponse.Type=="Redirect") {
				window.location=oResponse.Destination;
			}
		} else {
		    alert(wffAPIResponse.Error.Message);
		}
	},
	
    showForm : function() {
        if(document.getElementById('reviewForm')) {
            document.getElementById('reviewForm').style.display='block';
        }
    }
    
}
function Fader() {
    var me=this;
    me.waitSeconds=5;
    me.running = false;
    var transparency = 0;
    me.fps = 50;
    me.steps = 50;
	me.hideOnEnd = false;
    me.elements = new Array();
    var elementCounter = 0;
    me.startTransparency = 0;
    me.endTransparency = 100;
    me.addElement = function(ele) {
        me.elements[elementCounter++] = ele;
    };
    me.clearElements = function() {
        me.elements = new Array();
    };
    me.fade = function() {
        me.running=true;
        transparency = me.startTransparency;
        setTimeout("fader.fadeRoutine()", me.waitSeconds*1000);
    };
    me.fadeRoutine=function() {
        if(me.running) {
            var opacity = 100 - transparency;
            transparency += ((me.endTransparency - me.startTransparency) / me.steps);
            try {
                me.elements[0].style.opacity=(opacity/100);
            } catch(e) {}
            if(transparency>me.endTransparency) {
				if(me.hideOnEnd) {
					me.elements[0].style.display='none';
				}
                me.running = false;
            }
            setTimeout("fader.fadeRoutine()", delay()
            );
        }
    };
    var delay=function() {
        return 1000 / me.fps;
    };
}
var fader = new Fader();