﻿var iProductButtonsTimeout = 1000;			// Used by pbasket and product lists for the button timeout

var iBasketStatusTimeout = 4000;				// Used by the product add functionality status timeout
var iBasketStatusItemsChangedTimeout = 2500;

var bDebugMode = false;
var bDoFullSync = false;

var iMaxURLLength = 1800;

var bDisableClientBasket = false;

var sWeightDelimiter = "|";
var sWeightDelimiterReplacement = "/";

var userAgent = navigator.userAgent.toUpperCase();
if(userAgent.indexOf("MAC") != -1 && (userAgent.indexOf("MSIE") != -1 || userAgent.indexOf("SAFARI") != -1)) {
	bDisableClientBasket = true;
} else if(document.pageType == "PROMOMAIN") {
	var oMain = document.appFrames.mainContent();
	if(oMain && oMain.document.pageType == "FULLBASKET") {
		bDisableClientBasket = true;
	}
}

document.leavingPage = false;
document.basketProductServerQty = new Array();
document.pUpdateList = new Array();
document.showBasketMessage = true;

// Initialise the product list array...
if(document.appFrames) {
	var oTop = document.appFrames.topNav();
	if(oTop) {
		if(!oTop.document.pList) {
			oTop.document.pList = new Array();
		}
	}
}
	
function e(id) {	// attach events to product line elements
	var o = document.getElementById("i" + id + "-q");
	if(o) {
		attachEventHandler(o, "focus", _setActivePageElement);
		attachEventHandler(o, "focus", _focusUpdateProduct);
		attachEventHandler(o, "keypress", _processKeyPressEvent);
		if(o.attachEvent) { // IE only
			o.attachEvent("onkeyup", new Function("kup(" + id + ")"));
		} else {
			attachEventHandler(o, "keyup", new Function("kup(" + id + ")"));
		}
	}
	o = document.getElementById("i" + id + "-w");
	if(o) {
		attachEventHandler(o, "focus", _setActivePageElement);
		attachEventHandler(o, "keypress", _processKeyPressEvent);
	}
	o = document.getElementById("i" + id + "-s");
	if(o) {
		attachEventHandler(o, "focus", _setActivePageElement);
		attachEventHandler(o, "change", _processChangeEvent);
	}
	o = document.getElementById("i" + id + "-a");
	if(o) {
		attachEventHandler(o, "focus", _setActivePageElement);
		attachEventHandler(o, "mousedown", _setActivePageElement);
		if(o.attachEvent) { // IE only
			o.attachEvent("ondblclick", new Function("a(" + id + ")"));
		}

	}

/*	Removed to speed up page rendering. Hopefully, this isn't needed anyway.
	o = _updateProduct(id);
	if(o) {
		o.resetIsDirty();
	}*/
}

function kup(id) {
	var prod = _updateProduct(id, true);
	updateProductButton(prod);
}

function _setActivePageElement(e) {
	try {
		document.activePageElement = _getSrcElement(this);
		if (document.activePageElement.tagName == "INPUT" &&  document.activePageElement.type == "text") {
			document.activePageElement.select();
		}
	} catch(e) {
	}
}

function _processKeyPressEvent(e) {
	var iKeyCode;
	if(window.event) {
		iKeyCode = window.event.keyCode;
	} else if(this) {
		iKeyCode = e.which;
	}

	var oSrcElement = _getSrcElement(this);;
	if(oSrcElement && (iKeyCode == 13)) {
		b(oSrcElement);
		return false;
	}
}

function _processChangeEvent(e) {
	var oSrcElement = _getSrcElement(this);
	if(oSrcElement) {
		var sId = oSrcElement.id;
		if(sId && (sId.charAt(0) == "i")) {
			var iIndex = sId.indexOf("-");
			if(iIndex != -1) {
				sId = sId.substr(1, iIndex - 1);
				var o = _updateProduct(sId);
				updateProductButton(o);
			}
		}
	}
}

function _getSrcElement(o) {
	if(window.event) {
		return window.event.srcElement;
	} else if(o) {
		return o;
	}
}

// product can either by a product object to clone or the product code. All other parameters will be ignored when cloning.
function product(product, qty, orderUnits, note, subs, subsText, desc, price, avg, unitPrice, looseWeighIndicator, inBasket) {
	if(typeof product == "object") {		// a product object has been passed in to be cloned...
		for(var i in product) {
			this[i] = product[i];
		}
	} else {
		if(product) {
			this.id = product;
		} else {
			this.id = null;
		}
	
		if(qty) {
			this.qty = qty;
		} else {
			var oq = document.getElementById("i" + product + "-q");
			if (oq) {
				this.qty = getValue(oq);
			} else {
				this.qty = 1;
			}
		}
	
		if(orderUnits) {
			this.orderUnits = orderUnits;
		} else {
			this.orderUnits = 1;
		}
	
		var oProd = document.getElementById("i" + product + "-b");
		if(note) {
			this.note = note;
		} else {
			if (oProd && oProd.getAttribute("note"))
				this.note = oProd.getAttribute("note");
			else
				this.note = "";
		}
	
		if(subs) {
			this.subs = subs;
		} else {
			if (oProd && oProd.getAttribute("subs")) {
				this.subs = oProd.getAttribute("subs");
			}
		}
		this.subs = _checkSubsValue(this.subs);
	
		if(subsText) {
			this.subsText = subsText;
		} else {
			if (oProd && oProd.getAttribute("subsText"))
				this.subsText = oProd.getAttribute("subsText");
			else
				this.subsText = "";
		}
	
		this.avg = avg;					// average weight
		if (oProd && oProd.getAttribute("avg")) {
			this.avg = oProd.getAttribute("avg");
		} 

		this.unitPrice = unitPrice;
		if (oProd && oProd.getAttribute("unitPrice")) {
			this.unitPrice = oProd.getAttribute("unitPrice");
		}

		if(looseWeighIndicator) {
			this.looseWeighIndicator = looseWeighIndicator;
		} else {
			if (oProd && oProd.getAttribute("loose") == "true")
				this.looseWeighIndicator = true;
			else
				this.looseWeighIndicator = false;
		}

		if(desc) {
			this.desc = desc;
		} else {
			this.desc = "";
		}
	
		if(price) {
			this.price = price;
		} else {
			this.price = 0;
		}
	
		// Weight values are taken from the HTML page (select element)
		var oWeight = document.getElementById("i" + this.id + "-s");
		if(oWeight) {
			this.weightIndex = oWeight.selectedIndex;
			if(oWeight.selectedIndex > 0) {
				this.weight = oWeight.value;
			}
		} else {
			this.weightIndex = 0;
			this.weight = "";
		}
		this.shelfId;	// leave undefined if there is no shelf set for the product

		if(inBasket) {
			this.inBasket = inBasket;
		}
		
		this.ignoreQty = false;
	}
	
	this.status = "READY";
	
	_resetIsDirty(this);
	updateProductButton(this);
}

function _checkSubsValue(subs) {
	sSubs = "TS";

	if(subs) {
		subs = subs.toUpperCase();
		if((subs == "MC") || (subs == "NS")) {
			return subs;
		}
	}
	
	return sSubs;
}

function _resetIsDirty(p) {
	p._orig_qty = p.qty;
	p._orig_orderUnits = p.orderUnits;
	p._orig_note = p.note;
	p._orig_subs = p.subs;
	p._orig_subsText = p.subsText;
	p._orig_weightIndex = p.weightIndex;
}

product.prototype.isDirty = products_isDirty;
product.prototype.resetIsDirty=  products_resetIsDirty;
product.prototype.add = products_add;

products.prototype.item = products_item;

function products() {
	this.items = new Array();
}

function products_item(id) {
	var bFound = false;

	for(var i = 0; i < this.items.length; i++) {
		if(this.items[i].id == id) {
			return this.items[i];
		}
	}

	var oProduct = new product(id);
	this.items[this.items.length] = oProduct;

	_updateProduct(id);
	
	return oProduct;
}

function products_isDirty() {
	if((this._orig_qty != this.qty) || (this._orig_orderUnits != this.orderUnits) || (this._orig_note != this.note) || (this._orig_subs != this.subs) || (this._orig_subsText != this.subsText) || (this._orig_weightIndex != this.weightIndex)) {
		return true;
	}
	return false;
}

function products_add(qty, amend, retry) {
	try {
		var oBasket;
		if(document.appFrames) {
			oBasket = document.appFrames.basketMain();
		}

		this.addProductsTimer = null;
		this.addQty = 0;
		
		if(this.ignoreQty) {
			if(oBasket) {
				var oQty = oBasket.document.getElementById("i" + this.id + "-q");
				if(oQty) {
					qty = oQty.innerHTML;
				}
			}
			this.ignoreQty = false;
			amend = true;
		} else if(!qty) {
			qty = this.qty;
		}

		this.pageType = document.pageType;
		if(!document.listId) {
			var oQS = new queryString(document.href);
			document.listId = oQS.item("listId").value;
		}
		this.listId = document.listId;
	
		var oTop = document.appFrames.topNav();
		if(oTop) {
			if(!oTop.document.pList) {
				oTop.document.pList = new Array();
			}
			
			var bFound = false;
			for(var i = 0; i < oTop.document.pList.length; i++) {
				if(!oTop.document.pList[i]) {
					oTop.document.pList[i] = oTop.document.createProduct(this);
					bFound = true;
					break;
				}
			}
			if(!bFound) {
				oTop.document.pList[oTop.document.pList.length] = oTop.document.createProduct(this);
			}
			
			var oAdd = oTop.document.getElementById("ap");
			if(oAdd) {
				oAdd.setAttribute("pId", this.id);
				oAdd.setAttribute("qty", qty);
				oAdd.setAttribute("amend", amend);
				oAdd.setAttribute("retry", retry);
				oAdd.click();
			}
		}
		if(oBasket) {
			var o = oBasket.document.getElementById("bs");
			if(o) {
				o.click();
			}
		}
	} catch(e) {
//		alert("DEBUG: products_add: " + e);
	}
}

function _getAddProductItem(doc, id) {
	for(var i = 0; i < doc.pList.length; i++) {
		if(doc.pList[i] && doc.pList[i].id == id) {
			return doc.pList[i];
		}
	}
	return null;
}

function userEvent(event, value) {
	this.event = event;
	this.value = value;
}

function userEvents() {
	this.events = new Array();
}
userEvents.prototype.add = _userEvents_add;
userEvents.prototype.clearAll = _userEvents_clearAll;

function _userEvents_clearAll() {
	this.events.length = 0;
}

function _userEvents_add(event, value) {
	var o = new userEvent(event, value);
	this.events[this.events.length] = o;
}

