var srcForm;
var dstForm;
var subWin;
var askedOnceAlready = false;
var showPopup = true;
var isAllProds =false;

function plus(formName, productId, frameObject) {

	var qtyField = null;
	if (frameObject == null) {
		qtyField = document.forms[formName]["qty_" + productId];
	} else {
		qtyField = frameObject.document.forms[formName]["qty_" + productId];
	}

	errFlag = false;
	fieldValue = parseFloat(qtyField.value);

	if (isNaN(fieldValue)) fieldValue = 0;
	if (fieldValue >= 99999) fieldValue = 99999;

	if (errFlag) {
		alert(qtyField.value + " is an invalid value or this action would take its value above 99999");
		qtyField.focus();
		qtyField.select();
	} else {
		fieldValue++;
		qtyField.value = makeProperNumber(fieldValue);
	}
	if (frameObject == null) {
		updateProductProperty(productId,"quantity",qtyField.value);
	}
	return false;
}

function minus(formName, productId, frameObject) {

	var qtyField = null;
	if (frameObject == null) {
		qtyField = document.forms[formName]["qty_" + productId];
	} else {
		qtyField = frameObject.document.forms[formName]["qty_" + productId];
	}

	var errFlag = false;
	var fieldValue = parseFloat(qtyField.value);

	if (isNaN(fieldValue)) fieldValue = 1;
	if (fieldValue < 1) fieldValue = 1;

	if (errFlag) {
		alert(qtyField.value + " is an invalid value or this action would take its value below 0");
		qtyField.focus();
		qtyField.select();
	} else {
		fieldValue -= 1;
		qtyField.value = makeProperNumber(fieldValue);
	}
	if (frameObject == null) {
		updateProductProperty(productId,"quantity",qtyField.value);
	}
	return false;
}

function makeProperNumber(funnyNumber) {
/*	*
	 * Take a float as input. Round it to 2 decimal places.
	 * If the integer is 99 or greater, return the integer,
	 * otherwise return the float.
	 * Return as String.
	 */
//	 Use round to get the integer bit. If float is .5 or greater, this will
//	 round up, so subtract 1 if > number we started with.
//	 alert("The rounded value of " + funnyNumber + " is " + Math.round(funnyNumber));

	wholeBit = 0
	wholeBit = Math.round(funnyNumber);
	if (wholeBit > funnyNumber) wholeBit--;

//	 Just subtract the integer part to get the fraction part
	var fractionBit = funnyNumber - wholeBit;

//	 Multiply fraction by 10 then round to nearest int
	var trueValue = Math.round(fractionBit * 100);

//	 Only return fraction if we are under 100 or if there is a fraction
	if (wholeBit < 100 && fractionBit != 0) {
		return ("" + wholeBit + "." + trueValue);
	} else {
		return ("" + wholeBit);
	}
}

function ProductProperty(prodRefNum, isAnalgesic, quantity, quantityUnit, isSubstitutable, comments, message, isToAdd, qtyInTrolley,dftQtyUnit){
	this.prodRefNum=prodRefNum;
	this.isUpdated=false;
	this.isAnalgesic=isAnalgesic;
	this.isToDelete=false;
	this.quantity=quantity;
	this.quantityUnit=quantityUnit;
	this.origQuantity=quantity;
	this.origQuantityUnit=quantityUnit;
	this.isSubstitutable=isSubstitutable;
	this.comments=unparseHTML(comments);
	this.lineMessage=unparseHTML(message);
	this.isToAdd = false;
	this.qtyInTrolley = qtyInTrolley;
	this.dftQtyUnit = dftQtyUnit;
}

function focusQty(uniqueId){
	with(document.forms['shppngFrm']){
		qtyBox = eval("qty_"+uniqueId);
		qtyBox.focus();
		qtyBox.select();
	}
}

function showQty(uniqueId,qtyVal){
	with(document.forms['shppngFrm']){
		qtyBox = eval("qty_"+uniqueId);
		qtyBox.value=qtyVal;
	}
}

function updateUnit(productId, property, unitDropDown){	// necessary intermediate function for netscape
	var val = unitDropDown.options[unitDropDown.selectedIndex].value;
	updateProductProperty(productId, property, val);
}

//Global update flag
var isListUpdated = false;