function _displayBasketStatusMessage(id) {
	try {
		var oBasket = document.appFrames.basketMain();
		if(oBasket) {
			var oBasketDoc = oBasket.document;
			if(oBasketDoc) {
				if(bDebugMode) {
					var oBasketDiv = oBasketDoc.getElementById("basket");
					if(oBasketDiv) {
						var oStatusMsg = oBasketDoc.getElementById("statusmsg");
						if(!oStatusMsg) {
							oStatusMsg = oBasketDoc.createElement("div");
							oStatusMsg.id = "statusmsg";
							oBasketDiv.insertBefore(oStatusMsg, oBasketDiv.firstChild);
						}
						if(oStatusMsg) {
							clearTimeout(oBasketDoc.statusMsgTimeout);
							oStatusMsg.innerHTML = "DEBUG: Updating basket...";
							oStatusMsg.style.display = "block";
						}
					}
				}
				
				var oItem = oBasketDoc.getElementById("i" + id + "-b");
				if(oItem) {
					if(bDebugMode) {
						oItem.className = "update";
					} else {
						oItem.className = "";
					}
				}
			}
		}
	} catch(e) {
//		alert("DEBUG: _displayBasketStatusMessage: " + e);
	}
}

function _clearBasketStatusMessage(oBasketDoc, id) {
	if(oBasketDoc) {
		var oItem = oBasketDoc.getElementById("i" + id + "-b");
		if(oItem) {
			if(oItem.className != "error") {
				oItem.className = "";
			}
		}

		if(bDebugMode) {
			var oTop = document.appFrames.topNav();
			if(oTop) {
				var o = oTop.document.pList;
				if(o) {
					var bReturn = false;
				
					for(var i = 0; i < o.length; i++) {
						if((o[i] && o[i].status && o[i].status != "READY")) {
							bReturn = true;
							break;
						}
					}
				
					if(!bReturn) {
						var oStatusMsg = oBasketDoc.getElementById("statusmsg");
						if(oStatusMsg) {
							oStatusMsg.innerHTML = "DEBUG: Basket update complete.";
							oBasketDoc.statusMsgTimeout = setTimeout("document.appFrames.basketMain().document.getElementById('statusmsg').style.display = 'none'", 1000);
						}
					}
				}
			}
		}
	}
}

function products_add_success(id) {
	var o = _getAddProductItem(document, id);
	if(o) {
		_clearBasketError(o.id);
		o.status = "READY";

		var oBasket = document.appFrames.basketMain();
		if(oBasket) {
			var oBasketDoc = oBasket.document;
			var oItem = oBasketDoc.getElementById("i" + id + "-b");
			if(oItem) {
				var oQty = oBasketDoc.getElementById("i" + id + "-q");
				if(oQty) {
					var sDisplay;
					if(parseFloat(oQty.innerHTML) > 0) {
						sDisplay = "block";
					} else {
						sDisplay = "none";
					}
					if(oItem.style.display != sDisplay) {
						oItem.style.display = sDisplay;
						_checkForProductErrors(oBasketDoc, id);
					}
				}
			}
		}

		_addSendNextEvent(o);

		_checkRetry();

		checkForWarnings();
	}
}

function _clearBasketTimestamp(id) {
	var oBasket = document.appFrames.basketMain();
	if(oBasket) {
		var oBasketDoc = oBasket.document;
		var oList = oBasketDoc.getElementById("b");
		if(oList) {
			var oItem = oBasketDoc.getElementById("i" + id + "-b");
			if(oItem) {
				if(oItem.getAttribute("updateMode") == "ADD") {
					oItem.setAttribute("status", "READY");
					oItem.setAttribute("updateMode", null);
				}
			}
		}
	}
}

function _addSendNextEvent(o) {
	try {
		if(o.userEvents && o.userEvents.events.length > 0) {
			var lQty = 0;
			for(var i = 0; i < o.userEvents.events.length; i++) {
				lQty += (o.userEvents.events[i].value);
			}
			o.userEvents.clearAll();
			o.add(lQty);
		} else {
			o.addImg = null;
			var oBasket = document.appFrames.basketMain();
			if(oBasket) {
				_clearBasketStatusMessage(oBasket.document, o.id);
			}
				
			_clearBasketTimestamp(o.id);
		}
	
		if(document.pList) {
			for(var i = 0; i < document.pList.length; i++) {
				if(document.pList[i] && document.pList[i].id == o.id && document.pList[i].status == "READY") {
					document.pList[i] = null;
				}
			}
			
			/* TODO: need to do some garbage collection here...
			var bFound = false;
			for(var i = document.pList.length - 1; i >= 0; i--) {
				if(document.pList[i]) {
					document.pList.length = i;
					bFound = true;
					break;
				}
			}
			if(!bFound) {
				document.pList.length = 0;
			}
			*/
		}
	} catch(e) {
//		alert("DEBUG: _addSendNextEvent: " + e);
	}
}

function products_add_error(id) {
	try {
		var o = _getAddProductItem(document, id);
		if(o) {
			_setBasketError(o.id);
			o.status = "READY";
			_addSendNextEvent(o);
			_checkRetry();
			var oBasket = document.appFrames.basketMain();
			if(oBasket) {
				_calculateTotal(oBasket.document);
			}
		}
	} catch(e) {
//		alert("DEBUG: products_add_error : " + e);
	}
}

function _setBasketError(id) {
	var oBasket = document.appFrames.basketMain();
	if(oBasket) {
		var oBasketDoc = oBasket.document;
		var oList = oBasketDoc.getElementById("b");
		if(oList) {
			var oItem = oBasketDoc.getElementById("i" + id + "-b");
			if(oItem) {
				oItem.setAttribute("error", "ERROR");
				oItem.setAttribute("status", "READY");
			}
		}
	}
}

function _clearBasketError(id) {
	var oBasket = document.appFrames.basketMain();
	if(oBasket) {
		var oBasketDoc = oBasket.document;
		var oList = oBasketDoc.getElementById("b");
		if(oList) {
			var oItem = oBasketDoc.getElementById("i" + id + "-b");
			if(oItem) {
				oItem.setAttribute("error", null);
				var oQty = oBasketDoc.getElementById("i" + id + "-q");
				if(oQty) {
					oItem.setAttribute("serverQty", oQty.innerHTML);
				}
			}
		}
	}
}

function products_resetIsDirty() {
	try {
		_resetIsDirty(this);
	} catch(e) {
	}
}

document.products = new products();
var p = document.products;	// shortcut variable to the page products

document.addProducts = new Array();

document.updateBasketDisplay = _updateBasketDisplay;
function _updateBasketDisplay(o, qty) {
	var bReturn = true;
	var oBasket = document.appFrames.basketMain();
	if(oBasket) {
		var oBasketDoc = oBasket.document;
		var oQty = oBasketDoc.getElementById("i" + o.id + "-q");
		var fBasketQty;
		if(oQty) {
			fBasketQty = parseFloat(oQty.innerHTML);
		}
		var sPrice = "";
		var sOriginalPrice = "";
		var oList = oBasketDoc.getElementById("b");
		var bError = false;
		var fPrice = o.price;
		if(o.unitPrice && o.unitPrice > 0) {
			fPrice = o.unitPrice;
		}
		if(oList) {
			var oItem = oBasketDoc.getElementById("i" + o.id + "-b");
			if(oItem) {	// update
				var d = new Date();
				oItem.setAttribute("updateTimeStamp", d.getTime());
				bError = (oItem.getAttribute("ERROR") == "ERROR");
				if(oItem.style.display == "none") {
					oItem.style.display = "block";
					o.originalQty = null;
				}
				if(bDebugMode) {
					if(oItem.className != "update") {
						oItem.className = "";
					}
				} else {
					oItem.className = "";
				}
				if((oItem.previousSibling && oItem.previousSibling.getAttribute("error") != "ERROR") || (oItem.nextSibling && oItem.nextSibling.getAttribute("error") == "ERROR")) {
					if(oList.childNodes.length > 1) {
						try {
							var oItemCopy = oItem.cloneNode(true);
							oList.removeChild(oItem);
							var oFirst;
							for(var i = 0; i < oList.childNodes.length; i++) {
								if(oList.childNodes[i].getAttribute("error") != "ERROR") {
									oFirst = oList.childNodes[i];
									break;
								}
							}
							if(oFirst) {
								oItem = oList.insertBefore(oItemCopy, oFirst);
							} else {
								oItem = oList.appendChild(oItemCopy);
							}
						} catch(e) {
//							alert("DEBUG: _updateBasketDisplay: " + e);
						}
					}
				}
				
				oQty = oBasketDoc.getElementById("i" + o.id + "-q");
				var oPrice = oBasketDoc.getElementById("i" + o.id + "-p");
				if(oQty) {
					if(oQty.innerHTML == "99") {
						bReturn = false;
					} else {
						var q = (parseFloat(oQty.innerHTML) + parseFloat(qty));
						if(q > 99) {
							q = 99;
						}
						var dp = 0;
						if(oPrice) {
							if(oPrice.getAttribute("loose")) {
								dp = 1;
							}
						}
						oQty.innerHTML = _formatNumber(q.toString(), dp);
						oItem.setAttribute("status", "CHANGED");
					}
				}

				if(oPrice) {
					sPrice = formatNumber((fPrice * parseFloat(oQty.innerHTML)), 2);
                    if (oPrice.innerHTML.indexOf("£") > -1 ) {
                        sOriginalPrice = parseFloat(oPrice.innerHTML.substr(1));
                    }
                    else {
                        sOriginalPrice = parseFloat(oPrice.innerHTML);
                    }
                    oPrice.innerHTML = "£" + sPrice;					
					oPrice.setAttribute("note", o.note);
					oPrice.setAttribute("subs", o.subs);
					oPrice.setAttribute("subsText", o.subsText);
					oPrice.setAttribute("desc", o.desc);
				}
			} else {		// add
				var oNewItem = oBasketDoc.createElement("li");
				oNewItem.id = "i" + o.id + "-b";
				oNewItem.setAttribute("productId", o.id);
				sPrice = formatNumber(fPrice * qty, 2);
				sOriginalPrice = "0.00";
				var step = 1;
				if(o.looseWeighIndicator) {
					step = 0.1;
					oNewItem.setAttribute("loose", "true");
				}
				oNewItem.innerHTML = _buildBasketProductHTML(o.id, qty, o.desc, fPrice, sPrice, step, o.looseWeighIndicator, o);
				
				var d = new Date();
				oNewItem.setAttribute("updateTimeStamp", d.getTime());
				oNewItem.setAttribute("status", "CHANGED");
				
				var oFirst;
				for(var i = 0; i < oList.childNodes.length; i++) {
					if(oList.childNodes[i].getAttribute("error") != "ERROR") {
						oFirst = oList.childNodes[i];
						break;
					}
				}
				if(oFirst) {
					oList.insertBefore(oNewItem, oFirst);
				} else {
					oList.appendChild(oNewItem);
				}
			}
			_checkForProductErrors(oBasketDoc, o.id);
		}
		if(bError) {
			_calculateTotal(oBasketDoc);
		} else {
			var fQty = parseFloat(o.qty);
			if(fBasketQty) {
				if((fBasketQty + fQty) > 99) {
					fQty = 99 - fBasketQty;
				}
			}
			_amendTotal(oBasketDoc, sOriginalPrice, sPrice);
		}
	}

	_displayEmptyBasketMessage();

	return bReturn;
}

function _amendTotal(oBasketDoc, origAmount, newAmount) {
	var oTotal = oBasketDoc.getElementById("headerTotalAmount");
	if(oTotal) {
		var fTotal = parseFloat(oTotal.getAttribute("total")) - parseFloat(formatNumber(parseFloat(origAmount), 2)) + parseFloat(formatNumber(parseFloat(newAmount), 2));
		if(fTotal < 0) {
			fTotal = 0;
		}
		oTotal.setAttribute("total", fTotal);
		var sTotal = "£" + formatNumber(parseFloat(fTotal), 2, true);
		if(oTotal.innerHTML != sTotal) {
			oTotal.innerHTML = sTotal;
			var s = new String(oTotal.innerHTML);
			if(s.substr(0, 1) != "£") { // If the browser does not fully support UTF-8...
				oTotal.innerHTML = "£" + formatNumber(parseFloat(fTotal), 2, true);
			}
		}
	}
}

function _calculateTotal(oBasketDoc) {
	if(oBasketDoc) {
		var oTotal = oBasketDoc.getElementById("headerTotalAmount");
		if(oTotal) {
			var oList = oBasketDoc.getElementById("b");
			if(oList) {
				var fTotal = 0;
				var sId;
				for(var i = 0; i < oList.childNodes.length; i++) {
					if(oList.childNodes[i].style.display != "none" && oList.childNodes[i].className != "error" && oList.childNodes[i].className != "error-last") {
						sId = oList.childNodes[i].getAttribute("productId");
						if(sId) {
							oPrice = oBasketDoc.getElementById("i" + sId + "-p")
							if(oPrice) {
								fTotal += parseFloat(oPrice.innerHTML.replace(/[^0-9\.]/,''));
							}
						}
					}
				}
				oTotal.setAttribute("total", fTotal);
				var sTotal = "£" + formatNumber(fTotal, 2, true);
				if(oTotal.innerHTML != sTotal) {
					oTotal.innerHTML = sTotal;
					var s = new String(oTotal.innerHTML);
					if(s.substr(0, 1) != "£") { // If the browser does not fully support UTF-8...
						oTotal.innerHTML = "£" + formatNumber(fTotal, 2, true);
					}
				}
			}
		}
	}
}

// Edit comments
function eC(id) {
	_updateProduct(id);
	var o = openWindow("/superstore/content/comments.html?bpr=" + id, "comments", 470, 292);
	o.focus();
	return false;
}

function _validateQuantity(o, q) {
	if (!o.looseWeighIndicator) {
		q = Math.floor(q);
		var iMinValue = (_pageAllowsZero() ? 0 : 1);
		if(q < iMinValue) {
			q = iMinValue;
		}
	}
	return q;
}

function _focusUpdateProduct() {
	var sId;
	if(window.event && event.srcElement) {
		sId = event.srcElement.id;
	} else if(this.id) {
		sId = this.id;
	}
	if(sId) {
		var id = parseInt(sId.substring(1));
		if(id) {
			_updateProduct(id);
		}
	}
}

function _updateProduct(id, ignoreValidation) {
	if(document.products) {
		var o = document.products.item(id);
		if(o) {
			var oDesc = document.getElementById("i" + id + "-d");
			var oPrice = document.getElementById("i" + id + "-p");
			var oQty = document.getElementById("i" + id + "-q");
			var oWeight = document.getElementById("i" + id + "-s");
			var oShelfId = document.getElementById("i" + id + "-b");
			var oInBasket = document.getElementById("i" + id + "-ib");
			if(oWeight) {
				if(oWeight.selectedIndex > 0) {
				
					if(o.weight && (o.note.indexOf(sWeightDelimiter) != -1)) {
						_stripWeightFromNote(o);
					} 
					o.weight = oWeight.value;
					_addWeightToNote(o);
					
					/* BOB15 Accurate Guide Price - Start
					   Grab the actual catch wieght/unit price from the weight feild (actual weight selected)
					   Use this to set the unit price. This will show accutate price in the basket and at checkout. 
					*/
					var tempUnitPrice = 0;                
					var iSlashDelimiterIndex = o.weight.indexOf('/');
					if (iSlashDelimiterIndex != -1)        
					{
						tempUnitPrice = o.weight.substring(iSlashDelimiterIndex + 2)        
						if (tempUnitPrice > 0 && !isNaN(tempUnitPrice))        
						{
							o.unitPrice = parseFloat(tempUnitPrice);        
						}         
					}
					// BOB15 Accurate Guide Price - End	
									
				} else {
					_stripWeightFromNote(o);
					o.weight = "";
				}
				o.weightIndex = oWeight.selectedIndex;
				o.subs = _checkSubsValue(o.subs);
			} else {
				o.weight = "";
			}
			if(oDesc) {
				o.desc = getValue(oDesc);
			}
			if(oPrice) {
				o.price = parseFloat(getValue(oPrice));
			}
			if(oQty) {
				if(ignoreValidation) {
					o.qty = getValue(oQty);
				} else {
					o.qty = _validateQuantity(o, getValue(oQty));
				}
				setValue(oQty, o.qty);
			}
			if(oShelfId) {
				o.shelfId = oShelfId.getAttribute("shelfId");
			}
			var oNote = document.getElementById("i" + id + "-n");
			if(oNote) {
				if((o.subs == "TS") && (o.note == "")) {
					oNote.innerHTML = "Write a note";
				} else if((o._orig_note != o.note) || (o._orig_subs != o.subs) || (o._orig_subsText != o.subsText)) {
					oNote.innerHTML = "Edit your note";
				}
			}
			if(!bDisableClientBasket) {
				_setInBasketIndicator(id);
			}
		}
		return o;
	}
}

// Amend the product (same as add but in full basket mode)
function am(id) {
	return a(id, "full");
}

function add(id, desc, price, looseWeightIndicator, mode, voucherId) {
	if(id && desc && price) {
		var o = _updateProduct(id);
		if(o) {
			o.desc = desc;
			o.price = price;
			if(looseWeightIndicator) {
				this.looseWeighIndicator = true;
			} else {
				this.looseWeighIndicator = false;
			}
			a(id, mode, voucherId);
		}
	}
}


// Add the product(s)
function a(id, mode, voucherId, ignoreTimeout, forceAdd) {
	if(!forceAdd && document.activePageElement && (document.activePageElement.type != "image")) {
		return false;
	}

	var o = _updateProduct(id);
	if (!o.isDirty() && mode == "full") {
		alert("This item is unchanged");
		return false;
	}
	if(o.qty > 0) {
		var oWeight = document.getElementById("i" + id + "-s");
		if(oWeight) {
			if(oWeight.selectedIndex == 0) {
				if(forceAdd) {
					oWeight.selectedIndex = 1;
				} else {
					alert("Please choose a weight");
					oWeight.focus();
					return false;
				}
			}
		}
	}

	if (mode != "full" && !bDisableClientBasket) {
		var lQty = o.qty;
		if(o.ignoreQty) {
			lQty = 0;
		}
		if(document.appFrames) {
			var oBasket = document.appFrames.basketMain();
			if(oBasket) {
				var oItem = oBasket.document.getElementById("i" + id + "-b");
				if(oItem) {
					if(!oItem.getAttribute("serverQty")) {
						var oQty = oBasket.document.getElementById("i" + id + "-q");
						if(oQty) {
							oItem.setAttribute("serverQty", oQty.innerHTML);
						}
					}
				}
				
				if(oBasket.document.updateBasketDisplay(o, lQty)) {
					o.voucherId = voucherId;
					o.mode = mode;
				
					if (o.addProductsTimer) {
						clearTimeout(o.addProductsTimer);
					}
				
					if(!o.addQty) {
						o.addQty = 0;
					}
		
					o.addQty += parseFloat(o.qty);
					if(ignoreTimeout) {
						_updateProduct(o.id).add(o.addQty);
					} else {
						o.addProductsTimer = setTimeout("_updateProduct(" + o.id + ").add('" + o.addQty + "')", iProductButtonsTimeout);
					}
				}
			
				oItem = oBasket.document.getElementById("i" + id + "-b");
				if(oItem) {
					oItem.setAttribute("updateMode", "ADD");
				}
			}
		}
 				
		var oQty = document.getElementById("i" + id + "-q");
		if(oQty) {
			oQty.value = o.qty = "1";
			_updateWeight(id);
		}
	
		updateProductButton(o);
		o.resetIsDirty();
		_setInBasketIndicator(o.id);

		if(o.shelfId) {
			updateAdvert(o.shelfId, 3);
		}
		return false;
	}
	
	if(o.shelfId) {
		updateAdvert(o.shelfId, 3);
	}

	if (document.addProductsTimer) {
		clearTimeout(document.addProductsTimer);
	}

	if(o != null) {
		var sUrl = _buildAddUrl(o, voucherId);
		o.ignoreQty = false; // Reset the flag
		var oBasket = document.appFrames.basketMain();
		if(oBasket) {
			// Ensure the new product to add is not missed if products are being added...
			if(document.doingAddProducts && (document.addProducts.length == 1)) {
				document.addProducts.unshift();
			}
			
			if(!document.addProducts[0]) {
				document.addProducts[0] = "";
			}
			
			var sNew = document.addProducts[0] + sUrl;
			if(sNew.length > iMaxURLLength) {
				document.addProducts.unshift("");
			}
			
			if(!document.addProducts[0]) {
				var sMode = "";
				if(mode) {
					sMode = "mode=" + mode;
					if (mode == "full") {
						// If full basket mode, then amend quantity instead of adding
						sMode += "&ao=amend";
					} else if (mode == "iv") {
						// Item and voucher mode
						sMode += "&ao=iv"; 
					}
					sMode += "&";
				}
				document.addProducts[0] = sMode + "from=" + _getFromString() + "&" + sUrl;
			} else {
				document.addProducts[0] += ("&" + sUrl);
			}
			document.addProductsTimer = setTimeout("_addProducts()", iProductButtonsTimeout);

			o.resetIsDirty();

			if(mode != "full") {
				_setInBasketIndicator(o.id);
				var oQty = document.getElementById("i" + id + "-q");
				if(oQty) {
					oQty.value = o.qty = "1";
					_updateWeight(id);
				}
			}

			updateProductButton(o);
		}
	}

	return false;
}

function _buildAddUrl(o, voucherId, qty) {
	if(isNaN(qty)) {
		if(o.ignoreQty) {
			qty = 0;
		} else {
			qty = o.qty;
		}
	}
	var sUrl = "bpr=" + o.id + "&qty=" + qty + "&note=" + escapeAll(o.note) + "&subs=" + escape(o.subs) + "&subsText=" + escapeAll(o.subsText) + "&desc=" + escapeAll(o.desc) + "&lp=" + escape(o.price);
	if(o.shelfId && (document.addShelfId != o.shelfId)) {
		sUrl += "&shelfId=" + o.shelfId;
		document.addShelfId = o.shelfId;
	}
	if(o.unitPrice && o.unitPrice > 0) {
		sUrl += " &up=" + o.unitPrice;
	} else {
		sUrl += " &up=" + escape(o.price);
	}
	if(o.looseWeighIndicator) {
		sUrl += " &lwi=1";
	} else {
		sUrl += " &lwi=0";
	}
	if (voucherId) {
		sUrl += "&voucher=" + voucherId;
	}
	
	return sUrl;
}