function updateProductProperty(productId,property,val){
    //alert("Shopping.js: Updating product property for id" + productId);	
    var prodUpdated = true;
	if(arguments.length<2){property="update";}
	
	product = eval("p"+productId);
	
	switch(property){
		case "delete":
			product.isToDelete=val;
			// Toggle the displayed quantity
			if (val==true){
				showQty(productId,"");
			} else {
				showQty(productId,product.quantity);
			}
			break;
		case "undelete":
			product.isToDelete=false;
			showQty(productId,val);
			updateProductProperty(productId,"quantity",val);
			break;
		case "quantity":
			if(val<0){
				alert("Sorry, you are not allowed to add negative numbers of products to your trolley");
				prodUpdated = false;
				if(isTrolley()){
					val = 0;
				}else{
					val = 1;
					if (product.quantityUnit == "EA"){
						eval("document.forms['shppngFrm'].qty_" + productId + ".value = '1'");
					}else{
						eval("document.forms['shppngFrm'].qty_" + productId + ".value = ''");
					}
				}
				focusQty(productId);
			} else {
				val = val.toString().replace(/ /g, "");
				if(isTrolley() && val.length==0){val=0;};
				if(parseFloat(val)==0) {val=0; }
				if(isNaN(val) || parseFloat(val)<0) {
					alert("Sorry, the quantity is invalid.\nPlease ensure your quantity field is numeric and try again.");
					prodUpdated = false;
					focusQty(productId);
				} else {
					unit = product.quantityUnit;
					if(unit == "EA" && (parseFloat(val) - parseInt(val) != 0)) {
						alert("Please check the required quantity.\nThe quantity for items ordered by 'Each' must be a whole number.");
						prodUpdated = false;
						focusQty(productId);
					}
					delImg = eval("document.images.del_"+productId);
					delImgFound = typeof delImg;
					var elementName="desc_"+productId;
					var descElement = top.frames['trolley'].document.getElementById(elementName);
					if (val==0 && thisListType != shoppingListListType && thisListType != productListType){
						classChange('trolleyDeleted',descElement);
						updateProductProperty(productId,"delete",true);
						return;
					}else if(descElement!=null){ 
						if(val>0 && descElement.className=="trolleyDeleted" && thisListType != shoppingListListType && thisListType != productListType){
							classChange('trolleyNormal',descElement);
							updateProductProperty(productId,"undelete",val);
							return;
						}
					}
					product.quantity=val;
				}
			}
			break;
		case "qtyUnit":
			if (val==product.quantityUnit){return;}
			//focusUnit(productId);
			if (thisListType!=productListType){
				for (j=0; j<weightBasedCodes.length; j++){
					if(weightBasedCodes[j]==val){
						unitDesc = weightBasedDescs[j];
					}else{
						if(weightBasedCodes[j]==product.quantityUnit){
							with(document.forms['shppngFrm']){	// reset the unit
								unitBox = eval("qty_unit_"+productId);
								unitBox.options[j].selected = -1;
								unitBox.focus();
							}
						}
					}
				}
				alert("You already have this product measured in " + unitDesc + ".  Please choose a different unit or delete as appropriate.");
				prodUpdated = false;
				return;
			}
			product.quantityUnit=val;
			break;
		case "comment":
			var commentField = null;
			commentField = document.forms["shppngFrm"]["comments_" + productId];
			if (unescape(val).indexOf("%")>=0){
				alert("Sorry, your special requirements cannot contain the character '%'");
				prodUpdated = false;
				commentField.select();
				return;
			}else if (unescape(val).indexOf("|")>=0){
				alert("Sorry, your special requirements cannot contain the character '|'");
				prodUpdated = false;
				commentField.select();
				return;
			}
			if (val==product.comments){return;}
			//All '+'s must be replaced by '%2B' as otherwise the java URLDecoder.decode method
			//called against the special requirements field will strip them out and put spaces in instead.
			//The replace must occur after the above test for the character '%' as otherwise the
			//test will fail
			product.comments = val.replace('+', '%2B'); 
			break;
		case "lineMsg":
			var greetingField = null;
			greetingField = document.forms["shppngFrm"]["msg_" + productId];
			if (unescape(val).indexOf("%")>=0){
				alert("Sorry, your greeting cannot contain the character '%'");
				prodUpdated = false;
				greetingField.select();
				return;
			}else if (unescape(val).indexOf("|")>=0){
				alert("Sorry, your greeting cannot contain the character '|'");
				prodUpdated = false;
				greetingField.select();
				return;
			}else if (unescape(val).indexOf(">")>=0){
				alert("Sorry, your greeting cannot contain the character '>'");
				prodUpdated = false;
				greetingField.select();
				return;
			}else if (unescape(val).indexOf("<")>=0){
				alert("Sorry, your greeting cannot contain the character '<'");
				prodUpdated = false;
				greetingField.select();
				return;
			}			
			if (val==product.lineMessage){return;}
			//All '+'s must be replaced by '%2B' as otherwise the java URLDecoder.decode method
			//called against the greetings field will strip them out and put spaces in instead.
			//The replace must occur after the above test for the character '%' as otherwise the
			//test will fail
			product.lineMessage = val.replace('+', '%2B'); 
			break;
		case "substitute":
			if (val==product.isSubstitutable){return;}
			product.isSubstitutable=val;
			break;
		case "isToAdd":
			if(val){
				product.isToAdd = true;
			}else{
				product.isToAdd = false;
			}
			break;	
	}	
	// update property (always set to true when use this method)
	if(property!="isToAdd"){
		product.isUpdated=true;
		isListUpdated = true;
	}
	
	return prodUpdated; // break out of loop because product has been found
}

function addProductToTrolleyOnTopMenu(productId, isLoggedIn, substitute){
	var returnVar = false;
	var updateListForm=document.forms["updateListForm"];
	if (typeof substitute == 'undefined') substitute=0;

	updateListForm.dst_list_type.value = trolleyListType;
	updateListForm.dst_list_num.value = 0;
	updateListForm.next_url.value ="/JSPs/shop/trolleyandlogonInter.jsp?siteCode=" +updateListForm.siteCode.value+ "&oldTrolley=true";

	if (isLoggedIn) {		
		if (checkProduct(productId,substitute)){ returnVar = true; }
	} 
	else { // not logged in... 
		if (checkProduct(productId, substitute)){
		 	returnVar = false; 
		}
	}
	return returnVar;
}