function _addProducts() {
	if(document.addProducts.length > 0) {
		if(document.appFrames.basketMain() && document.appFrames.basketMain().document.pageInitialised) {
			document.doingAddProducts = true;

			var sUrl = document.addProducts.pop();
			
			var oBasket = document.appFrames.basketMain();
			if(sUrl && oBasket) {
				oBasket.location.replace("/superstore/basket/perm.aspx?" + sUrl);
			}
		
			document.doingAddProducts = false;
		}
	}
}

function i(id, step, allowZero) {	// Increment quantity
	if (!step)
		step = 1;
	_changeQuantity(id, step, allowZero);
}

function d(id, step, allowZero) {	// Decrement quantity
	if (!step)
		step = 1;
	_changeQuantity(id, -(step), allowZero);
}

// TODO: Move these two into util.js?
function getValue(o) {
	if (o.value)
		return o.value;
	else
		return o.innerHTML;
}

function setValue(o, val) {
	if (o.value)
		o.value = val;
	else
		o.innerHTML = val;
}

function _changeQuantity(id, c, allowZero) {
	var b = p.item(id); // Make sure the product is created
	var o = document.getElementById("i" + id + "-q");
	if(o) {
		if(bDisableClientBasket) {
			var q = parseFloat(getValue(o));
	
			if(isNaN(q)) {
				setValue(o, "1");
			} else {
				q+=(new Number(c));
				if (!allowZero) {
					if(q > 0 && q<=99) {
						setValue(o, _formatNumber(q,2));
					}
				} else {
					if(q >= 0 && q<=99) {
						setValue(o, _formatNumber(q,2));
					}
				}
			}
	
			_updateWeight(id);
			_updateProduct(id);
			updateProductButton(b);
		} else {
			var q = originalQ = parseFloat(getValue(o));
			if((q + c) <= 99) {
				if(isNaN(document.basketProductServerQty["i" + id])) {
					document.basketProductServerQty["i" + id] = q;
				}
			
				if(isNaN(q)) {
					setValue(o, "1");
				} else {
					q+=(new Number(c));
					if (!allowZero) {
						if(q > 0 && q<=99) {
							setValue(o, _formatNumber(q,2));
						}
					} else {
						if(q >= 0 && q<=99) {
							setValue(o, _formatNumber(q,2));
						}
					}
				}
		
				_updateWeight(id);
				var oProduct = _updateProduct(id);
				if(!oProduct.originalQty && originalQ == 0) {
					oProduct.originalQty = 0;
				}
	
				var oList = document.getElementById("b");
				if(oList) {
					var oItem = document.getElementById("i" + id + "-b");
					if(oItem) {
						oItem.setAttribute("updateMode", "UPDATE");
	 				
						if(oItem.nextSibling && oItem.nextSibling.getAttribute("ERROR") == "ERROR") {
							try {
								var oItemCopy = oItem.cloneNode(true);
								oList.removeChild(oItem);
								var oFirst;
								for(var i = 0; i < oList.childNodes.length; i++) {
									if(oList.childNodes[i].getAttribute("error") != "ERROR") {
										oFirst = oList.childNodes[i];
										break;
									}
								}
								if(oFirst) {
									oItem = oList.insertBefore(oItemCopy, oFirst);
								} else {
									oItem = oList.appendChild(oItemCopy);
								}
							} catch(e) {
//								alert("DEBUG: _changeQuantity: " + e);
							}
						}
						var d = new Date();
						oItem.setAttribute("updateTimeStamp", d.getTime());
						oItem.setAttribute("status", "CHANGED");
						if(oProduct.qty == 0) {
							oItem.style.display = "none";
						} else {
							if(oItem.style.display == "none") {
								oItem.style.display = "block";
							}
						}
						if(bDebugMode) {
							if(oItem.className != "update") {
								oItem.className = "";
							}
						} else {
							oItem.className = "";
						}
		
						var oPrice = document.getElementById("i" + id + "-p");
						if(oPrice) {
							oPrice.innerHTML = formatNumber(oPrice.getAttribute("price") * oProduct.qty, 2);
						}
						var oBasket = document.appFrames.basketMain();
						if(oBasket) {
							if(oItem.getAttribute("ERROR") == "ERROR") {
								_calculateTotal(oBasket.document);
							} else {
								_amendTotal(oBasket.document, originalQ * oPrice.getAttribute("price"), oPrice.getAttribute("price") * oProduct.qty);
							}
						}
					}
				}
				var oStatus = document.getElementById("bs");
				if(oStatus) {
					oStatus.click();
				}
				updateProductButton(b);
			}
			_checkForProductErrors(document, o.id);
			_displayEmptyBasketMessage();
		}
	}
	
	return false;
}

function _updateWeight(id) {
	var o = document.getElementById("i" + id + "-q");
	if(o) {
		var q = parseFloat(getValue(o));
		
		if(q < 0 || isNaN(q)) {
			q = 1;
			setValue(o, _formatNumber(q,1));
		} else if(q > 99) {
			q = 99;
			setValue(o, _formatNumber(q,1));
		}
		var oWeight = document.getElementById("i" + id + "-w");
		if(oWeight) {
			var avgWeight = document.products.item(id).avg;
			if(avgWeight) {
				oWeight.value = _formatNumber(avgWeight * q, 2);
			}
		}
	}
}

function _calcWeight(id) {
	var oWeight = document.getElementById("i" + id + "-w");
	if(oWeight) {
		var avgWeight = document.products.item(id).avg;
		if(avgWeight) {
			var o = document.getElementById("i" + id + "-q");
			if(o) {
				if(isNaN(oWeight.value)) {
					q = o.value;
				} else {
					var q = Math.round(oWeight.value / avgWeight);
					var iMinValue = (_pageAllowsZero() ? 0 : 1);
					if(q < iMinValue) {
						q = iMinValue;
					} else if(q > 99) {
						q = 99;
					}
					o.value = q;
				}
				oWeight.value = _formatNumber(q * avgWeight, 2);
			}
		}
	}
}

function _formatNumber(n, decimalPlaces) {
	if(decimalPlaces == 0) {
		return Math.round(n);
	} else {
		var i = Math.pow(10, decimalPlaces);
		return Math.round(n * i) / i;
	}
}

function b(o) {	// blur
	if(o && o.id) {
		var re = new RegExp(/^([0-9]*|\d*\.\d{1}?\d*)$/);
		if(!_pageAllowsZero() && (parseFloat(o.value) == "0")) {
			o.value = "1";
		} else if(!re.test(o.value)) {
			o.value = parseInt(o.value);
		} else {
			o.value = parseFloat(o.value);
		}
	
		var q = parseInt(o.value);
		var id = parseInt(o.id.substring(1));
		if(o.id.substring(o.id.length - 2) == "-w") {
			_calcWeight(id);
		} else {
			_updateWeight(id);
		}
		var prod = _updateProduct(id);
		updateProductButton(prod);
	}
}

function _pageAllowsZero() {
	switch(document.pageType) {
		case "FULLBASKET":
		case "PBASKET":
			return true;
		default:
			return false;
	}
}

function updateAdvert(shelfId, tile) {
	var oAdvert = document.appFrames.advert();

	if(oAdvert) {
		if(document.adShelfId != shelfId) {
			_loadAdd(shelfId, tile, oAdvert);
		} else {
			if (!document.bReloadedAd) {
				_loadAdd(shelfId, tile, oAdvert);
				document.bReloadedAd = true;
			}
		}
	}
}

function _loadAdd(shelfId, tile, frame) {
	document.adShelfId = shelfId;
	if(!tile) {
		tile = 1;
	}

	try {
		var sUrl = "/superstore/content/advert.html?shelfId=" + document.adShelfId + "&tile=" + tile;
		frame.location.href = sUrl;
	} catch(e) {
	}
}

function il(id){
	var o = _updateProduct(id);

	if(o != null) {
		var last = o.id.toString();
	
		var sUrl = "/superstore/xpi/" + lastDigit(last) + "/xpi" + o.id + ".htm";
//		openWindow(sUrl, "ilabel", 720, 480, true, false);
		var oWin = openWindow(sUrl, "ilabel", 720, 480, true, false);
		if(oWin) {
			oWin.focus();
		}
	}
}

function lastDigit(id) {
	return id.charAt(7);
}

function ip(id){
	il(id);
	return false;
}

function pp(bpr) {
	PromoPopup(bpr);
	return false;
}

function PromoPopup(bpr) {
	var sURL = "/superstore/product/promo.aspx?prodId=" + bpr;
	var o = openWindow(sURL, "promotion", 600, 300);
	if(o) {
		var oBasket = document.appFrames.basketMain();
		if(oBasket) {
			oBasket.document.productPoPup = o;
		}
	}
}

function productLinkPopup(anchor) {
	var sURL = anchor.href;
	var o = openWindow(sURL, "prodlink", 600, 300);
	if(o) {
		var oBasket = document.appFrames.basketMain();
		if(oBasket) {
			oBasket.document.productPoPup = o;
		}
	}
}

// Shelf popup
function sp(shelfId) {
	var sURL = "/superstore/product/shelf.aspx?shelfId=" + shelfId + "&popup=1";
	var o = openWindow(sURL, "shelf", 600, 300, "no");
	if(o) {
		var oBasket = document.appFrames.basketMain();
		if(oBasket) {
			oBasket.document.productPoPup = o;
		}
	}
	return false;
}

// Shelf popup with the old Product Id passed in.
// This is used to indicate which product to delete once the customer has added a product from the shelf.
function spWithOldProduct(shelfId, oldProductId, oldIsRanged, oldIsDelisted) {
	var sURL = "/superstore/product/shelf.aspx?shelfId=" + shelfId + "&popup=1" + "&oldProductId=" + oldProductId + "&oldIsRanged=" + oldIsRanged + "&oldIsDelisted=" + oldIsDelisted;
	var o = openWindow(sURL, "shelf", 570, 300, "no");
	if(o) {
		var oBasket = document.appFrames.basketMain();
		if(oBasket) {
			oBasket.document.productPoPup = o;
		}
	}
	return false;
}

function ppOfferID(id) {
	PromoPopupOfferID(id);
	return false;
}

function PromoPopupOfferID(id) {
	var sURL = "/superstore/product/promo.aspx?offerId=" + id;
	var o = openWindow(sURL, "promotion", 570, 300);
	if(o) {
		var oBasket = document.appFrames.basketMain();
		if(oBasket) {
			oBasket.document.productPoPup = o;
		}
	}
}

// ------------------------------------------------------------------------------------------------------------------------------

function _isDirty(productList) {
	var o = document.products.items;
	var bReturn = false;

	for(var i = 0; i < o.length; i++) {
		if(o[i].isDirty()) {
			bReturn = true;
			if(productList) {
				productList[productList.length] = o[i];
			} else {
				break;
			}
		}
	}

	return bReturn;
}

document.isDirty = _isDirty;
document.checkedIsDirty = false;

if(document.pageType != "PBASKET") {
	attachEventHandler(window, "beforeunload", checkIsDirty);
}

function checkIsDirty() {
	if(!document.checkedIsDirty) {
		document.checkedIsDirty = true;
		var userAgent = navigator.userAgent.toUpperCase();
		if(bDisableClientBasket || (document.pageType == "FULLBASKET" && !document.suppressIsDirtyTest) || (userAgent.indexOf("MAC") == -1 && userAgent.indexOf("MSIE 5.0") != -1 && !document.suppressIsDirtyTest)) {
			if(document.isDirty()) {
				if(document.pageType == "FULLBASKET") {
					alert("You have changed the quantities of some products or entered a note and then left the page without clicking 'add'.\n\nAs a result these changes have been lost.\n\nTo make these changes you will have to navigate back to your basket page, repeat them, then confirm by clicking 'add'.");
				} else {
					alert("You have changed the quantities of some products or entered a note and then left the page without clicking 'add'.\n\nAs a result these changes have been lost.\n\nTo make these changes you will have to navigate back to the page, repeat them, then confirm them by clicking 'add'.");
				}
			}
		} else {
			if(!document.suppressIsDirtyTest) {
				var oProduct;
				var o = new Array()
				if(document.isDirty(o)) {
					if(confirm("You changed the quantities of some products or entered a note on this page and didn't click 'add'.\n\nDo you want to add these to your basket now?\n\nPress 'OK' to add these products or 'Cancel' to discard.")) {
						document.leavingPage = true;
						for(var i = 0; i < o.length; i++) {
							if(o[i].isDirty()) {
								oProduct = _updateProduct(o[i].id);
								if(oProduct) {
	//								if(document.pageType != "FULLBASKET") {
										a(oProduct.id, null, null, true, true);
	//								} else {
	//									oProduct.add(oProduct.qty, true);
	//								}
								}
							}
						}
					}
				}
			
				// check for any product that have not been added because the window has closed before the add timeout...
				o = document.products.items;
				var oQty;
				var oBasket = document.appFrames.basketMain();
				if(oBasket) {
					for(var i = 0; i < o.length; i++) {
						if(o[i].addProductsTimer) {
							clearTimeout(o[i].addProductsTimer);
							oProduct = _updateProduct(o[i].id);
							if(oProduct) {
								if(oBasket) {
									oQty = oBasket.document.getElementById("i" + oProduct.id + "-q");
									if(oQty) {
										oProduct.add(parseFloat(oQty.innerHTML), true);
									}
								}
							}
						}
					}
				}
			}
		}
	}
}

function switchImages(cBox) {
	checkIsDirty();
	document.suppressIsDirtyTest = true;
	
	var oldUrl = window.location.href;
	var flag = cBox.checked ? "true" : "false";
	queryString().item("displayImages").value = flag;
	queryString().item("withImagesOnPage").value = flag;
	window.location.href = queryString().toString();
	
	return true;
}

function switchPagination(cBox) {
	checkIsDirty();
	document.suppressIsDirtyTest = true;
	
	var oldUrl = window.location.href;
	var flag = cBox.checked ? "1" : "-1";
	queryString().item("pageNumber").value = flag;
	window.location.href = queryString().toString();
	
	return true;
}

function changePagination(pageno) {
	checkIsDirty();
	document.suppressIsDirtyTest = true;
	
	var oldUrl = window.location.href;
	var flag = pageno;
	queryString().item("pageNumber").value = flag;
	window.location.href = queryString().toString();
	
	return true;
}


function pU() {
	if (document.basketTimeout != 0)  {
		clearTimeout(document.basketTimeout);
	}

	document.basketTimeout = setTimeout("_permUpdateSubmit()", iProductButtonsTimeout);

	return false;
}

function _permUpdateSubmit(retry) {
	if(bDisableClientBasket) {
		clearTimeout(document.basketTimeout);
		pBasketTimeout = 0;
		var oBasket = document.appFrames.basketMain();
	
		var pBasketQString = "?from=" + _getFromString() + "&ao=update";
		for (var i = 0; i<p.items.length; i++) {
			var o = p.items[i];
			pBasketQString += "&bpr=" + o.id;
			pBasketQString += "&qty=" + o.qty;
		}
	
		var sUrl = "/superstore/basket/perm.aspx" + pBasketQString;
	
		if(oBasket) {
			oBasket.location.href = sUrl;
		}
	} else {
		clearTimeout(document.basketTimeout);
	
		var pBasketQString = "?from=" + _getFromString();
		var sUpdateList = "";
		var oItem, oQty, oPrice, bUpdate;
	
		for (var i = 0; i< p.items.length; i++) {
			var o = p.items[i];
			var sDisplay = "";
			oItem = document.getElementById("i" + o.id + "-b");
			if(!o.originalQty || (o.originalQty != o.qty) || oItem.getAttribute("error") == "ERROR") {
				bUpdate = false;
				if(oItem) {
					if(oItem.getAttribute("error") == "ERROR" && ((oItem.getAttribute("status") == "CHANGED") || retry)) {
						if(!o.originalQty) {
							// Update the o object
							oQty = document.getElementById("i" + o.id + "-q");
							if(oQty) {
								oItem.setAttribute("status", "READY");
								oItem.setAttribute("updateMode", "ADD");
								oItem.setAttribute("error", null);
								document.basketProductServerQty["i" + o.id] = null;
								o.qty = oQty.innerHTML;
	
								oPrice = document.getElementById("i" + o.id + "-p");
								if(oPrice) {
									o.note = oPrice.getAttribute("note");
									o.subs = oPrice.getAttribute("subs");
									o.subsText = oPrice.getAttribute("subsText");
									o.desc = oPrice.getAttribute("desc");
								}
								
								o.add(o.qty, true, retry);
							}
						} else{
							pBasketQString += "&bpr=" + o.id;
							pBasketQString += "&qty=" + o.qty;
							bUpdate = true;
						}
					} else if(oItem.getAttribute("status") == "CHANGED") {
						pBasketQString += "&bpr=" + o.id;
						pBasketQString += "&qty=" + o.qty;
						bUpdate = true;
					}
	
					oQty = document.getElementById("i" + o.id + "-q");
					if(oQty) {
						if(parseFloat(oQty.innerHTML) <= 0) {
							sDisplay = "none";
						} else {
							sDisplay = "block";
						}
						if(oItem.style.display != sDisplay && retry) {
							oItem.style.display = sDisplay;
//							_checkForProductErrors(document, o.id);
						}
					}
	
	 				if(bUpdate) {
	 					oItem.setAttribute("status", "UPDATE");
						sUpdateList += (o.id + ":" + o.qty + ",");
						
						if(bDebugMode) {
							oItem.className = "update";
						} else {
							oItem.className = "";
						}
	 				}
				}
			}
		}
	
		_displayEmptyBasketMessage();
		
		if(sUpdateList) {
			pBasketQString += "&ao=update";
	
			if(retry) {
				pBasketQString += "&R=1";
			}
	
			var sUrl = "/superstore/basket/add.aspx" + pBasketQString;
		
			var iIndex;
			for(var i = 0; i < document.pUpdateList.length; i++) {
				if(document.pUpdateList[i] == null) {
					iIndex = i;
					break;
				}
			}
			if(!iIndex) {
				iIndex = document.pUpdateList.length - 1;
				if(iIndex < 0) {
					iIndex = 0;
				}
			}
			
			document.pUpdateList[iIndex] = new Image();
			document.pUpdateList[iIndex].onerror = new Function("_permUpdateSubmit_error('" + sUpdateList + "', " + iIndex + ")");
			document.pUpdateList[iIndex].onload = new Function("_permUpdateSubmit_success('" + sUpdateList + "', " + iIndex + ")");
			var d = new Date();
			document.pUpdateList[iIndex].src = sUrl + "&ts=" + d.getTime();
		}
		if(retry) {
			_calculateTotal(document);
		}
	}
}

function _permUpdateSubmit_success(productList, index) {
	if(!isNaN(index)) {
		document.pUpdateList[index] = null;
	}

	var oList = productList.split(",");
	var oP, sUpdateMode;
	for(var i = 0; i < oList.length; i++) {
		if(oList[i]) {
			oP = oList[i].split(":");
			document.basketProductServerQty["i" + oP[0]] = oP[1];
			_clearBasketError(oP[0]);
			oItem = document.getElementById("i" + oP[0] + "-b");
			if(oItem) {
				sUpdateMode = oItem.getAttribute("updateMode");
				oItem.setAttribute("updateMode", null);
				oItem.setAttribute("error", "");
				if(oItem.getAttribute("status") != "CHANGED") {
					if(bDebugMode) {
						if(oItem.className != "checked") {
							oItem.className = "";
						}
					} else {
						oItem.className = "";
					}
					oItem.setAttribute("status", "READY");
					if(oP[1] <= 0 && sUpdateMode != "ADD") {
						oItem.style.display = "none";
					}
				}
			}
			if(sUpdateMode == "UPDATE" || oP[1] <= 0) {
				var o = document.products.item(oP[0]);
				if(o) {
					o.originalQty = null;
				}
			}
		}
	}
	_checkRetry();

	checkForWarnings();
}

function _permUpdateSubmit_error(productList, index) {
	if(!isNaN(index)) {
		document.pUpdateList[index] = null;
	}
	var oList = productList.split(",");
	for(var i = 0; i < oList.length; i++) {
		if(oList[i]) {
			var oP = oList[i].split(":");
			var o = document.products.item(oP[0]);
			if(o) {
				if(!o.userEvent) {
					o.userEvent = new userEvent();
				}
				o.originalQty = o.qty = document.basketProductServerQty["i" + oP[0]];
				o.price = null;
				_setBasketError(o.id);

				var oItem = document.getElementById("i" + o.id + "-b");
				if(oItem) {
					oItem.setAttribute("updateMode", null);
					oItem.setAttribute("status", "READY");
					oItem.setAttribute("error", "ERROR");
					oItem.className = "";
				}
			}
		}
	}
	_checkRetry();
	var oBasket = document.appFrames.basketMain();
	if(oBasket) {
		_calculateTotal(oBasket.document);
	}
}






function trackBuyList(from, itemList, offerText, listId, headerId, footerId, suppressPopup, specialOffer, altImagePath, isListId) {
	return displayBuyList(itemList, offerText, listId, headerId, footerId, suppressPopup, specialOffer, altImagePath, from, isListId);
}

function displayBuyList(itemList, offerText, listId, headerId, footerId, suppressPopup, specialOffer, altImagePath, from, isListId) {
	var sUrl = "/superstore/product/list.aspx";
	
	if(isListId) {
		sUrl += "?id=" + itemList;
	} else {
		sUrl += "?items=" + itemList;
	}
	
	if(offerText) {
		sUrl += ("&sOffer=" + escape(offerText.URLEncode()));
	}
	if(listId) {
		sUrl += ("&listId=" + escape(listId));
	}
	if(headerId && headerId != '') {
		sUrl += ("&headerId=" + headerId);
	}
	if(footerId && footerId != '') {
		sUrl += ("&footerId=" + footerId);
	}
	if(specialOffer == '1') {
		sUrl += "&specialOffer=1";
	} else {
		sUrl += "&specialOffer=0";
	}
	if(!suppressPopup) {
		sUrl += ("&popup=1");
	}
	if(altImagePath && altImagePath != '') {
		sUrl += ("&altImgPath=" + altImagePath);
	}

	if(typeof(from) != "undefined") {
		sUrl = "/r/?from=" + from + "&url=" + sUrl;
	} 
	if(suppressPopup) {
		var sTarget = "mainContentRight";
		if(checkUrl(new urlData(document, sUrl, sTarget))) {
			// the target frame currently exists...
			var oTarget = document.appFrames.locateFrame(sTarget);
			if(oTarget) {
				oTarget.location.href = sUrl;
			}
		}
	} else {
		var oWin = openWindow(sUrl, "buylist", 570, 300);
		if(oWin) {
			oWin.focus();
			var oBasket = document.appFrames.basketMain();
			if(oBasket) {
				oBasket.document.productPoPup = oWin;
			}
		}
	}

	return false;
}