function getProvisionalProductDetails(productId){
	product = eval("p" + productId);
	var retString='';

	if (typeof(fhSearchTerm)!='undefined' && Boolean(fhSearchTerm)){ retString+='fh_search='+fhSearchTerm+'|'; }
	if (typeof(openCategory)!='undefined' && openCategory!=-1){ retString+='open_category='+openCategory+'|'; }
	if (typeof(jotterResults)!='undefined' && jotterResults){ retString+='jotterResults=true|'; }
	retString+='product_rn='+product.prodRefNum+'|';
	retString+='qty='+product.quantity+'|';
	retString+='qty_unit='+product.quantityUnit+'|';
	retString+='substitute='+0+'|';
	retString+='src_list_num='+0+'|';
	retString+='src_list_type='+productListType+'|';
	retString+='dst_list_type=6'+'|';
	retString+='dst_list_num=0'+'|';
	retString+='add_more=N';
	return retString;
}

function checkProduct(productId, subst){
	product = eval("p" + productId);
	unit = product.quantityUnit;	
	var returnVar = false;	

	if (validateQtys(productId)) {
		with (document.forms["updateListForm"]){
			product_rn.value=product.prodRefNum;
			qty.value=product.quantity;
			qty_unit.value=unit;
			comments.value=product.comments;
			lineMessage.value=product.lineMessage;
			substitute.value=subst;
			src_list_num.value = 0;
			src_list_type.value = productListType;
			
			if (dst_list_type.value == trolleyListType){
				if (!isLoggedIn){
					SetSessionCookie('provisionalTrolley', getProvisionalProductDetails(productId));				
					next_url.value ='/JSPs/shop/home_page.jsp';
					target='_top';
				}
				else {		
					target="trolley";
				}
				submit();
			}else{
				if (dst_list_type.value == shoppingListListType){
					newWin = openSubWindow("/wdeliver/servlet/JSPs/shop/list_operation.jsp?action=addToList&siteCode=" + siteCode.value);
					next_url.value="/JSPs/shop/list_operation.jsp?action=listSaved&siteCode=" + siteCode.value+ "&source=" + productListType;
				}else{
					if (dst_list_type.value == orderListType){
						newWin = openSubWindow("/wdeliver/servlet/JSPs/shop/list_operation.jsp?action=addToOrder&siteCode=" + siteCode.value);
						next_url.value="/JSPs/shop/list_operation.jsp?action=orderSaved&siteCode=" + siteCode.value+ "&source=" + productListType;
					}else{
						alert("Invalid destination list type!");
					}
				}
				target = "SubmissionWindow";
				err_url.value="/JSPs/shop/list_operation.jsp?action=problem&siteCode=" + siteCode.value +"&oldTrolley=true";
				submit();
			}
		}
		returnVar = true;
	}
	if (unit == "EA"){
		product.quantity = "1";		
		eval("document.forms['shppngFrm'].qty_" + productId + ".value = '1'");
	}else{
		product.quantity = "";
		eval("document.forms['shppngFrm'].qty_" + productId + ".value = ''");
	}
	return returnVar;
}

function validateQtys(productId){
	var qty = eval("document.forms['shppngFrm'].qty_" + productId + ".value");
	var noQuantity = false;
	var prevAnalge = top.frames["trolley"].analgesic;
	var test = (parseFloat(prevAnalge) + parseFloat(qty));
	var desc = '';

	if(isNaN(qty) || parseFloat(qty) < 0) {
		alert("Sorry, your quantity is invalid.\nPlease ensure your quantity field is numeric and try again.");
		return false;
	}
	if (qty=="") {
		product.quantity=1;
		noQuantity = true;
	}
	else{
		product.quantity=qty;
	}
	if (parseFloat(qty)==0) {
		alert("You cannot add zero items");
		return false;
	}
	if (unit == "EA" && (parseFloat(qty) - parseInt(qty) != 0)) {
		alert("Please check the required quantity.\nThe quantity for items ordered by 'Each' must be a whole number.");
		return false;
	}
	if (product.isAnalgesic && product.quantity > 2){
		alert("You are only allowed to purchase a maximum of 2 analgesic products.  Please order a smaller quantity.");
		return false;
	}
	if (product.isAnalgesic && test>2) {
		alert("You are only allowed to purchase a maximum of 2 analgesic products.");
		return false;
	}
	if (noQuantity && (unit == "KG" || unit == "G" || unit == "LB" || unit == "EA" || unit == "ST")){
		//this block probably never executed now since introduction of 'checkQuantity()' below
		if (unit == "EA") {
			descr = "";
		} else if (unit == "ST") {
			descr = "£";
		} else {
			descr = unit;
		}
		var retVal=confirm("This is a weighed item - do you want to add 1 " + descr + " ?")
		if (subWin){
			if (retVal){ 
				subWin.focus(); 
			} else { 
				subWin.close(); 
			}
		}	
		return retVal;
	}
	return true;
}