function _getFromString(product) {
	var sFrom = "";
	if(product && product.pageType) {
		sFrom = product.pageType;
		if(product.listId) {
			sFrom += ("-" + product.listId);
		}
	} else if(document.pageType) {
		// If a pageType is specified, use it.
		sFrom = document.pageType;
		if(document.pageType == "TOPNAV") {
			var oMain = document.appFrames.mainContentRight();
			if(oMain && oMain.document.pageType) {
				sFrom = oMain.document.pageType;
			}
		}
	} else {
		// Otherwise, get the info from the pathname
		sFrom = document.location.pathname;
		
		if(sFrom.charAt(sFrom.length - 1) == "/") {
			sFrom = sFrom.substr(0, sFrom.length - 1);
		}
		sFrom = sFrom.substr(sFrom.lastIndexOf("/") + 1);
		if(sFrom.lastIndexOf(".") != -1) {
			sFrom = sFrom.substr(0, sFrom.lastIndexOf("."));
		}
	}

	sFrom = sFrom.toUpperCase();
	
	if(sFrom == "BUYLIST" && !product) {
		var o = new queryString(document.href);
		var sListId = o.item("listId").value;
		if(sListId) {
			sFrom += ("-" + sListId);
		}
	}
	
	return escape(sFrom);
}

function setNotesButtonState(p, addText, setInBasketIndicator) {
	var o = document.getElementById("i" + p.id + "-n");
	if(o) {
		if(addText) {
			o.innerHTML = "Write a note";
		} else {
			o.innerHTML = "Edit your note";
		}
		if(setInBasketIndicator) {
			_setInBasketIndicator(p.id);
		}
	}
}
document.setNotesButtonState = setNotesButtonState;

function updateProductButton(o, doc) {
	if (!doc)
		doc = document;
	if (doc.pageType != 'FULLBASKET') {
		return;
	}
	var strImgPath;
	if (o.isDirty()) {
		strImgPath = '/superstore/i/b/btnConfirm.gif';
	} else {
		strImgPath = '/superstore/i/b/btnConfirmGrey.gif';
	}
	var btn;
	btn = doc.getElementById('i'+o.id+'-a');
	
	
	if (btn != null)
		btn.src = strImgPath;
}

function initBasketPage() {
	var sShelfId = queryString().item("shelfId").value;
	if(sShelfId) {
		updateAdvert(sShelfId.trim(), 3);
	}
	
	document.pageInitialised = true;
	var o = document.appFrames.mainContentRight();
	if(o && o.onBasketLoad) {
		o.onBasketLoad();
	}
}














// Background update support (from top frame) ------------------------------------------------------------------------------------------------------------------------------

function _top_addProduct(id, qty, amend, retry) {
	var o = _getAddProductItem(document, id);
	_addProduct(o, qty, amend, retry)
}

function _addProduct(o, qty, amend, retry) {
	try {
		if(o.status == "READY") {
			o.status = "ADDING";
			if(!o.addImg) {
				o.addImg = new Image();
			}
			
			_displayBasketStatusMessage(o.id)
			
			o.addImg.onerror = new Function("products_add_error(" + o.id + ")");
			o.addImg.onload = new Function("products_add_success(" + o.id + ")");
		
			if(!o.userEvent) {
				o.userEvent = new userEvent;
			}
			
			o.userEvent.event = "add";
			o.userEvent.value = qty;
						
			var sQS = "";
			if(o.mode == "iv") {
				sQS = "&mode=" + o.mode + "&ao=iv";
			} else if(amend && amend != "undefined") {
				sQS = "&ao=amend";
			}
			if(retry && retry != "undefined") {
				sQS += "&R=1";
			}
			var d = new Date();
			o.addImg.src = "/superstore/basket/add.aspx?from=" + _getFromString(o) + sQS + "&" + _buildAddUrl(o, o.voucherId, qty) + "&ts=" + d.getTime();
		} else {
			// add event to array...
			if(!o.userEvents) {
				o.userEvents = new userEvents();
			}
			o.userEvents.add("add", qty);
		}
	} catch(e) {
//		alert("DEBUG: _addProduct: " + e);
	}
}

function _top_createProduct(o) {
	return new product(o);
}





function _basket_setBasketStatusTimer() {
	if(!document.basketStatusTimer && bDoFullSync) {
		document.basketStatusTimer = setTimeout("_basket_getBasketStatus()", iBasketStatusTimeout);
	}
}

function _basket_getBasketStatus() {
	var o = document.getElementById("basketStatus");
	if(o) {
		var d = new Date();
		document.basketStatusTimeStamp = d.getTime();
		o.src = "/superstore/basket/add.aspx?ao=status&ts=" + document.basketStatusTimeStamp;
	}
}

document.basketStatusComplete = _basket_getBasketStatusComplete;

function _basket_getBasketStatusComplete() {
	var bUpdateStatus = false;
	try {
		var o = document.getElementById("basketStatus");
		var oStatusWindow = o.contentWindow;
		if(!oStatusWindow) {
			if(document.frames && document.frames.basketStatus) {
				oStatusWindow = document.frames.basketStatus;
			} else {
				oStatusWindow = o;
			}
		}
		
		if(oStatusWindow) {
			var bCheckStatus = false;
			try {
				if(oStatusWindow.document.title == "BASKET_STATUS") {
					bCheckStatus = true;
				}
			} catch(e) {
				bCheckStatus = false;
			}

			if(bCheckStatus) {
				if(!document.imagesOn) {
					alert("You must have images turned on to use this website");
					return;
				}
				
				var oList = document.getElementById("b");
				if(oList) {
					var oDocStatus = oStatusWindow.document;
					if(oDocStatus) {
						var oItem;
						// sync the visual basket to the status basket...
						var oStatusItemQty, sId, oBasketItemQty, oBasketItemPrice;
						for(var i = 0; i < oList.childNodes.length; i++) {
							oItem = oList.childNodes[i];
							if(oItem.id.substring(oItem.id.length - 2) == "-b") {
								if((!oItem.getAttribute("updateTimeStamp") || (oItem.getAttribute("updateTimeStamp") <= document.basketStatusTimeStamp)) && (!oItem.getAttribute("status") || (oItem.getAttribute("status") == "READY"))) {
									sId = oItem.getAttribute("productId");
									if(sId) {
										oStatusItemQty = oDocStatus.getElementById("i" + sId + "-q");
										if(oStatusItemQty) {
											oItem.setAttribute("serverQty", oStatusItemQty.innerHTML);
											oBasketItemQty = document.getElementById("i" + sId + "-q");
											if(oItem.getAttribute("error") != "ERROR") {
												if(oBasketItemQty && (parseFloat(oStatusItemQty.innerHTML) != parseFloat(oBasketItemQty.innerHTML))) {
													oBasketItemQty.innerHTML = oStatusItemQty.innerHTML;
			
													oBasketItemPrice = document.getElementById("i" + sId + "-p");
													if(oBasketItemPrice) {
														if(oBasketItemPrice.getAttribute("price")) {
															oBasketItemPrice.innerHTML = formatNumber(parseFloat(oBasketItemPrice.getAttribute("price")) * parseFloat(oStatusItemQty.innerHTML), 2);
														}
													}
												}
											}
											if(bDebugMode) {
												if(oItem.className != "error" && oItem.className != "error-last") {
													oItem.className = "checked";
												}
											}
											_setInBasketIndicator(sId);
										} else {	// item no longer in the basket...
											oItem.setAttribute("serverQty", null);
											if(oItem.getAttribute("error") != "ERROR") {
												oItem.setAttribute("error", "");
												oItem.style.display = "none";
												oBasketItemQty = document.getElementById("i" + sId + "-q");
												if(oBasketItemQty) {
													oBasketItemQty.innerHTML = "0";
												}
											}
											_setInBasketIndicator(sId);
										}
									} else {
//										alert("DEBUG: _basket_getBasketStatusComplete: unable to find " + sId);
									}
								} else {
									bUpdateStatus = true;
								}
							}
						}

						var oStatusList = oDocStatus.getElementById("b");
						if(oStatusList) {
							// sync the status basket to the visual basket...
							var oItem, sPrice, sDesc, sQty, oI, bLooseWeight, step;
							for(var i = 0; i < oStatusList.childNodes.length; i++) {
								var sId = oStatusList.childNodes[i].getAttribute("productId");
								if(sId) {
									oItem = document.getElementById("i" + sId + "-b");
									if(!oItem || (oItem.style.display == "none" && (!oItem.getAttribute("status") || oItem.getAttribute("status") == "READY"))) {
										if(!oItem) {
											oItem = document.createElement("li");
											oItem.id = "i" + sId + "-b";
											oItem.setAttribute("productId", sId);
											oList.appendChild(oItem);
										}
										if(oItem) {
											sPrice = "";
											sDesc = ""
											sQty = ""
											oItem.style.display = "block";
											oI = oDocStatus.getElementById("i" + sId + "-p");
											if(oI) {
												sPrice = oI.innerHTML;
											}
											oI = oDocStatus.getElementById("i" + sId + "-d");
											if(oI) {
												sDesc = oI.innerHTML;
											}
											oI = oDocStatus.getElementById("i" + sId + "-q");
											if(oI) {
												sQty = oI.innerHTML;
												oItem.setAttribute("serverQty", sQty);
											}
											if(bDebugMode) {
												oItem.className = "new";
											}
											
											bLooseWeight = oStatusList.childNodes[i].getAttribute("loose");
											step = 1;
											if(bLooseWeight) {
												step = 0.1;
												oItem.setAttribute("loose", "true");
											}
											oItem.innerHTML = _buildBasketProductHTML(sId, sQty, sDesc, sPrice, sPrice, step, bLooseWeight);
											_setInBasketIndicator(sId);
										}
									}
								}
							}
						}
					}
					
					_calculateTotal(document);
					
					if(bUpdateStatus) {
						document.basketStatusTimer = setTimeout("_basket_getBasketStatus()", iBasketStatusItemsChangedTimeout);
					}
				}
			}
		}
	} catch(e) {
//		alert("DEBUG: _basket_getBasketStatusComplete: " + e);
	} finally {
		_displayEmptyBasketMessage();

		if(!bUpdateStatus) {
			document.basketStatusTimer = null;
		}
	}
}

function _showBasketErrors(oList) {
	var iErrorCount = 0;
	for(var i = 0; i < oList.childNodes.length; i++) {
		oItem = oList.childNodes[i];
		if(oItem.id.substring(oItem.id.length - 2) == "-b" && oItem.getAttribute("error") == "ERROR") {
			if(oItem.style.display != "block") {
				oItem.style.display = "block";
			}
			iErrorCount++;
		}
	}
	
	return iErrorCount;
}

function _buildBasketProductHTML(id, qty, desc, price, totalPrice, step, looseWeighIndicator, product) {
	if(!step) {
		step = 1;
	}
	var weightIndicator = "", weightIndicatorAttribute = "";;
	if(looseWeighIndicator) {
		weightIndicator = "kg";
		weightIndicatorAttribute = " loose=\"true\"";
	}
	var sAttributes = "";
	if(product) {
		sAttributes = " desc=\"" + product.desc + "\"";
		sAttributes += " note=\"" + product.note + "\"";
		sAttributes += " subs=\"" + product.subs + "\"";
		sAttributes += " subsText=\"" + product.subsText + "\"";
	}
	return "<table class=\"bL\"><tr><td class=\"qty-m\"><a href=\"#\" onclick=\"d(" + id + ", " + step + ", true); return pU();\" ondblclick=\"if(this.attachEvent)this.onclick()\"><img src=\"/superstore/i/b/ms.gif\" alt=\"-\" /></a></td><td class=\"qty\"><span id=\"i" + id + "-q\">" + qty + "</span> " + weightIndicator + "</td><td class=\"qty-p\"><a href=\"#\" onclick=\"i(" + id + ", " + step + ", true); return pU();\" ondblclick=\"if(this.attachEvent)this.onclick()\"><img src=\"/superstore/i/b/ps.gif\" alt=\"+\" /></a></td><td class=\"bI\"><a name=\"i" + id + "\" id=\"i" + id + "\"></a>" + desc + "</td><td class=\"iP\" id=\"i" + id + "-p\" price=\"" + price + "\"" + weightIndicatorAttribute + sAttributes + ">" + totalPrice + "</td></tr></table>";
}

function _showRetryMessage(errorCount, doc) {
	var o = doc.getElementById("retryMessage");
	if(!o) {
		var oBasketDiv = doc.getElementById("basket");
		if(oBasketDiv) {
			var oBasketList = doc.getElementById("b");
			if(oBasketList) {
				o = doc.createElement("div");
				o.id = "retryMessage";
				o.innerHTML = "<p><strong>Sorry, there was a problem updating your basket.</strong></p><p>Do you want to try again?</p><input type=\"image\" id=\"retryMessage-retry\" src=\"/superstore/i/b/btnYes.gif\" onclick=\"_basketRetry()\" alt=\"Yes\"/><input type=\"image\" id=\"retryMessage-cancel\" src=\"/superstore/i/b/btnNo.gif\" onclick=\"_basketCancel()\" alt=\"No\"/><div style=\"clear:both\"></div>";
				oBasketDiv.insertBefore(o, oBasketList);
			}
		}
	}
	
	if(o) {
		if(o.style.display != "block") {
			o.style.display = "block";
			var oMsg = doc.getElementById("guide-price-msg");
			if(oMsg) {
				oMsg.style.display = "none";
			}
		}
	}
}

function _hideRetryMessage(doc) {
	var o = doc.getElementById("retryMessage");
	if(o) {
		o.style.display = "none";
		var oMsg = doc.getElementById("guide-price-msg");
		if(oMsg) {
			oMsg.style.display = "block";
		}
	}
}

function _basketRetry() {
	_hideRetryMessage(document);
	
	// Ensure any new products are added to the product list object...
	var oList = document.getElementById("b");
	var sId, oProduct, oPrice, sPrice;
	if(oList) {
		for(var i = 0; i < oList.childNodes.length; i++) {
			if(oList.childNodes[i].getAttribute("error") == "ERROR") {
				sId = oList.childNodes[i].getAttribute("productId");
				if(sId) {
					oProduct = _updateProduct(sId);
					oPrice = document.getElementById("i" + sId + "-p");
					if(oPrice) {
						sPrice = oPrice.getAttribute("price");
						if(sPrice) {
							oProduct.price = sPrice;
						}
					}
				}
			}
		}
	}
	
	if(document.basketStatusTimer) {
		clearTimeout(document.basketStatusTimer);
	}
	document.basketStatusTimer = null;

	_permUpdateSubmit(true);
	var o = document.getElementById("bs");
	if(o) {
		o.click();
	}
}

function _basketCancel() {
	_hideRetryMessage(document);

	var oList = document.getElementById("b");
	var sId, oProduct, qty, oItem, oQty, sPrice;
	if(oList) {
		for(var i = 0; i < oList.childNodes.length; i++) {
			oItem = oList.childNodes[i];
			if(oItem.getAttribute("error") == "ERROR" && oItem.getAttribute("status") != "CHANGED") {
				sId = oItem.getAttribute("productId");
				if(sId) {
					qty = oItem.getAttribute("serverQty");
					if(!qty) {
						qty = document.basketProductServerQty["i" + sId];
					}
					if(qty && qty > 0) {
						oQty = document.getElementById("i" + sId + "-q");
						if(oQty) {
							oQty.innerHTML = qty;
							var oPrice = document.getElementById("i" + sId + "-p");
							if(oPrice) {
								sPrice = oPrice.getAttribute("price");
								oPrice.innerHTML = formatNumber((parseFloat(sPrice) * parseFloat(qty)), 2);
							}
							if(bDebugMode && oItem.getAttribute("serverQty")) {
								oItem.className = "checked";
							} else {
								oItem.className = "";
							}
							oItem.setAttribute("error", null);
							_setInBasketIndicator(sId);
						}
					} else {
						oQty = document.getElementById("i" + sId + "-q");
						if(oQty) {
							oQty.innerHTML = "0";
						}
						oItem.setAttribute("error", null);
						oItem.style.display = "none";
						_setInBasketIndicator(sId);
					}
				}
			}
		}
		_calculateTotal(document);
		_displayEmptyBasketMessage();
	}

	if(document.basketStatusTimer) {
		clearTimeout(document.basketStatusTimer);
	}
	document.basketStatusTimer = null;
}

function _moveRetryProductLines(doc, sRetryIdList) {
	try {
		var oList = doc.getElementById("b");
		if(oList) {
			var oFirst;
			for(var i = 0; i < oList.childNodes.length; i++) {
				if(oList.childNodes[i].getAttribute("error") != "ERROR") {
					oFirst = oList.childNodes[i];
					break;
				}
			}

			var oIds = sRetryIdList.split(",");
			var o, oItemCopy, oItem;
			for(var i = 0; i < oIds.length; i++) {
				if(oIds[i] != "") {
					o = doc.getElementById("i" + oIds[i] + "-b");
					if(o.previousSibling && o.previousSibling.getAttribute("error") != "ERROR") {
						oItemCopy = o.cloneNode(true);
						oList.removeChild(o);
						if(oFirst) {
							oItem = oList.insertBefore(oItemCopy, oFirst);
						} else {
							oItem = oList.appendChild(oItemCopy);
						}
					} else {
						oItem = o;
					}
					if(oItem) {
						if(i != oIds.length - 2) {
							oItem.className = "error";
						} else {
							oItem.className = "error-last";
						}
						if(oItem.style.display != "block") {
							oItem.style.display = "block";
						}
					}
				}
			}
		}
	} catch(e) {
//		alert("DEBUG: _moveRetryProductLines: " + e);
	}
}

function _checkForProductErrors(doc, id) {
	var oList = doc.getElementById("b");
	var oItem;
	var iErrorCount = 0;
	if(oList) {
		var oLastErrorLine, sId;
		for(var i = 0; i < oList.childNodes.length; i++) {
			oItem = oList.childNodes[i];
			sId = oItem.getAttribute("productId");
			if(sId != id) {
				if(oItem.getAttribute("error") == "ERROR" && oItem.getAttribute("status") == "READY") {
					iErrorCount++;
					if(oItem.className == "error-last") {
						oItem.className = "error";
					}
					oLastErrorLine = oItem;
				} else if(iErrorCount > 0 && oLastErrorLine) {
					oLastErrorLine.className = "error-last";
					break;
				} else {
					break;
				}
			}
		}
	}
	
	if(iErrorCount > 0) {
		_showRetryMessage(iErrorCount, doc);
	} else {
		_hideRetryMessage(doc);
	}
}


function _displayEmptyBasketMessage() {
	var oBasket = document.appFrames.basketMain();
	if(oBasket) {
		var oBasketDoc = oBasket.document;
		var oEmptyMsg = oBasketDoc.getElementById("emptyBasketMessage");
		if(oEmptyMsg) {
			var oList = oBasketDoc.getElementById("b");
			if(oList) {
				var bFound = false;
				for(var i = 0; i < oList.childNodes.length; i++) {
					oItem = oList.childNodes[i];
					if(oItem.id.substring(oItem.id.length - 2) == "-b" && oItem.style.display != "none") {
						bFound = true;
						break;
					}
				}
				if(!bFound) {
					oEmptyMsg.style.display = "block";
				} else {
					oEmptyMsg.style.display = "none";
				}
			}
		}
	}
}

function _checkRetry() {
	if(document.appFrames) {
		var oBasket = document.appFrames.basketMain();
		if(oBasket) {
			var oBasketDoc = oBasket.document;
			var oList = oBasketDoc.getElementById("b");
			if(oList) {
				var iErrorCount = 0;
				var sRetryIdList = "", sId;
				for(var i = 0; i < oList.childNodes.length; i++) {
					oItem = oList.childNodes[i];
					if(oItem.id.substring(oItem.id.length - 2) == "-b" && oItem.getAttribute("error") == "ERROR") {
						iErrorCount++;
						sId = oItem.getAttribute("productId");
						if(sId) {
							sRetryIdList += (sId + ",");
						}
					}
				}
				if(iErrorCount > 0) {
					_showRetryMessage(iErrorCount, oBasketDoc);
				} else {
					_hideRetryMessage(oBasketDoc);
				}
				
				if(sRetryIdList != "") {
					_moveRetryProductLines(oBasketDoc, sRetryIdList);
				}
			}
		}
		_displayEmptyBasketMessage();
	}
}						

function _setInBasketIndicator(id) {
	if(document.appFrames) {
		if(window.opener) {	// sync the source windows from the popup
			_setInBasketIndicatorWindow(id, window);
		} else {
			var oBasket = document.appFrames.basketMain();
			if(oBasket) {
				try {
					if(oBasket.document.productPoPup && !oBasket.document.productPoPup.closed) {
						_setInBasketIndicatorWindow(id, oBasket.document.productPoPup);
					}
				} catch(e) {
				}
			}
		}

		var oMain = document.appFrames.mainContentRight();
		if(oMain) {
			_setInBasketIndicatorWindow(id, oMain);
		} else {
			oMain = document.appFrames.mainContent();
			if(oMain) {
				_setInBasketIndicatorWindow(id, oMain);
			}
		}
	}
}