function checkQuantity(productId){
	var qty = eval("document.forms['shppngFrm'].qty_" + productId + ".value");
	if (qty=="" && (unit == "KG" || unit == "G" || unit == "LB" || unit == "EA" || unit == "ST")){
		if (unit == "EA") {
			descr = "";
		} else if (unit == "ST") {
			descr = "£";
		} else {
			descr = unit;
		}
		if (!confirm("This is a weighed item - do you want to add 1 " + descr + " ?")){
			return false;
		}
		
		document.shppngFrm['qty_'+productId].value=1;
	}
	return true;
}

function showListsToAddProductFromProductListing(productId,isLoggedIn){
	product = eval("p" + productId);
	unit=product.quantityUnit;
	if (!checkQuantity(productId)){ 
		return;
	}
	
	if(isLoggedIn) {
		document.forms['updateListForm'].product_rn.value = product.prodRefNum;
		document.forms['chooseShoppingList'].productId.value = productId;
		showListWindow(isLoggedIn);
		return;
	}
	else {
		mustBeSignedIn();
//		gotoRegistration();
	}
}

function addProductToList(listRefNum, prodId, isLoggedIn, subPref, listName, listNames){
	with (document.forms['updateListForm']){
		reset();
		if (listRefNum == 0){	
			if(!checkName(listName, listNames)){
				return false;
			}
		}
		dst_list_num.value = listRefNum;
		dst_list_type.value = shoppingListListType;
	}
	checkOrderOnTopMenu(prodId,isLoggedIn, subPref);
}

function checkOrderOnTopMenu(productId, isLoggedIn, subPref) {
	if (isLoggedIn=="true") {
		checkProduct(productId,subPref);
	} else {
		gotoRegistration();
	}
}

function checkName(nameField,nameList){
	var name = trim(nameField.value);
	if (name.length==0){
		alert("You need to give your new list a name.");
		nameField.focus();
		return false;
	}
	if(nameList!=null && nameList != 'undefined'){
		if(nameList=="array"){  // look at the array on the page for the existing list names
			for( var i=0; i<listNames.length; i++ ){
				if( listNames[i]==name){
					alert("You have already used '"+name+"' as a list name. Please choose another.");
					nameField.select();
					nameField.focus();
					return false;
				}
			}
		}else{
			var len = nameList.options.length;
			for( var i=0; i<len; i++ ){
				if( nameList.options[i].text==name){
					alert("You have already used '"+name+"' as a list name. Please choose another.");
					nameField.select();
					nameField.focus();
					nameList = null;
					return false;
				}
			}
			listNames = null;
		}
	}
	if (name.length>28){
		alert("Your list name is too long.  Please shorten it to less than 28 characters");
		nameField.focus();
		return false;
	}
	if (name.indexOf('<') > -1 || name.indexOf('>') > -1 || name.indexOf('%') > -1) {
		alert("Sorry the '<', '>' or '%' are not allowed in your list name.");
		nameField.focus();
		return false;
	}
	document.forms['updateListForm'].dst_list_name.value = name;
	return true;
}

function addProductToOrderFromProdList(orderRefNum, prodId,isLoggedIn, subPref){
	with (document.forms['updateListForm']){
		reset();
		dst_list_num.value = orderRefNum;
		dst_list_type.value = orderListType;
	}
	checkOrderOnTopMenu(prodId,isLoggedIn, subPref);
}

function showListWindow(isLoggedIn){
	if(isLoggedIn){
		openMediumSubWindow();
		document.forms['chooseShoppingList'].submit();
	}else{
		mustbeSignedIn();
//		gotoRegistration();
	}
}

function openProductWindow(url){
	product=window.open(url,"product","toolbar=no,left=160,top=75,status=no,scrollbars=yes,resizable=yes,menubar=no,width=700,height=525");
	parent.focus();
	product.focus();
} 

function replacePage(redirectURL,form,target){
	var submitStr = redirectURL;
	if(submitStr.lastIndexOf("?")!=(submitStr.length-1)){submitStr+="?";}
	var elementsNum = form.length;
	for(var i=0; i<elementsNum ; i++){
		if (i!=0){submitStr += "&";}
		submitStr +=  form.elements[i].name + "=";
		if (ascii_value(form.elements[i].value)!=32) submitStr += form.elements[i].value;
	}
	target.location.replace(submitStr);
}


function openSubWindow(url) {
	if(arguments.length<1) {
		url = "";
	}
	if(isScreenSmall) {
		x=200;
		y=225;
	}else{
		x=260;
		y=225;
	}
	subWin=window.open(url,"SubmissionWindow","toolbar=no,width=400,height=200,screenX="+x+",left="+x+",screenY="+y+",top="+y+",status=no,scrollbars=yes,resize=yes,menubar=no");
	return subWin;
}

function openMediumSubWindow(url) {
	if(arguments.length<1) {
		url = "";
	}
	if(isScreenSmall) {
		x=200;
		y=25;
	}else{
		x=312;
		y=159;
	}
	subWin=window.open(url,"SubmissionWindow","toolbar=no,width=400,height=450,screenX="+x+",left="+x+",screenY="+y+",top="+y+",status=no,scrollbars=yes,resize=yes,menubar=no");
	return subWin;
}