function _setInBasketIndicatorWindow(id, oMain) {
	var bInbasket = false;
	if(oMain && !document.leavingPage) {
		var oDoc = oMain.document;
		var oProduct;
		if(oDoc.products) {
			oProduct = oDoc.products.item(id);
		}
		var oAddSection = oDoc.getElementById("i" + id + "-ib");
		var oQty = oDoc.getElementById("i" + id + "-q");
		var s = "", sClassName = "p-n";
		var bLooseWeight = false;
		var oItem = oDoc.getElementById("i" + id);
		if(oItem && oAddSection) {
			if(bDisableClientBasket) {
				bInbasket = true;
			} else {
				var oBasket = document.appFrames.basketMain();
				var fTotalQty = 0;
				if(oBasket) {
					var oBasketDoc = oBasket.document;
					var oItemLine = oBasketDoc.getElementById("i" + id + "-b");
					if(oItemLine && oItemLine.style.display != "none") {
						bLooseWeight = (oItemLine.getAttribute("loose") == "true");
						var oBasketQty = oBasketDoc.getElementById("i" + id + "-q");
						if(oBasketQty) {
							fTotalQty = parseFloat(oBasketQty.innerHTML);
							if(fTotalQty > 0) {
								bInbasket = true;
							}
						}
					} else {
						oItemLine = oDoc.getElementById("i" + id + "-b");
						if(oItemLine) {
							bLooseWeight = (oItemLine.getAttribute("loose") == "true");
						}
					}
				}
			}
	
			if(bInbasket) {
			
			//s += "<a href=\"/superstore/basket/perm.aspx#i" + id + "\" target=\"basketMain\"><img src=\"/superstore/i/iconInBasket.gif\" alt=\"In Basket\" /></a>";
			
				if(!bDisableClientBasket) {
					if(bLooseWeight) {
						s += "<strong>" + fTotalQty + "kg in basket</strong>";
					} else {
						s += "<strong>" + fTotalQty + " in basket</strong>";
					}
				} else {
						s += "<strong>in basket</strong>";
				}
				
				sClassName = "p-ib";
			}
			if(oProduct && oProduct.isDirty()) {
				var oQty = oDoc.getElementById("i" + id + "-q");
				if(oQty) {
					var sQty = parseFloat(oQty.value);
					if(bLooseWeight) {
						sQty = formatNumber(oQty.value, 1);
					}
					if(document.showBasketMessage) {
						if(fTotalQty > 0) {
							s = "<div class=\"a\">Click <strong>add</strong> to put <strong>" + sQty + (bLooseWeight ? "kg" : "") + "</strong> more in your basket</div>" + s;
						} else {
							s = "<div class=\"a\">Click <strong>add</strong> to put <strong>" + sQty + (bLooseWeight ? "kg" : "") + "</strong> in your basket</div>" + s;
						}
					}
	
					sClassName = "p-m";
				}
			}
			
			s = "<div class=\"c\">&nbsp;" + s + "</div>";
			
			var oAdd = oDoc.getElementById("i" + id + "-a");
			if(oAdd) {
				var sAddUrl = "/superstore/i/b/btnAdd.gif"
				if(sClassName == "p-m") {
					sAddUrl = "/superstore/i/b/btnAddAmend.gif";
				}
				
				if(oAdd.src != sAddUrl) {
					oAdd.src = sAddUrl;
				}

			}

			if(oAddSection.innerHTML != s) {
				oAddSection.innerHTML = s;
			}
			
			if(oItem.className != sClassName) {
				oItem.className = sClassName;
			}
	
			if(oProduct) {
				oProduct.inBasket = bInbasket;
			}
		}
	}
}

function checkImages() {
	document.checkImage = new Image();
	document.checkImage.onload = _checkImages_img_load;
	var d = new Date();
	document.checkImage.src = "/superstore/basket/success.gif?ts=" + d.getTime();
}

function _checkImages_img_load() {
	document.imagesOn = true;
}

function warningReason(reason, productIds) {
	this.reason = reason;
	this.productIds = productIds;
}

function checkForWarnings() {
	// Ensure _checkForWarnings() is in a new thread so and alerts etc. do not interfere with any rendering within the main frameset...
	setTimeout("_checkForWarnings()", 0);
}

function _checkForWarnings() {
	var sWarningReasons = getApplicationValue("warnings", "SSVars");
	setApplicationValue("warnings", "");

	if(sWarningReasons && sWarningReasons != "") {
		var sWarningReason = sWarningReasons.split("|");
		var sItem;
		var iIndex;
		var sReasons = new Array();
		for(var i = 0; i < sWarningReason.length; i++) {
			sItem = sWarningReason[i].split(":");
			if(sItem.length == 2) {
				iIndex = null;
				for(var ii = 0; ii < sReasons.length; ii++) {
					if(sReasons[ii].reason == sItem[0]) {
						iIndex = ii;
						break;
					}
				}
				if(iIndex == null) {
					sReasons[sReasons.length] = new warningReason(sItem[0]);
					iIndex = sReasons.length - 1;
				}
				
				sReasons[iIndex].productIds = sItem[1];
			}
		}

		var sReasonIds
		var sReasonIdList; // Unique list of ids
		for(var i = 0; i < sReasons.length; i++) {
			sReasonIds = sReasons[i].productIds.split("*");
			sReasonIdList = "";
			for(var ii = 0; ii < sReasonIds.length; ii++) {
				if(sReasonIds[ii] != "") {
					if(sReasonIdList.indexOf("[" + sReasonIds[ii] + "]") == -1) {
						sReasonIdList += ("[" + sReasonIds[ii] + "]*");
					}
				}
			}
			sReasonIds = sReasonIdList.split("*");
			sReasonIdList = "";
			var sReasonLimitQuantityList = "";
			for(var ii = 0; ii < sReasonIds.length; ii++) {
				if(sReasonIds[ii] != "") {
					sReasonIds[ii] = sReasonIds[ii].substr(1, sReasonIds[ii].length - 2);
					sReasonIdList += parseInt(sReasonIds[ii]) + ",";
					if(sReasonIds[ii].indexOf("+") != -1) {
						sReasonLimitQuantityList += sReasonIds[ii].substr(sReasonIds[ii].indexOf("+") + 1) + ",";
					} else {
						sReasonLimitQuantityList += "*" + ",";
					}
				}
			}
			sReasonIdList = sReasonIdList.substr(0, sReasonIdList.length - 1);

			switch(sReasons[i].reason) {
				case "ProductUnranged":
				case "ProductMissing": // NG: 14-06-2005 Added for defect# 15361 CR#618 
					var oBasket = document.appFrames.basketMain();
					var oBasketDoc, sProductList = "", sDesc, iProductCount = 0;
					if(oBasket) {
						oBasketDoc = oBasket.document;
						var oItem, oQty, oLineItems;
						for(var ii = 0; ii < sReasonIds.length; ii++) {
							oItem = oBasketDoc.getElementById("i" + sReasonIds[ii] + "-b");
							if(oItem) {
								oQty = oBasketDoc.getElementById("i" + sReasonIds[ii] + "-q");
								if(oQty) {
									oQty.innerHTML = "0";
								}
								oItem.style.display = "none";
								oLineItems = oItem.getElementsByTagName("td");
								sDesc = "";
								if(oLineItems && oLineItems.length == 5) {
									sDesc = new String(oLineItems[3].innerHTML);
									iIndex = sDesc.indexOf("</a>");
									if(iIndex != -1) {
										sDesc = sDesc.substr(iIndex + 4);
									} else {
										iIndex = oLineItems[3].innerHTML.indexOf("</A>");
										if(iIndex != -1) {
											sDesc = sDesc.substr(iIndex + 4);
										} else {
											iIndex = oLineItems[3].innerHTML.indexOf(">");
											if(iIndex != -1) {
												sDesc = sDesc.substr(iIndex + 1);
											}
										}
									}
								}
								if(sDesc != "") {
									sProductList += (sProductList != "" ? "\n" : "") + sDesc;
									iProductCount++;
								}
							}
						}
						_calculateTotal(oBasketDoc);
						if(iProductCount == 1) {
							alert("Sorry, " + sProductList + " is currently unavailable in your store so we've removed it from your basket.");
						} else if(iProductCount > 1) {
							alert("Sorry, the following products are unavailable in your store so we've removed them from your basket:\n" + sProductList);
						}
					}
					break;
				case "LimitExceeded":
					var idList = sReasonIdList.split(",");
					var qtyList = sReasonLimitQuantityList.split(",");
					var oBasket = document.appFrames.basketMain();
					if(oBasket) {
						var oBasketDoc = oBasket.document;
						var oBasketItemQty, oBasketItemPrice;
	
						for(var i = 0; i < idList.length; i++) {
							if(idList[i] && qtyList[i] != "*") {
								oBasketItemQty = oBasketDoc.getElementById("i" + idList[i] + "-q");
								if(oBasketItemQty) {
									oBasketItemQty.innerHTML = parseInt(qtyList[i]);

									oBasketItemPrice = oBasketDoc.getElementById("i" + idList[i] + "-p");
									if(oBasketItemPrice) {
										if(oBasketItemPrice.getAttribute("price")) {
											oBasketItemPrice.innerHTML = formatNumber(parseFloat(oBasketItemPrice.getAttribute("price")) * qtyList[i], 2);
										}
									}
								}
								_setInBasketIndicator(idList[i]);
							}
						}
						_calculateTotal(oBasketDoc);
					}
	
					var oMain = document.appFrames.mainContent();
					if(oMain) {
						if(oMain.document.limitPopupWin && !oMain.document.limitPopupWin.closed) {
							var o = sReasonIdList.split(",");
							var oPopupList = oMain.document.reasonIdList.split(",");
							var bFound;
							for(var i = 0; i < o.length; i++) {
								bFound = false;
								for(var ii = 0; ii < oPopupList.length; ii++) {
									if(o[i] == oPopupList[ii]) {
										bFound = true;
										break;
									}
								}
								if(!bFound) {
									oMain.document.reasonIdList += ("," + o[i]);
								}
							}
						} else {
							oMain.document.reasonIdList = sReasonIdList;
						}
						oMain.document.limitPopupWin = openWindow("/superstore/product/limitpopup.aspx?bpr=" + oMain.document.reasonIdList, "limit", 550, 300, "scrollbars");
						if(oMain.document.limitPopupWin) {
							oMain.document.limitPopupWin.focus();
						} else {
							if(oMain.document.reasonIdList && oMain.document.reasonIdList.split(",").length > 1) {
								alert("Some items you have added to your basket have a limit on the quantity you can buy. We've reset theses items to the maximum possible quantity.");
							} else {
								alert("The item you have added to your basket has a limit on the quantity you can buy. We've reset this item to the maximum possible quantity.");
							}
						}
					}
					break;
			}
		}
	}	
}

function _stripWeightFromNote(o)
{
	if(o) 
	{
		if(o.weight) 
		{
			var iDelimiterIndex = o.note.indexOf(sWeightDelimiter);
			if (iDelimiterIndex != -1)
			{
				o.note = o.note.substr(iDelimiterIndex + 1);
			}
		}
	}
}
function _addWeightToNote(o)
{
	if(o) 
	{
		if(o.weight && (o.note.indexOf(sWeightDelimiter) == -1)) 
		{
			o.note = o.weight + sWeightDelimiter + o.note;
		}
	}
}