function trim(inputString) {
	if (typeof inputString != "string") { return inputString; }
	var retValue = inputString;
	var ch = retValue.substring(0, 1);
	while (ch == " ") {
		retValue = retValue.substring(1, retValue.length);
		ch = retValue.substring(0, 1);
	}
	ch = retValue.substring(retValue.length-1, retValue.length);
	while (ch == " ") {
		retValue = retValue.substring(0, retValue.length-1);
		ch = retValue.substring(retValue.length-1, retValue.length);
	}
	while (retValue.indexOf("  ") != -1) {
		retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
	}
	return retValue;
}

function ascii_value (c){
	c = c.charAt(0);
	var i;
	for (i=0; i<256; ++i){
		// convert i into a 2-digit hex string
		var h = i.toString(16);
		if (h.length == 1) h = "0" + h;
		// insert a % character into the string
		h = "%" + h;
		// determine the character represented by the escape code
		h = unescape (h);
		// if the characters match, we've found the ASCII value
		if (h == c) break;
	}
	return i;
}

function unparseHTML(inString){
	var charsInForHtml = new Array ("&amp;", "&quot;", "&#039;" ,"&lt;","&gt;","<br>"); 
	var charsOutForHtml = new Array('&','"','\'','<','>','\n');
	
	for(i=0; i<charsInForHtml.length; i++){
		pattern = new RegExp(charsInForHtml[i],"g");
		inString = inString.replace(pattern, charsOutForHtml[i]);
	}
	return inString.toString();
}

function gotoRegistration(){
	alert("You have to be registered and signed in to use this feature");	
} 

function promptToSave(promptForNoChanges,doRefresh,listOp){
	getForms();
	answer = false;
	if(srcForm == null) return true;
	if (srcForm.length==0){ // No products to save
		return true;
	}
	switch(checkListLoop(thisListType)){
		case "OK":
			if(!promptForNoChanges){			
				if (askedOnceAlready == true){					
					answer = false;
				}
				else {
					if (isTrolley()){ msg = "Do you want to save the changes you have made to your trolley?"; }
					else if (isOrder()){ msg = "Do you want to save the changes you have made to this order?"; }
					else{ msg = "Do you want to save the changes you have made to this list?"; }
					answer = confirm(msg);
				}
			}else{
				answer = true;
			}
			if (answer){				
				if(doRefresh){ showLoading(); }
				doSave(doRefresh,listOp);
			}else{ // Reset the form values so that changes are not saved
				if (listOp){
					return false;
				}else{
					dstForm.product_rn.value="";
					dstForm.qty.value="";
					dstForm.qty_unit.value="";
					dstForm.substitute.value="";
					dstForm.comments.value="";
					dstForm.lineMessage.value="";
					dstForm.delete_rn.value="";
					dstForm.delete_unit.value="";					
					clearUpdateFlags();					
					return true;
				}
			}
			break;
		case "unchanged":
			if (promptForNoChanges){
				if (isTrolley()){ msg = "You have not made any changes to your trolley."; }
				else if (isOrder()){ msg = "You have not made any changes to this order."; }
				else{ msg = "You have not made any changes to this list."; }
				alert(msg);
			}
			if (listOp){
				return false;
			}else{
				return true;
			}
			break;
			break;
		case "analgesic":
			return false;
	}
	return true;
}

function doSave(doRefresh,nextUrl){
	if(arguments.length<1){ var doRefresh = false; }
	if (isTrolley()){
		doneAction = "trolleySaved";
	}else if (isOrder()){
		doneAction = "orderSaved";
	}else if (isList()){
		doneAction = "listSaved";
	}else{
		alert("Unknown list type when saving list!");
		return;
	}
	if (doRefresh){
		doneAction = doneAction+"&refresh=true";
	}
	if(nextUrl == "" || nextUrl == null){
		dstForm.next_url.value="/JSPs/shop/list_operation.jsp?action="+doneAction + "&siteCode=" + siteCode;
	}else{
		dstForm.next_url.value = nextUrl;
	}
	showSaving();
	dstForm.err_url.value="/JSPs/shop/list_operation.jsp?action=problem&siteCode=" + siteCode;
	dstForm.dst_list_type.value = dstForm.src_list_type.value;
	dstForm.dst_list_num.value = dstForm.src_list_num.value;
	dstForm.add_more.value = "Y";
	if(showPopup){
		newWin = openSubWindow("/wdeliver/servlet/JSPs/shop/list_operation.jsp?action=save&siteCode=" + siteCode);
		dstForm.target = "SubmissionWindow";
	}else{
		dstForm.next_url.value="/JSPs/shop/trolleyandlogonInter.jsp?siteCode=" + siteCode;
		dstForm.target = "trolley";
	}
	dstForm.submit();
	return false;
}

function showLoading() {	
	//put some stuff in here
	return true;
}

function showSaving(){	
	//to show saving and loading etc
	return true;
}

function getForms(){
	srcForm = document.forms['shppngFrm'];
	dstForm = document.forms['updateListForm'];
}

function checkListLoop(toListType,productId){
	var checkASingleProductOnly = false;
	if(arguments.length==2){
		checkASingleProductOnly = true;
	}
	
	if (!isListChanged()){
		return "unchanged";
	}	
	
	var deleteString = "";
	var deleteUnitString = "";
	var deleteCount = 0;
	var productString = "";
	var qtyString = "";
	var qtyUnitString = "";
	var origQtyUnitString = "";
	var origQty = "";
	var cmtString = "";
	var lineMsgString = "";
	var substString = "";
	var updateCount = 0;
	var analgesicCount = 0;
	var prodRefNum = 0;
	for(i=0; i<productProperties.length; i++){
		prodRefNum = productProperties[i].prodRefNum;
		prodId = prodRefNum + productProperties[i].quantityUnit;
		if(checkASingleProductOnly){
			// Skip over all the products except the one equal to productId
			if(prodId!=productId){continue;}
		}
		// analgesic products
		if (productProperties[i].isAnalgesic==true){ analgesicCount+=parseInt(productProperties[i].quantity); }
		// updated products
		if (productProperties[i].isUpdated==true){
			
			if (productProperties[i].isToDelete==true){
				// Only delete products from the list if we are saving changes to list in view
				if (thisListType == toListType){
					deleteString += prodRefNum + "|";
					deleteUnitString += productProperties[i].origQuantityUnit + "|";
					deleteCount++;
					if (productProperties[i].isAnalgesic==true){
						analgesicCount-=parseInt(productProperties[i].quantity);
					}
				}
			}else{
				// don't add zero quantity items
				// when adding list to trolley or trolley to order or order to trolley
				if (productProperties[i].quantity==0 &&
					((isList() && toListType==trolleyListType)
					|| (isOrder() && toListType==trolleyListType)
					|| (isGoShopping() && toListType==trolleyListType)
					|| (isTrolley() && toListType==orderListType))){continue;}
				// update product
				productString += prodRefNum + "|";
				qtyString += productProperties[i].quantity + "|";
				origQty += productProperties[i].origQuantity + "|";
				qtyUnitString += productProperties[i].quantityUnit + "|";
				origQtyUnitString += productProperties[i].origQuantityUnit + "|";
				cmtString += productProperties[i].comments + "|";
				lineMsgString += productProperties[i].lineMessage + "|";
				substString += (productProperties[i].isSubstitutable ? 1 : 0) + "|";
				updateCount++;
			}
		}
	}	
	if(analgesicCount>2 && ((toListType==trolleyListType) || (toListType==orderListType)) ){
		alert("You are only allowed to purchase a maximum of 2 analgesic products.  Please order a smaller quantity.");
		result="analgesic";
	}else if(updateCount>0 || deleteCount>0){
		with(document.forms['updateListForm']){
			
			delete_rn.value=deleteString.substr(0,deleteString.lastIndexOf("|"));
			delete_unit.value=deleteUnitString.substr(0,deleteUnitString.lastIndexOf("|"));
			product_rn.value=productString.substr(0,productString.lastIndexOf("|"));
			qty.value=qtyString.substr(0,qtyString.lastIndexOf("|"));
			old_qty.value=origQty.substr(0,origQty.lastIndexOf("|"));
			qty_unit.value=qtyUnitString.substr(0,qtyUnitString.lastIndexOf("|"));
			old_unit.value=origQtyUnitString.substr(0,origQtyUnitString.lastIndexOf("|"));
			comments.value=cmtString.substr(0,cmtString.lastIndexOf("|"));
			lineMessage.value=lineMsgString.substr(0,lineMsgString.lastIndexOf("|"));
			substitute.value=substString.substr(0,substString.lastIndexOf("|"));

			//debugForm(document.forms["updateListForm"]);
		}
		result = "OK";
	}else{ result="unchanged"; }
	return result;
}
function isListChanged(){
	return isListUpdated;
}
function isTrolley(){
	if (thisListType==trolleyListType){ return true; }
	else{ return false; }
}
function deleteProduct(productId){	
	delImg = eval("document.images.del_"+productId);
		if(delImg.src.indexOf("removed.gif")>0){
			delImg.src = "/wdeliver/images/product_page/go_shopping/1x1blank.gif";
			updateProductProperty(productId,"delete",false);
		}else{
			delImg.src = "/wdeliver/images/products/removed.gif";
			updateProductProperty(productId,"delete",true);
		}
}
function undeleteProduct(productId, newval){	
	delImg = eval("document.images.del_"+productId);
	delImg.src = "/wdeliver/images/product_page/go_shopping/1x1blank.gif";	
	updateProductProperty(productId,"undelete",newval);	
}
function debugForm(formObject) {
	var nElements=formObject.elements.length;
	var msg=formObject.name+"\n"+nElements+" Elements"+"\n\n";
	for(i=0; i<nElements; i++){
		msg=msg+formObject.elements[i].name+" = "+formObject.elements[i].value+"\n";
	}
	alert(msg);
	return;
}
function mustBeSignedIn(){
	alert('Sorry, you need to be signed in to use this feature.\nPlease sign in or register using the sign-in box on the right hand side of the screen.');
	return false;
}
function getDateParms(dateStr){
	var dateLen = dateStr.length;
	var months = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	var monthNums = new Array("01","02","03","04","05","06","07","08","09","10","11","12");
	var month = dateStr.substring(dateLen-8,dateLen-5);
	var monthNum = "01";
	for (i=0; i<12; i++){ if (months[i]==month) monthNum=monthNums[i]; }
	var dayNum = dateStr.substring(dateLen-11, dateLen-9);
	dayNum = dayNum.replace(/ /g, "0");
	return "&suggested_date="+dateStr.substring(dateLen-4, dateLen)+"-"+monthNum+"-"+dayNum;
}
function displayTitleAtTop(pageTitle){
	with (document){
		close();
		if (!is_safari){
			open("text/html","replace");
		} else {
			open();
		}
		write('<html><head><title>WaitroseEntertaining</title>');
		write(css);
		if (is_ns){
			var wWidth=window.innerWidth;
		} else {
			var wWidth=document.body.clientWidth;
		}
		write('</head> ');
		write('<table border=0 cellpadding=0 cellspacing=0 width="100%">');
		write('<tr><td width="100%"><img src="/wdeliver/images/by_invitation/cat_bar.gif" alt="" height=16 width=',parseInt(wWidth),'></td></tr>');
		write('<tr><td>');
			write('<table border=0 cellpadding=0 cellspacing=0 width="100%">');
			write('<tr>');
			write('<td width="5%"></td>');
			write('<td height=45 class="heading2bold">',pageTitle,'</td>');
			write('</tr>');
			write("</table>");
		write('</td>');
		write('</tr>');
		write('<tr height=4><td width="100%" valign=bottom><img src="/wdeliver/images/general/buttons/by_inv/1x1separator.gif" alt="" height=1 width=',parseInt(wWidth),'></td></tr>');
		write('</table>');
		write('</body></html>');
		close();
	}
}
function byInvImage(indItemAnchor,imageName,description,pxSize){
	if(arguments.length<4){ pxSize=170; }
	var borderPath = "/wdeliver/images/by_invitation/borders";
	var str = "<table border=0 cellpadding=0 cellspacing=0 width='"+parseInt(pxSize+16+9)+"'>";
	str +="<tr><td height=5px colspan=4></td></tr>";
	str +="<tr><td width=9 rowspan=3 valign=bottom><img src='"+borderPath+"/serving_suggestion.gif' alt='serving suggestion' height=85 width=9></td><td width=8><img src='"+borderPath+"/tl.gif' alt='' height=8 width=8></td>";
	str +="<td><img src='"+borderPath+"/tp.gif' alt='' height=8 width="+parseInt(pxSize)+"></td>";
	str +="<td width=8><img src='"+borderPath+"/tr.gif' alt='' height=8 width=8></td></tr>";
	str +="<tr><td width=8><img src='"+borderPath+"/lf.gif' alt='' height="+parseInt(pxSize)+" width=8></td>";
	str +="<td>"+indItemAnchor+"<img border=0 alt='more information on "+description+"' src='"+productImageBaseUrl+imageName+"' width="+parseInt(pxSize)+" height="+parseInt(pxSize)+"></a></td>";
	str +="<td width=8><img src='"+borderPath+"/rt.gif' alt='' height="+parseInt(pxSize)+" width=8></td></tr>";
	str +="<tr><td width=8><img src='"+borderPath+"/bl.gif' alt='' height=8 width=8></td>";
	str +="<td><img src='"+borderPath+"/bm.gif' alt='' height=8 width="+parseInt(pxSize)+"></td>";
	str +="<td width=8><img src='"+borderPath+"/br.gif' alt='' height=8 width=8></td></tr>";
	str +="<tr><td height=5px colspan=4></td></tr>";
	str +="</table>";
	return str;
}
function clearUpdateFlags() {
	isListUpdated = false;
	for(var i=0; i<productProperties.length; i++){
		productProperties[i].isUpdated=false;
	}
}
function categoryLink(link,catRef,passedSiteCode){
	with(top.frames['shopping'].document.forms['categoryLinkForm']){
		siteCode.value=passedSiteCode;
		fh_location.value=link.substring(12);
		catid.value=catRef;
		submit();
	}
	return true;
}
function categoryLinkChangeSite(link,catRef,passedSiteCode){
	with(top.frames['shopping'].document.forms['categoryLinkFormChangeSite']){
		siteCode.value=passedSiteCode;
		fh_location.value=link.substring(12);
		catid.value=catRef;
		submit();
	}
	return true;
}

function classChange(styleChange,item){
	item.className=styleChange;
}
function emptyTrolley() {
	if(confirm("Are you sure you want to empty your trolley?")) {
		parent.frames['trolley'].onunload="";
		parent.frames['trolley'].clearUpdateFlags();
		with(document.forms['updateListForm']){
			delete_rn.value = "all";
			product_rn.value = "all";
			dst_list_type.value = trolleyListType;
			dst_list_num.value = 0;
			src_list_num.value = 0;
			src_list_type.value = trolleyListType;
			next_url.value="/JSPs/shop/trolleyandlogonInter.jsp";
			target = "trolley";
			submit();
		}
	}
	return false;
}
function addCommentToProductInTrolley(prodNum,qtyUnit){
	if(arguments.length<1) {
		url = "";
	}
	if(isScreenSmall) {
		x=200;
		y=25;
	}else{
		x=312;
		y=159;
	}
	var url = '/wdeliver/servlet/JSPs/shop/addCommentsAgainstLine.jsp?prodRefNum='+prodNum+"&siteCode="+siteCode+"&qtyUnit="+qtyUnit;
	subWin=window.open(url,"SubmissionWindow","toolbar=no,width=400,height=500,screenX="+x+",left="+x+",screenY="+y+",top="+y+",status=no,scrollbars=yes,resize=yes,menubar=no");
	subWin.focus();
}
function showEdit(prodId,isLoggedIn){
	if((isLoggedIn) && !(document.getElementById('addnote'+prodId)==null)){
		document.getElementById('addnote'+prodId).className="shown";
	}
	return;
}
function highLightTrolleyProducts(){
	var carryon = true;
	var numTrolleyProds =0;
	try{
		numTrolleyProds = parent.frames['trolley'].productProperties.length;
	}catch(exception){
		carryon=false; 
	}
	if(carryon){
		clearHighLightTrolleyProducts()
		for(iloop=0;iloop<numTrolleyProds;iloop++){
			var name = parent.frames['trolley'].productProperties[iloop].prodRefNum.toString() + parent.frames['trolley'].productProperties[iloop].dftQtyUnit
			var elementName = 'addnote' + name;
			try{
				nameString = document.getElementById('introlleyName'+name).innerHTML;
				if (parent.frames['trolley'].productProperties[iloop].quantityUnit =="EA" ){
					if (parent.frames['trolley'].productProperties[iloop].qtyInTrolley==1){
						nameString="<br><span class=\"sunday\">1x&nbsp;"+nameString+" is in your trolley</span>";
						if (document.getElementById('introlley'+name).innerHTML.indexOf("1x")<0){
							document.getElementById('introlley'+name).innerHTML+=nameString;
						}
					} else {
						if (nameString.substring(nameString.length-1)!="s") nameString=nameString+"s";
						nameString="<br><span class=\"sunday\">"+parent.frames['trolley'].productProperties[iloop].qtyInTrolley+"x&nbsp;"+nameString+" are in your trolley</span>";
						if (document.getElementById('introlley'+name).innerHTML.indexOf(parent.frames['trolley'].productProperties[iloop].qtyInTrolley+"x")<0){
							document.getElementById('introlley'+name).innerHTML+=nameString;
						}
					}	
				}else{
					if (parent.frames['trolley'].productProperties[iloop].quantityUnit =="ST" ){
						nameString="<br><span class=\"sunday\">£"+parent.frames['trolley'].productProperties[iloop].qtyInTrolley+"&nbsp;of "+nameString+" are in your trolley</span>";
						if (document.getElementById('introlley'+name).innerHTML.indexOf("£")<0){
							document.getElementById('introlley'+name).innerHTML+=nameString;
						}
					} else {
						if (parent.frames['trolley'].productProperties[iloop].qtyInTrolley==1){
							nameString="<br><span class=\"sunday\">"+parent.frames['trolley'].productProperties[iloop].qtyInTrolley+" " +parent.frames['trolley'].productProperties[iloop].quantityUnit+" of " +nameString + " is in your trolley</span>";
						} else {
							if(nameString.substring(nameString.length-1)!="s") nameString=nameString+"s";
							nameString="<br><span class=\"sunday\">"+parent.frames['trolley'].productProperties[iloop].qtyInTrolley+" " +parent.frames['trolley'].productProperties[iloop].quantityUnit+" of " +nameString + " are in your trolley</span>";
						}
						if (document.getElementById('introlley'+name).innerHTML.indexOf(" "+parent.frames['trolley'].productProperties[iloop].quantityUnit+" ")<0){
							document.getElementById('introlley'+name).innerHTML +=nameString;
						}
					}
				}
				document.getElementById('introlley'+name).className='shown';
				try{
					document.getElementById(elementName).className='shown';
					if(parent.frames['trolley'].productProperties[iloop].comments!=null && parent.frames['trolley'].productProperties[iloop].comments!=""){
						document.getElementById('addnotelink'+name).className="addLinks";
						document.getElementById('addnotelink'+name).innerHTML='edit note';
					}
				}catch(exception){}
			}catch(exception){
			}
		}
	}
}
function clearHighLightTrolleyProducts(){
	var carryon = true;
	var numTrolleyProds =0;
	try{
		numTrolleyProds = parent.frames['trolley'].productProperties.length;
	}catch(exception){
		carryon=false;
	}
	if(carryon){
		for(iloop=0;iloop<numTrolleyProds;iloop++){
			var name = parent.frames['trolley'].productProperties[iloop].prodRefNum.toString() + parent.frames['trolley'].productProperties[iloop].dftQtyUnit
			var elementName = 'addnote' + name;
			try{
				document.getElementById('introlley'+name).className="hidden";
				document.getElementById('introlley'+name).innerHTML="";
				document.getElementById(elementName).className="hidden";
			}catch(exception){}
		}
	}
}
function validateQtyAndAddToTrolley(productId,val,isLoggedIn,substitutionPref){
	if(updateProductProperty(productId,'quantity',val)){ 
		if(addProductToTrolleyOnTopMenu(productId,isLoggedIn,substitutionPref)){
			showEdit(productId,isLoggedIn);
		}
	}
}
function doSearch(searchTerm, showAllShelves){
	var searchForm = document.searchForm;
	searchForm.fh_search.value=searchTerm;
	searchForm.jotterResults.value=jotterResults;
	searchForm.showAllShelves.value=(typeof(showAllShelves)=='undefined')?false:showAllShelves;;
	searchForm.submit();
}

jsLoaded++;
