//-----------------------------------------------
//admin.js
//Lovell Jonhs Ltd.
//Code to deal with database admin
//-----------------------------------------------

//--------------------------------------------------------------GLOBALS
var menus = new Array("account","order","costs","interface","sites");
var timeout	= 500;			//For menus
var closetimer	= 0;		//		"
var ddmenuitem	= 0;		//		"
document.onclick = mclose;	// close layer when click-out

//--------------------------------------------------------------LOGIN SCRIPTS
//****************Run Login
function runAdminLogin(theAction){
	//Validate input
	var isOK = true;
	if(theAction == "in"){			
		if (document.frmAdminlogin.username.value == "") {											//Password field must not be empty
			showDialog('Warning','Please enter a value for the "User Name" field.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			isOK = false;
		}	
		if(isOK){
			//Check the 'Password' field			
			if (document.frmAdminlogin.pwd.value == "") {											//Password field must not be empty
				showDialog('Warning','Please enter a value for the "Password" field.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				isOK = false;
			}else if(!document.frmAdminlogin.pwd.value.match("^[a-z|A-Z|0-9|\.]*$")) {
				showDialog('Warning','Invalid Password. Password must contain only numbers and letters.<br/>If you used this password in the previous site, please login here and update. Alternatively contact site admin.<br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');				
				isOK = false;		
			}
		}
		var qstring = "name=" + document.frmAdminlogin.username.value + "&pwd=" + document.frmAdminlogin.pwd.value + "&login=" + theAction + "&code="  + document.frmAdminlogin.code.value;			
	}else{
		var qstring = "name=&pwd=&login=" + theAction + "&code=";			
	}
	if(isOK){
		var loginReq = new ajaxObject('runAdminLogin.php', adminLoginResponse);		
		loginReq.update(qstring,'POST');
	}	
}
//****************Response from running the login
function adminLoginResponse(responseText, responseStatus){
	if(responseStatus == 200){	
		//Get the returned values			
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");
			if(tempArray[2] == "in"){								//LOGGIN-IN			
				if(tempArray[0] == "ok"){			
					var siteLoginInfoArray = tempArray[1].split(",");   //(user name,white label,user type, site ref)
					if((siteLoginInfoArray[2] == "superuser") || (siteLoginInfoArray[2] == "admin1")){		//White label admin of super user show site index page
						document.frmAdminlogin.action = "siteIndex.php";
					}else{																					//Site admin go straight to site showing customer index page
						document.frmAdminlogin.currentsite.value = siteLoginInfoArray[3];
						document.frmAdminlogin.action = "userIndex.php";
					}
					document.frmAdminlogin.submit();
				}else{
					//Show error message
					showDialog('Warning', tempArray[1] + '.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');							
				}
			}else{													//LOGGIN-OUT
				document.frmCurrentSite.action = "adminLogin.php";
				document.frmCurrentSite.submit();
			}		
		}else{
			//Show error message
			showDialog('Warning', 'Problems logging in. Please try again<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}
	}
}
//****************Login to main interface as current user
function loginUser(theURL,isReduced){
	if(theURL != ""){
		if(isReduced == "yes"){											//Show portal login page
			document.loginform.action = theURL + "/portalLogin.php";
		}else{															//Show login page
			document.loginform.action = theURL + "/login.php";
		}
		document.loginform.target = "_blank";
		document.loginform.submit();
	}else{
		showDialog('Error', 'Problems logging in. Please try again<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
	}
}
//**************************Go to the main admin pages passing the relevant site info
function goToAdminContent(selectedSite){
	document.frmAdminSites.selectedsite.value = selectedSite;
	if(document.frmAdminSites.siteinfo.value != ""){
		document.frmAdminSites.submit();
	}
}

//--------------------------------------------------------------MENU SCRIPTS
//open hidden layer
function mopen(id){	
	// cancel close timer
	mcancelclosetime();
	// close old layer
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';
}
//close showed layer
function mclose(){
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}
//go close timer
function mclosetime(){
	closetimer = window.setTimeout(mclose, timeout);
}
//cancel close timer
function mcancelclosetime(){
	if(closetimer){
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}
//****************Changes the current site viewing
function changeCurrentSite(selObj){
	document.frmCurrentSite.currentsite.value = selObj.value;	
	var sPath = window.location.pathname;
	var currentPage = sPath.substring(sPath.lastIndexOf('/') + 1);
	document.frmCurrentSite.action = currentPage;
	document.frmCurrentSite.submit();
}

//----------------------------------------------------------------UPDATING SITE CONTENT SCRIPTS

//*******************Run script to update relevant content
function updateContent(theType){
	//Get the form 
	if(theType == "category"){
		var theForm = document.getElementById("categoriesform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "category=" + document.getElementById("category").value + "&catdesc=" + document.getElementById("catdesc").value + "&orderindex=" + document.getElementById("orderindex").value + "&catsites=" + document.getElementById("catsites").value + "&catid=" + document.getElementById("catid").value + "&updateaction=" + document.getElementById("updateaction").value;			
			var updateContentReq = new ajaxObject('upCategory.php', updateContentResponse);		
			updateContentReq.update(qstring,'POST');
		}	
	}else if(theType == "style"){
		var theForm = document.getElementById("styleform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "style=" + document.getElementById("style").value + "&styledesc=" + document.getElementById("styledesc").value + "&orderindex=" + document.getElementById("orderindex").value + "&styleid=" + document.getElementById("styleid").value + "&updateaction=" + document.getElementById("updateaction").value;			
			var updateContentReq = new ajaxObject('upStyle.php', updateContentResponse);		
			updateContentReq.update(qstring,'POST');
		}		
	}else if(theType == "delivery"){
		var theForm = document.getElementById("deliveryform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "method=" + document.getElementById("method").value.replace(/\+/g,"-plus-") + "&delprice=" + document.getElementById("delprice").value + "&site=" + document.getElementById("site").value + "&delid=" + document.getElementById("delid").value + "&updateaction=" + document.getElementById("updateaction").value;			
			var updateContentReq = new ajaxObject('upDelivery.php', updateContentResponse);		
			updateContentReq.update(qstring,'POST');
		}
	}else if(theType == "format"){
		var theForm = document.getElementById("formatsform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "format=" + document.getElementById("format").value + "&formatdesc=" + document.getElementById("formatdesc").value + "&explodeoutput=" + document.getElementById("explodeoutput").value  + "&formatid=" + document.getElementById("formatid").value + "&updateaction=" + document.getElementById("updateaction").value;				
			var updateContentReq = new ajaxObject('upFormat.php', updateContentResponse);		
			updateContentReq.update(qstring,'POST');
		}
	}else if(theType == "finish"){
		var theForm = document.getElementById("printingform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "finish=" + document.getElementById("finish").value + "&finishprice=" + document.getElementById("finishprice").value + "&site=" + document.getElementById("site").value + "&printid=" + document.getElementById("printid").value + "&updateaction=" + document.getElementById("updateaction").value;			
			var updateContentReq = new ajaxObject('upFinish.php', updateContentResponse);		
			updateContentReq.update(qstring,'POST');
		}
	}else if(theType == "licence"){
		var theForm = document.getElementById("licenceform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "licence=" + document.getElementById("licence").value + "&licdesc=" + document.getElementById("licdesc").value + "&licprice=" + document.getElementById("licprice").value + "&liclen=" + document.getElementById("liclen").value + "&hasproj=" + document.getElementById("hasproj").value + "&licid=" + document.getElementById("licid").value + "&updateaction=" + document.getElementById("updateaction").value;			
			var updateContentReq = new ajaxObject('upLicence.php', updateContentResponse);		
			updateContentReq.update(qstring,'POST');
		}
	}else if(theType == "overlay"){
		var theForm = document.getElementById("overlayform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "ovcode=" + document.getElementById("ovcode").value + "&ovprice=" + document.getElementById("ovprice").value + "&name=" + document.getElementById("name").value + "&ovid=" + document.getElementById("ovid").value + "&updateaction=" + document.getElementById("updateaction").value;			
			var updateContentReq = new ajaxObject('upOverlay.php', updateContentResponse);		
			updateContentReq.update(qstring,'POST');
		}
	}else if(theType == "discount"){
		var theForm = document.getElementById("discountform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "promo=" + document.getElementById("promo").value + "&outlet=" + document.getElementById("outlet").value + "&discount=" + document.getElementById("discount").value + "&site=" + document.getElementById("site").value + "&notes=" + document.getElementById("notes").value + "&did=" + document.getElementById("did").value + "&updateaction=" + document.getElementById("updateaction").value;			
			var updateContentReq = new ajaxObject('upDiscount.php', updateContentResponse);		
			updateContentReq.update(qstring,'POST');
		}
	}else if(theType == "site"){
		var theForm = document.getElementById("sitesform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){	
			//Get the u-r-m print pricing as one string
			var theMMPrintPrice = document.getElementById("urban").value + "," + document.getElementById("rural").value + "," + document.getElementById("moorland").value;
			var qstring = "whitelabel=" + document.getElementById("whitelabel").value + "&sitename=" + document.getElementById("sitename").value + "&site=" + document.getElementById("site").value + "&siteurl=" + document.getElementById("siteurl").value + "&geninvoice=" + document.getElementById("geninvoice").value + "&showaerial=" + document.getElementById("showaerial").value + "&showblom=" + document.getElementById("showblom").value + "&adminemail=" + document.getElementById("adminemail").value + "&orderprefix=" + document.getElementById("orderprefix").value + "&licno=" + document.getElementById("licno").value + "&emailfooter=" + encodeAsHTML(document.getElementById("emailfooter").value) + "&emailfooterhtml=" + encodeAsHTML(document.getElementById("emailfooterhtml").value) + "&secpayuser=" + document.getElementById("secpayuser").value + "&secpaypwd=" + document.getElementById("secpaypwd").value + "&secpaydig=" + document.getElementById("secpaydig").value + "&gsuname=" + document.getElementById("gsuname").value + "&gspwd=" + document.getElementById("gspwd").value + "&gsemail=" + document.getElementById("gsemail").value + "&siteid=" + document.getElementById("siteid").value + "&vatno=" + document.getElementById("vatno").value + "&invoicefooter=" + encodeAsHTML(document.getElementById("invoicefooter").value) + "&addressinfo=" + document.getElementById("addressinfo").value + "&nilicno=" + document.getElementById("nilicno").value + "&payaddress=" + document.getElementById("payaddress").value + "&payphone=" + document.getElementById("payphone").value + "&bankname=" + document.getElementById("bankname").value + "&bankaccno=" + document.getElementById("bankaccno").value + "&banksortcode=" + document.getElementById("banksortcode").value + "&gscode=" + document.getElementById("gscode").value + "&invoiceprefix=" + document.getElementById("invoiceprefix").value + "&quoteemail=" + document.getElementById("quoteemail").value + "&pdfurl=" + document.getElementById("pdfurl").value + "&pdflicno=" + document.getElementById("pdflicno").value + "&privacyurl=" + document.getElementById("privacyurl").value + "&termsurl=" + document.getElementById("termsurl").value + "&gsaccno=" + document.getElementById("gsaccno").value + "&logo=" + document.getElementById("logo").value + "&pdfnilicno=" + document.getElementById("pdfnilicno").value + "&reduced=" + document.getElementById("reduced").value + "&payinfohtml=" + encodeAsHTML(document.getElementById("payinfohtml").value) + "&homepagelink=" + document.getElementById("homepagelink").value + "&thedisabled=" + document.getElementById("thedisabled").value + "&mmprintprice=" + theMMPrintPrice + "&tenkprintprice=" + document.getElementById("tenkprintprice").value + "&faxno=" + document.getElementById("faxno").value + "&updateaction=" + document.getElementById("updateaction").value;		
			var updateContentReq = new ajaxObject('upSite.php', updateContentResponse);
			updateContentReq.update(qstring,'POST');
		}
	}else if(theType == "siteusers"){
		var theForm = document.getElementById("siteusersform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "whitelabel=" + document.getElementById("whitelabel").value + "&username=" + document.getElementById("username").value + "&site=" + document.getElementById("site").value + "&usertype=" + document.getElementById("usertype").value + "&userpwd=" + document.getElementById("userpwd").value + "&showreturns=" + document.getElementById("showreturns").value + "&showcosts=" + document.getElementById("showcosts").value + "&siteuserid=" + document.getElementById("siteuserid").value + "&updateaction=" + document.getElementById("updateaction").value;		
			var updateContentReq = new ajaxObject('upSiteUser.php', updateContentResponse);
			updateContentReq.update(qstring,'POST');
		}	
	}else if(theType == "sales"){
		var theForm = document.getElementById("salesform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "salesname=" + document.getElementById("salesname").value + "&site=" + document.getElementById("site").value + "&salesid=" + document.getElementById("salesid").value + "&userpwd=" + document.getElementById("userpwd").value + "&updateaction=" + document.getElementById("updateaction").value;		
			var updateContentReq = new ajaxObject('upSales.php', updateContentResponse);
			updateContentReq.update(qstring,'POST');
		}
	}else if(theType == "tariffs"){
		var theForm = document.getElementById("tariffform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "tariffcode=" + document.getElementById("tariffcode").value + "&site=" + document.getElementById("site").value + "&tenkprice=" + document.getElementById("tenkprice").value + "&mmprice=" + document.getElementById("mmprice").value + "&tariffid=" + document.getElementById("tariffid").value + "&updateaction=" + document.getElementById("updateaction").value;		
			//var qstring = "tariffcode=" + document.getElementById("tariffcode").value + "&site=" + document.getElementById("site").value + "&tariffid=" + document.getElementById("tariffid").value + "&updateaction=" + document.getElementById("updateaction").value;		
			var updateContentReq = new ajaxObject('upTariffs.php', updateContentResponse);
			updateContentReq.update(qstring,'POST');
		}
	}else if(theType == "markup"){
		var theForm = document.getElementById("markupform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "prodcode=" + document.getElementById("prodcode").value + "&site=" + document.getElementById("site").value + "&markup=" + document.getElementById("markup").value + "&fixedfee=" + document.getElementById("fixedfee").value + "&markupid=" + document.getElementById("markupid").value + "&updateaction=" + document.getElementById("updateaction").value;		
			var updateContentReq = new ajaxObject('upMarkup.php', updateContentResponse);
			updateContentReq.update(qstring,'POST');
		}	
	}else if(theType == "royaltyinfo"){
		var theForm = document.getElementById("royaltyform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var tempResolution = Number(document.getElementById("resolution").value);
			var amendedResolution = String(tempResolution);
			var qstring = "supplier=" + document.getElementById("supplier").value + "&prodcode=" + document.getElementById("prodcode").value + "&royaltycode=" + document.getElementById("royaltycode").value + "&printroyaltycode=" + document.getElementById("printroyaltycode").value + "&theregion=" + document.getElementById("theregion").value + "&areadisc=" + document.getElementById("areadisc").value + "&resolution=" + amendedResolution + "&fixedprice=" + document.getElementById("fixedprice").value + "&formulaname=" + document.getElementById("formulaname").value + "&longthin=" + document.getElementById("longthin").value + "&name=" + document.getElementById("name").value + "&royid=" + document.getElementById("royid").value + "&updateaction=" + document.getElementById("updateaction").value;
			var updateContentReq = new ajaxObject('upRoyaltyInfo.php', updateContentResponse);
			updateContentReq.update(qstring,'POST');
		}			
	}else if(theType == "vatrate"){
		var qstring = "vatrate=" + document.getElementById("vatrate").value + "&expires=" + document.getElementById("expires").value + "&vatid=" + document.getElementById("vatid").value + "&updateaction=" + document.getElementById("updateaction").value;		
		var updateContentReq = new ajaxObject('upVatRate.php', updateContentResponse);
		updateContentReq.update(qstring,'POST');
	}else if(theType == "royaltyrate"){
		var theForm = document.getElementById("rateform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "royalrate=" + document.getElementById("royalrate").value + "&site=" + document.getElementById("site").value + "&royalref=" + document.getElementById("royalref").value + "&expires=" + document.getElementById("expires").value + "&ratetype=" + document.getElementById("ratetype").value + "&rateid=" + document.getElementById("rateid").value + "&updateaction=" + document.getElementById("updateaction").value;		
			var updateContentReq = new ajaxObject('upRoyaltyRate.php', updateContentResponse);
			updateContentReq.update(qstring,'POST');	
		}		
	}else if(theType == "minPrice"){
		var theForm = document.getElementById("minpriceform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "prodcode=" + document.getElementById("prodcode").value + "&variantcode=" + document.getElementById("variantcode").value + "&minprice=" + document.getElementById("minprice").value + "&minid=" + document.getElementById("minid").value + "&updateaction=" + document.getElementById("updateaction").value;		
			var updateContentReq = new ajaxObject('upMinPrice.php', updateContentResponse);
			updateContentReq.update(qstring,'POST');
		}			
	}else if(theType == "fixedstyle"){
		var theForm = document.getElementById("fixedform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){
			var qstring = "fcode=" + document.getElementById("fcode").value + "&fcolour=" + document.getElementById("fcolour").value + "&fsize=" + document.getElementById("fsize").value + "&fsize2=" + document.getElementById("fsize2").value + "&fheader1=" + document.getElementById("fheader1").value + "&fheader2=" + document.getElementById("fheader2").value + "&fheader3=" + document.getElementById("fheader3").value + "&fheader4=" + document.getElementById("fheader4").value + "&styleid=" + document.getElementById("styleid").value + "&updateaction=" + document.getElementById("updateaction").value;		
			var updateContentReq = new ajaxObject('upFixedStyle.php', updateContentResponse);
			updateContentReq.update(qstring,'POST');
		}
	}else if(theType == "product"){
		var theForm = document.getElementById("productform");
		var isOk = adminFormValidator(theForm,theType);
		if(isOk){		
			var qstring = "prodid=" + document.getElementById("prodid").value;
			qstring += "&category=" + document.getElementById("category").value;
			qstring += "&product=" + document.getElementById("product").value;
			qstring += "&proddesc=" + document.getElementById("proddesc").value;	
			qstring += "&fulldesc=" + escapeAmp(document.getElementById("fulldesc").value);
			qstring += "&prodcode=" + document.getElementById("prodcode").value.replace(/\+/g,"-plus-");     
			qstring += "&scale=" + document.getElementById("scale").value;
			qstring += "&type=" + document.getElementById("type").value;	
			qstring += "&price=" + document.getElementById("price").value;
			qstring += "&tilesize=" + document.getElementById("tilesize").value;	
			qstring += "&formats=" + document.getElementById("formats").value;
			qstring += "&style=" + document.getElementById("style").value;
			qstring += "&licences=" + document.getElementById("licences").value;
			qstring += "&maxsize="  + document.getElementById("maxsize").value;
			qstring += "&minorder=" + document.getElementById("minorder").value;
			qstring += "&showit=" + document.getElementById("showit").value;
			qstring += "&areadisc=" + document.getElementById("areadisc").value;
			qstring += "&orderindex=" + document.getElementById("orderindex").value;
			qstring += "&tformats=" + document.getElementById("tformats").value;
			qstring += "&coverage=" + document.getElementById("coverage").value;
			qstring += "&allowoverlays=" + document.getElementById("allowoverlays").value;
			qstring += "&mmprice=" + document.getElementById("mmprice").value.replace(/\+/g,"-plus-"); 
			qstring += "&orderoption=" + document.getElementById("orderoption").value;
			qstring += "&privproduct=" + document.getElementById("privproduct").value;
			qstring += "&fixedtype=" + document.getElementById("fixedtype").value;
			qstring += "&fixedbuy=" + document.getElementById("fixedbuy").value;
			qstring += "&downloadit=" + document.getElementById("downloadit").value;
			qstring += "&limited=" + document.getElementById("limited").value;
			qstring += "&thescales=" + document.getElementById("thescales").value;
			qstring += "&discon=" + document.getElementById("discon").value;
			qstring += "&hasplic=" + document.getElementById("hasplic").value;
			qstring += "&multiextent=" + document.getElementById("multiextent").value;
			qstring += "&suppliers=" + document.getElementById("suppliers").value;
			qstring += "&suppliertype=" + document.getElementById("suppliertype").value;
			qstring += "&maxdiscount=" + document.getElementById("maxdiscount").value;
			qstring += "&theregion=" + document.getElementById("theregion").value;
			qstring += "&printprice=" + document.getElementById("printprice").value;
			qstring += "&addcredit=" + document.getElementById("addcredit").value;
			qstring += "&deltime=" + document.getElementById("deltime").value;
			qstring += "&varyprice=" + document.getElementById("varyprice").value;
			qstring += "&prodsites=" + document.getElementById("prodsites").value;
			qstring += "&cancombine=" + document.getElementById("cancombine").value;
			qstring += "&longthin=" + document.getElementById("longthin").value;
			qstring += "&hasroyalty=" + document.getElementById("hasroyalty").value;
			qstring += "&maxlongthinsize=" + document.getElementById("maxlongthinsize").value;
			qstring += "&resolution=" + document.getElementById("resolution").value;
			qstring += "&catid=" + document.getElementById("catid").value;
			qstring += "&updateaction=" + document.getElementById("updateaction").value;
			var updateContentReq = new ajaxObject('upProduct.php', updateContentResponse);
			updateContentReq.update(qstring,'POST');
		}
	}						
}
//*******************Run script to update relevant content
function deleteContent(theID,theType){	
	//Prompt before actually deleting
	var dialogContent = "Do you really want to delete this record?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='deleteTheContent(\"" + theID + "\",\"" + theType + "\");'>  <input type='button' value='No' id='noButton' onclick='hideDialog();' >"
	showDialog('',dialogContent,'prompt');	
}	
function deleteTheContent(theID,theType){		
	if(theType == "category"){
		var qstring = "category=&catdesc=&orderindex=&catsites=&catid=" + theID + "&updateaction=remove";			
		var updateContentReq = new ajaxObject('upCategory.php', updateContentResponse);		
		updateContentReq.update(qstring,'POST');	
	}else if(theType == "style"){
		var qstring = "style=&styledesc=&orderindex=&styleid=" + theID + "&updateaction=remove";			
		var updateContentReq = new ajaxObject('upStyle.php', updateContentResponse);		
		updateContentReq.update(qstring,'POST');
	}else if(theType == "delivery"){
		var qstring = "method=&delprice=&site=&delid=" + theID + "&updateaction=remove";			
		var updateContentReq = new ajaxObject('upDelivery.php', updateContentResponse);		
		updateContentReq.update(qstring,'POST');
	}else if(theType == "format"){
		var qstring = "format=&formatdesc=&explodeoutput&formatid=" + theID + "&updateaction=remove";			
		var updateContentReq = new ajaxObject('upFormat.php', updateContentResponse);		
		updateContentReq.update(qstring,'POST');
	}else if(theType == "finish"){
		var qstring = "finish=&finishprice=&site=&printid=" + theID + "&updateaction=remove";			
		var updateContentReq = new ajaxObject('upFinish.php', updateContentResponse);		
		updateContentReq.update(qstring,'POST');
	}else if(theType == "licence"){
		var qstring = "licence=&licdesc=&licprice=&liclen=&hasproj=&licid=" + theID + "&updateaction=remove";			
		var updateContentReq = new ajaxObject('upLicence.php', updateContentResponse);		
		updateContentReq.update(qstring,'POST');
	}else if(theType == "overlay"){
		var qstring = "ovcode=&ovprice=&name=&ovid=" + theID + "&updateaction=remove";			
		var updateContentReq = new ajaxObject('upOverlay.php', updateContentResponse);		
		updateContentReq.update(qstring,'POST');
	}else if(theType == "discount"){
		var qstring = "promo=&outlet=&discount=&site=&did=" + theID + "&updateaction=remove";			
		var updateContentReq = new ajaxObject('upDiscount.php', updateContentResponse);		
		updateContentReq.update(qstring,'POST');
	}else if(theType == "markup"){
		var qstring = "prodcode=&markup=&site=&fixedfee=&markupid=" + theID + "&updateaction=remove";			
		var updateContentReq = new ajaxObject('upMarkup.php', updateContentResponse);		
		updateContentReq.update(qstring,'POST');	
	}else if(theType == "site"){
		var qstring = "whitelabel=&sitename=&site=&siteurl=&geninvoice=&showaerial=&showblom=&adminemail=&orderprefix=&licno=&nilicno=&emailfooter=&emailfooterhtml=&secpayuser=&secpaypwd=&secpaydig=&siteid=" + theID + "&payaddress=&payphone=&bankname=&bankaccno=&banksortcode=&gscode=&invoiceprefix=&quoteemail=&pdfurl=&pdflicno=&termsurl=&privacyurl=&gsaccno=&logo=&pdfnilicno=&reduced=payinfohtml&homepagelink=&thedisabled=&faxno=&updateaction=remove";			
		var updateContentReq = new ajaxObject('upSite.php', updateContentResponse);		
		updateContentReq.update(qstring,'POST');
	}else if(theType == "siteusers"){
		var qstring = "whitelabel=&username=&site=&usertype=&userpwd=&showreturns=&showcosts=&siteuserid=" + theID + "&updateaction=" + "&updateaction=remove";
		var updateContentReq = new ajaxObject('upSiteUser.php', updateContentResponse);
		updateContentReq.update(qstring,'POST');
	}else if(theType == "product"){
		var qstring = "prodid=" + theID + "&category=&product=&proddesc=&fulldesc=&prodcode=&scale=&type=&price=&tilesize=&formats=&style=&licences=&maxsize=&minorder=&showit=&areadisc=&orderindex=&tformats=&coverage=&allowoverlays=&mmprice=&orderoption=&privproduct=&fixedtype=&fixedbuy=&downloadit=&limited=&thescales=&discon=hasplic=&multiextent=&suppliers=&suppliertype=&maxdiscount=&theregion=&printprice=&addcredit=&prodsites=&cancombine=&longthin=&hasroyalty=&catid=&updateaction=remove";
		var updateContentReq = new ajaxObject('upProduct.php', updateContentResponse);
		updateContentReq.update(qstring,'POST');
	}else if(theType == "fixedstyle"){
		var qstring = "fcode=&fcolour=&fsize=&fsize2=&fheader1=&fheader2=&fheader3=&fheader4=&styleid=" + theID + "&updateaction=remove";		
		var updateContentReq = new ajaxObject('upFixedStyle.php', updateContentResponse);
		updateContentReq.update(qstring,'POST');
	}else if(theType == "royaltyInfo"){
		var qstring = "supplier=&prodcode=&royaltycode=&printroyaltycode=&theregion=&areadisc=&resolution=&fixedprice=&formulaname=&longthin=&name=&royid=" + theID + "&updateaction=remove";
		var updateContentReq = new ajaxObject('upRoyaltyInfo.php', updateContentResponse);
		updateContentReq.update(qstring,'POST');		
	}else if(theType == "sales"){
		var qstring = "salesname=&site=&salesid=" + theID + "&updateaction=remove";		
		var updateContentReq = new ajaxObject('upSales.php', updateContentResponse);
		updateContentReq.update(qstring,'POST');
	}else if(theType == "vatrate"){
		var qstring = "vatrate=&expires=&vatid=" + theID + "&updateaction=remove";		
		var updateContentReq = new ajaxObject('upVatRate.php', updateContentResponse);
		updateContentReq.update(qstring,'POST');
	}else if(theType == "royaltyRate"){
		var qstring = "royalrate=&expires=&site=&royalref=&ratetype=&rateid=" + theID + "&updateaction=remove";		
		var updateContentReq = new ajaxObject('upRoyaltyRate.php', updateContentResponse);
		updateContentReq.update(qstring,'POST');			
	}else if(theType == "tariffs"){
		var qstring = "tariffcode=&site=&tenkprice=&mmprice=&tariffid=" + theID + "&updateaction=remove";		
		var updateContentReq = new ajaxObject('upTariffs.php', updateContentResponse);
		updateContentReq.update(qstring,'POST');
	}else if(theType == "minPrice"){
		var qstring = "prodcode=&variantcode=&minprice=&minid=" + theID + "&updateaction=remove";		
		var updateContentReq = new ajaxObject('upMinPrice.php', updateContentResponse);
		updateContentReq.update(qstring,'POST');
	}	
}
//*******************Response from updating site content
function updateContentResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Ensure no returns and other unwanted characters get passed back
		responseText = trim(responseText);	
		responseText = responseText.replace(/\n/g,"").replace(/\r/g,"");
		//Get the returned values			
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");			
			if(tempArray[0] == "ok"){							
				var dialogContent = tempArray[1] + "<br/><br/><input type='button' value='Close' id='closeButton' onclick='goBackToIndexPage(\"" + tempArray[2] + "\");' >";
				showDialog('Success', dialogContent ,'success');						
			}else{												
				//Show error message
				showDialog('Warning','Problems updating content.Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			}		
		}else{
			//Show error message
			showDialog('Warning','Problems updating content.Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}
	}	
}
//*******************Go back to index page after updating content
function goBackToIndexPage(passedpage){	
	if(passedpage == "productsResults.php"){		//Go back to index page keeping the initial search
		document.varform.action = passedpage;
		document.varform.submit();
	}else{
		hideDialog();
		window.location = passedpage;				//Go back to index page
	}
}
//*******************Clones product
function cloneProduct(){
	//Set update action form "update" to add
	document.getElementById("updateaction").value = "add";
	//Run the update content function
	updateContent("product");
}
//****************Update user info
function updateUserInfo(theAction){
	var theForm = document.getElementById("custform");	
	if(theAction == "register"){
		$validateThis = "register";
	}else{
		$validateThis = "user";
	}
	if(adminFormValidator(theForm,$validateThis)){	
		//Define the query string to pass variables
		var qstring = "title=" + document.custform.title.value;
		qstring += "&firstname=" + document.custform.firstname.value;
		qstring += "&secondname=" + document.custform.secondname.value;
		qstring += "&email=" + document.custform.email.value;		
		qstring += "&company=" + escapeAmp(document.custform.company.value);		
		qstring += "&address1=" + document.custform.address1.value;
		qstring += "&address2=" + document.custform.address2.value;
		qstring += "&town=" + document.custform.town.value;
		qstring += "&county=" + document.custform.county.value;
		qstring += "&postcode=" + document.custform.postcode.value;
		qstring += "&country=" + document.custform.country.value;
		qstring += "&telephone=" + document.custform.telephone.value;
 		qstring += "&fax=" + document.custform.fax.value;
		qstring += "&website=" + document.custform.website.value;
 		qstring += "&outcode=" + document.custform.outcode.value;
		qstring += "&mailing1=" + document.custform.mailing1.value;	
		qstring += "&notifyuser=" + document.custform.notifyuser.value;
		qstring += "&daddress1=" + document.custform.daddress1.value;
		qstring += "&daddress2=" + document.custform.daddress2.value;
		qstring += "&dtown=" + document.custform.dtown.value;
		qstring += "&dcounty=" + document.custform.dcounty.value;
		qstring += "&dpostcode=" + document.custform.dpostcode.value;
		qstring += "&dcountry=" + document.custform.dcountry.value;
		qstring += "&adminstatus=" + document.custform.adminstatus.value;
		qstring += "&pcharge=" + document.custform.pcharge.value;
		qstring += "&tenkdata=" + document.custform.tenkdata.value;
		qstring += "&gsref=" + document.custform.gsref.value;
		qstring += "&salesperson=" + document.custform.salesperson.value;
		qstring += "&salespersondisp=" + document.custform.salespersondisplay.value;
		qstring += "&usernotes=" + escapeAmp(document.custform.usernotes.value);
		qstring += "&useronlydata=" + document.custform.useronlydata.value;
		qstring += "&usersite=" + document.custform.usersite.value;	
		qstring += "&custid=" + document.custform.custid.value;
		if(theAction == "register"){					//If registering pass the password
			qstring += "&pwd1=" + document.custform.pwd1.value;
		}
		qstring += "&cadd=" + theAction;
		var loginReq = new ajaxObject('upUser.php', updateUserResponse);
		loginReq.update(qstring,'POST');
	}
}
//****************Response from updating user info
function updateUserResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");
			if(tempArray[0] == "yes"){
				document.custform.userid.value = tempArray[2];				//Set the user id to allow the user's details to display
				showDialog('',tempArray[1] + '<br/><input type="button" value="Close" id="closeButton" onclick="refreshAdminUserPage();" >','prompt');	
			}else{								//Could not register for some reason, show the error message
				showDialog('Error',tempArray[1] + '<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
			}
		}else{
			showDialog('Error','There has been a problem updating. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
		}
	}
}
//*******************Refresh user page after making updates
function refreshAdminUserPage(){
	hideDialog();
	document.custform.action = "user.php";
	document.custform.submit();				
}
//*******************Freeze or unfreeze the current account
function freezeUserAccount(theAction){
	var dialogContent = "Do you really want to " + theAction + " this account?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='freezeUserAccountUpdate(\"" + theAction + "\");'>  <input type='button' value='No' id='noButton' onclick='hideDialog();' >"
	showDialog('',dialogContent,'prompt');
}
function freezeUserAccountUpdate(theAction){
	//Define the query string to pass variables
	var qstring = "title=" + document.custform.title.value;
	qstring += "&firstname=" + document.custform.firstname.value;
	qstring += "&secondname=" + document.custform.secondname.value;
	qstring += "&cadd=" + theAction + "&custid=" + document.custform.custid.value + "&email=" + document.custform.email.value;
	var loginReq = new ajaxObject('upUser.php', updateUserResponse);
	loginReq.update(qstring,'POST');
}
//vvvvvvvvvvvvvvvvvvvvvvvvvvvNOT CALLED
//*******************Authorize the current account for invoicing
function authorizeUserAccount(){
	var dialogContent = "Do you really want to authorise this account?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='authorizeUserAccountUpdate();'>  <input type='button' value='No' id='noButton' onclick='hideDialog();' >"
	showDialog('',dialogContent,'prompt');
}
function authorizeUserAccountUpdate(){
	//Define the query string to pass variables
	var qstring = "title=" + document.custform.title.value;
	qstring += "&firstname=" + document.custform.firstname.value;
	qstring += "&secondname=" + document.custform.secondname.value;
	qstring += "&cadd=authorize&custid=" + document.custform.custid.value + "&email=" + document.custform.email.value;
	var loginReq = new ajaxObject('upUser.php', updateUserResponse);
	loginReq.update(qstring,'POST');
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//****************Update company info
function updateCompanyInfo(theAction){
	//Define the query string to pass variables
	var theForm = document.getElementById("compform");
	if(adminFormValidator(theForm,"company")){
		var qstring = "company=" + escapeAmp(document.compform.company.value);		
		qstring += "&address1=" + document.compform.address1.value;
		qstring += "&address2=" + document.compform.address2.value;
		qstring += "&town=" + document.compform.town.value;
		qstring += "&county=" + document.compform.county.value;
		qstring += "&postcode=" + document.compform.postcode.value;
		qstring += "&country=" + document.compform.country.value;
		qstring += "&telephone=" + document.compform.telephone.value;
		qstring += "&fax=" + document.compform.fax.value;
		qstring += "&website=" + document.compform.website.value;
		qstring += "&outcode=" + document.compform.outcode.value;
		qstring += "&monthlyspend=" + document.compform.monthlyspend.value;
		qstring += "&pcharge=" + document.compform.pcharge.value;	
		qstring += "&gsref=" + document.compform.gsref.value;		
		qstring += "&ponumber=" + document.compform.ponumber.value;
		qstring += "&paymentmethod=" + document.compform.paymentmethod.value;
		qstring += "&oneclickorder=" + document.compform.oneclickorder.value;	
		qstring += "&climit=" + document.compform.climit.value;	
		qstring += "&logo=" + document.compform.logo.value;	
		qstring += "&notes=" + escapeAmp(document.compform.notes.value);
		qstring += "&useronlydata=" + document.compform.useronlydata.value;				
		qstring += "&adminnotify=" + document.compform.adminnotify.value;
		qstring += "&notifyid=" + document.compform.notifyid.value;
		qstring += "&paperinvoice=" + document.compform.paperinvoice.value;
		qstring += "&geninvoice=" + document.compform.geninvoice.value;
		qstring += "&tenkdata=" + document.compform.tenkdata.value;
		qstring += "&companyid=" + document.compform.companyid.value;
		qstring += "&companysite=" + document.compform.companysite.value;
		qstring += "&salesperson=" + document.compform.salesperson.value;
		qstring += "&salespersondisp=" + document.compform.salespersondisplay.value;
		qstring += "&tariffref=" + document.compform.tariffref.value;
		qstring += "&retailoutlet=" + document.compform.retailoutlet.value;
		qstring += "&pdfurl=" + document.compform.pdfurl.value;
		qstring += "&licenceadvise=" + document.compform.licenceadvise.value;	
		qstring += "&extaccno=" + document.compform.extaccno.value;
		qstring += "&isportalsite=" + document.compform.isportalsite.value;
		if(theAction == "new"){
			qstring += "&freeviewcredit=" + document.compform.freeviewcredit.value;
			qstring += "&viewcredit=" + document.compform.viewcredit.value;
			qstring += "&custid=" + document.compform.custid.value;
		}	
		qstring += "&cadd=" + theAction;			
		var loginReq = new ajaxObject('upCompany.php', updateCompanyResponse);
		loginReq.update(qstring,'POST');
	}
}
//****************Response from updating user info
function updateCompanyResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");
			if(tempArray[0] == "yes"){
				if(tempArray[2] == "add"){
					showDialog('',tempArray[1] + '<br/><input type="button" value="Close" id="closeButton" onclick="backToMultiUsers();" >','prompt');	
				}else if(tempArray[2] == "new"){
					showDialog('',tempArray[1] + '<br/><input type="button" value="Close" id="closeButton" onclick="refreshAdminCompanyPage();" >','prompt');	
				}else{
					showDialog('',tempArray[1] + '<br/><input type="button" value="Close" id="closeButton" onclick="refreshAdminCompanyPage();" >','prompt');	
				}
			}else{								//Could not register for some reason, show the error message
				showDialog('Error',tempArray[1] + '<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
			}
		}else{
			showDialog('Error','There has been a problem updating. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
		}
	}
}
//*******************Refresh user page after making updates
function refreshAdminCompanyPage(){
	hideDialog();
	document.varform.action = "company.php";
	document.varform.submit();				
}
//*******************Freeze or unfreeze the current account
function freezeCompanyAccount(theAction){
	var dialogContent = "Do you really want to " + theAction + " this account?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='freezeCompanyAccountUpdate(\"" + theAction + "\");'>  <input type='button' value='No' id='noButton' onclick='hideDialog();' >"
	showDialog('',dialogContent,'prompt');
}
function freezeCompanyAccountUpdate(theAction){
	//Define the query string to pass variables
	var qstring = "cadd=" + theAction + "&companyid=" + document.compform.companyid.value;
	var loginReq = new ajaxObject('upCompany.php', updateCompanyResponse);
	loginReq.update(qstring,'POST');
}
//****************Defines options from check boxes when updating the account details
function setCheckOptions(theControl,theSource){
	if(theControl == "accpayable"){										//Show extra input for account payable user
		if(document.getElementById("accountpaychk").checked){
			document.getElementById("accpayable").value = "yes";
			if(theSource == "new"){
				document.getElementById("accpaydetails").style.display = "block";
			}		
		}else{
			document.getElementById("accpayable").value = "no";
			if(theSource == "new"){
				document.getElementById("accpaydetails").style.display = "none";
			}
		}		
	}else if(theControl == "mailing1"){
		if(document.getElementById("mailing1chk").checked){
			document.getElementById("mailing1").value = "yes";	
		}else{
			document.getElementById("mailing1").value = "no";
		}		
	}else if(theControl == "notifyadmin"){
		if(document.getElementById("notifyadminchk").checked){
			document.getElementById("notifyadmin").value = "yes";	
		}else{
			document.getElementById("notifyadmin").value = "no";
		}
	}else if(theControl == "notifyuser"){
		if(document.getElementById("notifyuserchk").checked){
			document.getElementById("notifyuser").value = "yes";	
		}else{
			document.getElementById("notifyuser").value = "no";
		}
	}
}
//*******************Defines options from check boxes (Company Details)
function setCompCheckOptions(theControl){
	if(theControl == "accaccess"){
		if(document.compform.accaccesschk.checked){
			document.compform.accaccess.value = 'yes';	
		}else{
			document.compform.accaccess.value = 'no';
		}
	}else if(theControl == "paperinvoice"){
		if(document.compform.paperinvoicechk.checked){
			document.compform.paperinvoice.value = 'yes';	
		}else{
			document.compform.paperinvoice.value = 'no';
		}			
	}else if(theControl == "oneclickorder"){
		if(document.compform.oneclickorderchk.checked){
			document.compform.oneclickorder.value = 'yes';	
		}else{
			document.compform.oneclickorder.value = 'no';
		}	
	}else if(theControl == "retailoutlet"){
		if(document.compform.retailoutletchk.checked){
			document.compform.retailoutlet.value = 'yes';
			document.compform.geninvoice.value = 'no';	
		}else{
			document.compform.retailoutlet.value = 'no';
			document.compform.geninvoice.value = 'yes';
		}
	}else if(theControl == "licenceadvise"){
		if(document.compform.licenceadvisechk.checked){
			document.compform.licenceadvise.value = 'yes';	
		}else{
			document.compform.licenceadvise.value = 'no';
		}
	}else if(theControl == "geninvoice"){
		if(document.compform.geninvoicechk.checked){
			document.compform.geninvoice.value = 'yes';	
		}else{
			document.compform.geninvoice.value = 'no';
		}			
	}else if(theControl == "adminnotify"){
		document.compform.dispnotifyemail.value = ""; //Ensure person to notify is cleared
		document.compform.notifyid.value = ""; 
		if(document.compform.adminnotifychk.checked){
			document.compform.adminnotify.value = "yes";				
		}else{
			document.compform.adminnotify.value = "no";
		}
	}
}
//*******************Marks order as cancelled or not
function updateOrderStatus(theOrderNo,theRecno){
	document.ordersform.pupdatevalue.value = eval("document.ordersform.cancelled" + theRecno + ".value");
	document.ordersform.pupdateflag.value = theOrderNo;
	document.ordersform.submit();
}
//*******************Hide/shows input for adding site user depending on user type (eg. superusers don't need white label and site entering)
function updateSiteUsersContent(selObject){
	if(selObject.value == "superuser"){
		document.getElementById("userswhitelabel1").style.display = "none";
		document.getElementById("userssiteid1").style.display = "none";
		document.getElementById("userswhitelabel2").style.display = "none";
		document.getElementById("userssiteid2").style.display = "none";	
		document.getElementById("usersreturns1").style.display = "none";
		document.getElementById("userscosts1").style.display = "none";
		document.getElementById("usersreturns2").style.display = "none";
		document.getElementById("userscosts2").style.display = "none";
	}else if(selObject.value == "admin1"){
		document.getElementById("userswhitelabel1").style.display = "block";
		document.getElementById("userssiteid1").style.display = "none";
		document.getElementById("userswhitelabel2").style.display = "block";
		document.getElementById("userssiteid2").style.display = "none";		
		document.getElementById("usersreturns1").style.display = "none";
		document.getElementById("userscosts1").style.display = "none";
		document.getElementById("usersreturns2").style.display = "none";
		document.getElementById("userscosts2").style.display = "none";	
	}else if(selObject.value == "admin2"){
		document.getElementById("userswhitelabel1").style.display = "block";
		document.getElementById("userssiteid1").style.display = "block";
		document.getElementById("userswhitelabel2").style.display = "block";
		document.getElementById("userssiteid2").style.display = "block";	
		document.getElementById("usersreturns1").style.display = "block";
		document.getElementById("userscosts1").style.display = "block";
		document.getElementById("usersreturns2").style.display = "block";
		document.getElementById("userscosts2").style.display = "block";		
	}
}
//*******************Reloads admin register user page to change the site to register (necessary wheer user viewing white label with more than one site)
function updateRegUserSite(selObj){
	document.custform.usersite.value = selObj.value;
	document.custform.submit();
}

//----------------------------------------------------------------------ADDING/REMOVING ITEMS TO-FROM A LIST SCRIPTS
//*******************Add licence/format/site to details from those valid values stored
function addFromList(selObj,theType){
	if((theType == "formats") || (theType == "tformats") || (theType == "prodsites")){
		var theCurrent = eval("document.productform." + theType + "display.value");
		var theCurrentHidden = eval("document.productform." + theType + ".value");
		var theNew = selObj.options[selObj.selectedIndex].value;
		if(theNew != ""){
			var tempFormats = theNew.split(",");
			if(theCurrent == ""){
				eval("document.productform." + theType + "display.value = '" + tempFormats[0] + "'");
				eval("document.productform." + theType + ".value = '" + tempFormats[1] + "'");
			}else{
				eval("document.productform." + theType + "display.value = '" + theCurrent + "," + tempFormats[0] + "'");
				eval("document.productform." + theType + ".value = '" + theCurrentHidden + "," + tempFormats[1] + "'");
			}
		}	
	}else if(theType == "catsites"){
		var theCurrent = eval("document.categoriesform." + theType + "display.value");
		var theCurrentHidden = eval("document.categoriesform." + theType + ".value");
		var theNew = selObj.options[selObj.selectedIndex].value;
		if(theNew != ""){
			var tempFormats = theNew.split(",");
			if(theCurrent == ""){
				eval("document.categoriesform." + theType + "display.value = '" + tempFormats[0] + "'");
				eval("document.categoriesform." + theType + ".value = '" + tempFormats[1] + "'");
			}else{
				eval("document.categoriesform." + theType + "display.value = '" + theCurrent + "," + tempFormats[0] + "'");
				eval("document.categoriesform." + theType + ".value = '" + theCurrentHidden + "," + tempFormats[1] + "'");
			}		
		}
	}else if(theType == "discountsite"){
		var theCurrent = eval("document.discountform.site.value");
		var theNew = selObj.options[selObj.selectedIndex].value;
		if(theNew != ""){		
			if(theCurrent == ""){
				 eval("document.discountform.site.value = '" + theNew + "'");
				 eval("document.discountform.sitedisplay.value = '" + theNew + "'");
			}else{
				eval("document.discountform.site.value = '" + theCurrent + "," + theNew + "'");
				eval("document.discountform.sitedisplay.value = '" + theCurrent + "," + theNew + "'");
			}
		}	
	}else if(theType == "deliverysite"){
		var theCurrent = eval("document.deliveryform.site.value");
		var theNew = selObj.options[selObj.selectedIndex].value;	
		if(theNew != ""){		
			if(theCurrent == ""){
				 eval("document.deliveryform.site.value = '" + theNew + "'");
				 eval("document.deliveryform.sitedisplay.value = '" + theNew + "'");
			}else{
				eval("document.deliveryform.site.value = '" + theCurrent + "," + theNew + "'");
				eval("document.deliveryform.sitedisplay.value = '" + theCurrent + "," + theNew + "'");
			}	
		}
	}else if(theType == "printingsite"){
		var theCurrent = eval("document.printingform.site.value");
		var theNew = selObj.options[selObj.selectedIndex].value;	
		if(theNew != ""){		
			if(theCurrent == ""){
				 eval("document.printingform.site.value = '" + theNew + "'");
				 eval("document.printingform.sitedisplay.value = '" + theNew + "'");
			}else{
				eval("document.printingform.site.value = '" + theCurrent + "," + theNew + "'");
				eval("document.printingform.sitedisplay.value = '" + theCurrent + "," + theNew + "'");
			}	
		}		
	}else if(theType == "salessite"){
		var theCurrent = eval("document.salesform.site.value");
		var theNew = selObj.options[selObj.selectedIndex].value;	
		if(theNew != ""){		
			if(theCurrent == ""){
				 eval("document.salesform.site.value = '" + theNew + "'");
				 eval("document.salesform.sitedisplay.value = '" + theNew + "'");
			}else{
				eval("document.salesform.site.value = '" + theCurrent + "," + theNew + "'");
				eval("document.salesform.sitedisplay.value = '" + theCurrent + "," + theNew + "'");
			}	
		}	
	}else if(theType == "markupsite"){
		var theCurrent = eval("document.markupform.site.value");
		var theNew = selObj.options[selObj.selectedIndex].value;	
		if(theNew != ""){		
			if(theCurrent == ""){
				 eval("document.markupform.site.value = '" + theNew + "'");
				 eval("document.markupform.sitedisplay.value = '" + theNew + "'");
			}else{
				eval("document.markupform.site.value = '" + theCurrent + "," + theNew + "'");
				eval("document.markupform.sitedisplay.value = '" + theCurrent + "," + theNew + "'");
			}	
		}
	}else if(theType == "royalratesite"){
		var theCurrent = eval("document.rateform.site.value");
		var theNew = selObj.options[selObj.selectedIndex].value;	
		if(theNew != ""){		
			if(theCurrent == ""){
				 eval("document.rateform.site.value = '" + theNew + "'");
				 eval("document.rateform.sitedisplay.value = '" + theNew + "'");
			}else{
				eval("document.rateform.site.value = '" + theCurrent + "," + theNew + "'");
				eval("document.rateform.sitedisplay.value = '" + theCurrent + "," + theNew + "'");
			}	
		}
	}else if(theType == "thedisabled"){
		var theCurrent = eval("document.sitesform.thedisabled.value");
		var theCurrentDisp = eval("document.sitesform.thedisableddisp.value");
		var theNew = selObj.options[selObj.selectedIndex].value;	
		if(theNew != ""){
			var theNewArray = theNew.split(",");		
			if(theCurrent == ""){
				 eval("document.sitesform.thedisabled.value = '" + theNewArray[0] + "'");
				 eval("document.sitesform.thedisableddisp.value = '" + theNewArray[1] + "'");
			}else{
				eval("document.sitesform.thedisabled.value = '" + theCurrent + "," + theNewArray[0] + "'");
				eval("document.sitesform.thedisableddisp.value = '" + theCurrentDisp + "," + theNewArray[1] + "'");
			}	
		}				
	}else{
		var theCurrent = eval("document.productform." + theType + ".value");
		var theNew = selObj.options[selObj.selectedIndex].value;
		if(theNew != ""){		
			if(theCurrent == ""){
				 eval("document.productform." + theType + ".value = '" + theNew + "'");
			}else{
				eval("document.productform." + theType + ".value = '" + theCurrent + "," + theNew + "'");
			}
		}
	}	
}
//*******************Add user specific product to customer details from those stored in the database lists
function addFromList2(selObj,theType,theForm){
	var theCurrent = eval("document." + theForm + "." + theType + ".value");
	var theNew = selObj.options[selObj.selectedIndex].value;	
	if(theCurrent == ""){
		 eval("document." + theForm + "."  + theType + ".value = '" + theNew + "'");
	}else{
	 	eval("document." + theForm + "."  + theType + ".value = '" + theCurrent + "|" + theNew + "'");
	}	
}
//*******************Add a defualt product to customer details from those stored in the database lists
function addFromList3(selObj,theForm){	
	var theNew = selObj.options[selObj.selectedIndex].value;
	if(theNew != ""){
		var tempArray = theNew.split(",")
		eval("document." + theForm + ".defproduct.value= '" + tempArray[0] + "'");
		eval("document." + theForm + ".dispdefproduct.value= '" + tempArray[1] + "'");
	}	
}
//*******************Add a admin user to notify by email to company details
function addFromList4(selObj,theForm){	
	var theNew = selObj.options[selObj.selectedIndex].value;
	if(theNew != ""){
		var tempArray = theNew.split(",")
		eval("document." + theForm + ".notifyid.value= '" + tempArray[0] + "'");
		eval("document." + theForm + ".notifyiddisplay.value= '" + tempArray[1] + "'");
	}	
}
//*******************Add a catid based on category name chosen
function addFromList5(selObj,theForm){	
	var theNew = selObj.options[selObj.selectedIndex].value;
	if(theNew != ""){
		var tempArray = theNew.split(",")
		eval("document." + theForm + ".catid.value= '" + tempArray[0] + "'");
		eval("document." + theForm + ".category.value= '" + tempArray[1] + "'");
	}	
}
//*******************Add a salesperson
function addFromList6(selObj,theForm){	
	var theNew = selObj.options[selObj.selectedIndex].value;
	if(theNew != ""){
		var tempArray = theNew.split(",")
		eval("document." + theForm + ".salesperson.value= '" + tempArray[0] + "'");
		eval("document." + theForm + ".salespersondisplay.value= '" + tempArray[1] + "'");
	}	
}
//*******************Add a tariff reference code
function addFromList7(selObj,theForm){	
	var theNew = selObj.options[selObj.selectedIndex].value;
	if(theNew != ""){
		var tempArray = theNew.split(",")
		eval("document." + theForm + ".tariffref.value= '" + tempArray[1] + "'");
		eval("document." + theForm + ".tariffrefdisplay.value= '" + tempArray[1] + "'");
	}	
}
//*******************Remove format/site from product details from those stored in the database lists
function remFromList(selObj,theType){
	//Get current values ids and names
	var theCurrent = eval("document.productform." + theType + "display.value");
	var theCurrentHidden = eval("document.productform." + theType + ".value");
	//Get format to remove
	var theNew = selObj.options[selObj.selectedIndex].value;
	var tempFormats = theNew.split(",");	
	if(theCurrent != ""){
		var newFormatsString = "";
		var newFormatIDsString = "";
		var tempCurrentIDs = theCurrentHidden.split(",");	//Store current values ids and names in arrays
		var tempCurrentNames = theCurrent.split(",");
		var cnt = 0;		
		for(c=0;c < tempCurrentIDs.length;c++){
			if(tempCurrentIDs[c] != tempFormats[1]){
				cnt +=1;
				if(cnt==1){
					newFormatIDsString += tempCurrentIDs[c];
					newFormatsString += tempCurrentNames[c];
				}else{
					newFormatIDsString += "," + tempCurrentIDs[c];
					newFormatsString += "," + tempCurrentNames[c];
				}
			}
		}		
		eval("document.productform." + theType + "display.value = '" + newFormatsString + "'");
		eval("document.productform." + theType + ".value = '" + newFormatIDsString + "'");
	}	
}
//*******************Remove site from category listing
function remFromList2(selObj,theType){
	//Get current values ids and names
	var theCurrent = eval("document.categoriesform." + theType + "display.value");
	var theCurrentHidden = eval("document.categoriesform." + theType + ".value");
	//Get category to remove
	var theNew = selObj.options[selObj.selectedIndex].value;
	var tempFormats = theNew.split(",");	
	if(theCurrent != ""){
		var newFormatsString = "";
		var newFormatIDsString = "";
		var tempCurrentIDs = theCurrentHidden.split(",");	//Store current values ids and names in arrays
		var tempCurrentNames = theCurrent.split(",");
		var cnt = 0;		
		for(c=0;c < tempCurrentIDs.length;c++){
			if(tempCurrentIDs[c] != tempFormats[1]){
				cnt +=1;
				if(cnt==1){
					newFormatIDsString += tempCurrentIDs[c];
					newFormatsString += tempCurrentNames[c];
				}else{
					newFormatIDsString += "," + tempCurrentIDs[c];
					newFormatsString += "," + tempCurrentNames[c];
				}
			}
		}		
		eval("document.categoriesform." + theType + "display.value = '" + newFormatsString + "'");
		eval("document.categoriesform." + theType + ".value = '" + newFormatIDsString + "'");
	}	
}
//*******************Remove site from discounts/delivery/salesperson listing
function remFromList3(selObj,theType){
	//Get current values ids and names
	if(theType == "discountsite"){
		var theCurrentHidden = eval("document.discountform.site.value");
	}else if(theType == "salessite"){
		var theCurrentHidden = eval("document.salesform.site.value");
	}else if(theType == "deliverysite"){
		var theCurrentHidden = eval("document.deliveryform.site.value");
	}else if(theType == "printingsite"){
		var theCurrentHidden = eval("document.printingform.site.value");
	}else if(theType == "markupsite"){
		var theCurrentHidden = eval("document.markupform.site.value");
	}else if(theType == "royalratesite"){
		var theCurrentHidden = eval("document.rateform.site.value");		
	}	
	//Get value to remove
	var theNew = selObj.options[selObj.selectedIndex].value;	
	if((theCurrentHidden != "") && (theNew != "")){
		var newSitesString = "";
		var tempCurrentIDs = theCurrentHidden.split(",");	//Store current values ids and names in arrays
		var cnt = 0;		
		for(c=0;c < tempCurrentIDs.length;c++){
			if(tempCurrentIDs[c] != theNew){
				cnt +=1;
				if(cnt==1){
					newSitesString += tempCurrentIDs[c];
				}else{
					newSitesString += "," + tempCurrentIDs[c];
				}
			}
		}	
		if(theType == "discountsite"){
			eval("document.discountform.sitedisplay.value = '" + newSitesString + "'");
			eval("document.discountform.site.value = '" + newSitesString + "'");
		}else if(theType == "salessite"){
			eval("document.salesform.sitedisplay.value = '" + newSitesString + "'");
			eval("document.salesform.site.value = '" + newSitesString + "'");
		}else if(theType == "deliverysite"){
			eval("document.deliveryform.sitedisplay.value = '" + newSitesString + "'");
			eval("document.deliveryform.site.value = '" + newSitesString + "'");
		}else if(theType == "printingsite"){
			eval("document.printingform.sitedisplay.value = '" + newSitesString + "'");
			eval("document.printingform.site.value = '" + newSitesString + "'");
		}else if(theType == "markupsite"){
			eval("document.markupform.sitedisplay.value = '" + newSitesString + "'");
			eval("document.markupform.site.value = '" + newSitesString + "'");
		}else if(theType == "royalratesite"){
			eval("document.rateform.sitedisplay.value = '" + newSitesString + "'");
			eval("document.rateform.site.value = '" + newSitesString + "'");
		}
	}	
}
//******************Remove admin to notify,salesperson and tariff from company listing
function remFromList4(selObj,theType){
	//Get current values ids and names
	var theCurrent = eval("document.compform." + theType + "display.value");
	var theCurrentHidden = eval("document.compform." + theType + ".value");
	//Get category to remove
	var theNew = selObj.options[selObj.selectedIndex].value;
	var tempFormats = theNew.split(",");	
	if(theCurrent != ""){
		var newFormatsString = "";
		var newFormatIDsString = "";
		var tempCurrentIDs = theCurrentHidden.split(",");	//Store current values ids and names in arrays
		var tempCurrentNames = theCurrent.split(",");
		var cnt = 0;		
		for(c=0;c < tempCurrentIDs.length;c++){
			if(tempCurrentIDs[c] != tempFormats[0]){
				cnt +=1;
				if(cnt==1){
					newFormatIDsString += tempCurrentIDs[c];
					newFormatsString += tempCurrentNames[c];
				}else{
					newFormatIDsString += "," + tempCurrentIDs[c];
					newFormatsString += "," + tempCurrentNames[c];
				}
			}
		}		
		eval("document.compform." + theType + "display.value = '" + newFormatsString + "'");
		eval("document.compform." + theType + ".value = '" + newFormatIDsString + "'");
	}		
}
//******************Remove salesperson from user listing
function remFromList5(selObj,theType){
	//Get current values ids and names
	var theCurrent = eval("document.custform." + theType + "display.value");
	var theCurrentHidden = eval("document.custform." + theType + ".value");
	//Get salesperson to remove
	var theNew = selObj.options[selObj.selectedIndex].value;
	var tempFormats = theNew.split(",");	
	if(theCurrent != ""){
		var newFormatsString = "";
		var newFormatIDsString = "";
		var tempCurrentIDs = theCurrentHidden.split(",");	//Store current values ids and names in arrays
		var tempCurrentNames = theCurrent.split(",");
		var cnt = 0;		
		for(c=0;c < tempCurrentIDs.length;c++){
			if(tempCurrentIDs[c] != tempFormats[0]){
				cnt +=1;
				if(cnt==1){
					newFormatIDsString += tempCurrentIDs[c];
					newFormatsString += tempCurrentNames[c];
				}else{
					newFormatIDsString += "," + tempCurrentIDs[c];
					newFormatsString += "," + tempCurrentNames[c];
				}
			}
		}		
		eval("document.custform." + theType + "display.value = '" + newFormatsString + "'");
		eval("document.custform." + theType + ".value = '" + newFormatIDsString + "'");
	}
}
//******************Remove disabled functionality 
function remFromList6(selObj,theType){
	//Get current values ids and names
	var theCurrent = eval("document.sitesform." + theType + "disp.value");
	var theCurrentHidden = eval("document.sitesform." + theType + ".value");
	//Get functionality to remove
	var theNew = selObj.options[selObj.selectedIndex].value;
	var tempFormats = theNew.split(",");	
	if(theCurrent != ""){
		var newFormatsString = "";
		var newFormatIDsString = "";
		var tempCurrentIDs = theCurrentHidden.split(",");	//Store current values ids and names in arrays
		var tempCurrentNames = theCurrent.split(",");
		var cnt = 0;		
		for(c=0;c < tempCurrentIDs.length;c++){
			if(tempCurrentIDs[c] != tempFormats[0]){
				cnt +=1;
				if(cnt==1){
					newFormatIDsString += tempCurrentIDs[c];
					newFormatsString += tempCurrentNames[c];
				}else{
					newFormatIDsString += "," + tempCurrentIDs[c];
					newFormatsString += "," + tempCurrentNames[c];
				}
			}
		}		
		eval("document.sitesform." + theType + "disp.value = '" + newFormatsString + "'");
		eval("document.sitesform." + theType + ".value = '" + newFormatIDsString + "'");
	}
}


//----------------------------------------------------------------------NAVIGATION SCRIPTS

//*******************Go back from users results page from pages that link out from this page (ensures search query is re-run)
function backFromUser(){
	document.varform.currentPage.value = "1";
	document.varform.action = "userResults.php";
	document.varform.submit();
}
//*******************Go back from company orders page
function backFromCompany(theAction){
	if(theAction == "user"){
		document.varform.action = "user.php";
	}else if(theAction == "all"){
		document.varform.action = "allUsers.php";
	}else{
		document.varform.action = "userResults.php";
	}
	document.varform.submit();
}
//*******************Go back from products results page from pages that link out from this page (ensures search query is re-run)
function backFromProduct(){
	document.varform.action = "productsResults.php";
	document.varform.submit();
}
//*******************Shows the passed page where tabular data is paged out 
function showThisPage(thePage,pageType){
	if(pageType == "allUsers"){										//Action all users
		document.varform.action = "allUsers.php";
		document.varform.currentPage.value = thePage;
		document.varform.submit(); 
	}else if(pageType == "userResults"){										//Action all users
		document.varform.action = "userResults.php";
		document.varform.currentPage.value = thePage;
		document.varform.submit(); 
	}else if(pageType == "allCompanies"){										//Action all users
		document.varform.action = "allCompanies.php";
		document.varform.currentPage.value = thePage;
		document.varform.submit(); 				
	}else if(pageType == "saved"){									//Action saved orders
		document.saveorderform.action = "userSavedOrders.php";
		document.saveorderform.currentPageSave.value = thePage;
		document.saveorderform.submit(); 	
	}else if(pageType == "payment"){								//Action orders requiring payment
		document.varform.action = "paymentsResults.php";
		document.varform.currentPagePay.value = thePage;
		document.varform.submit(); 
	}else if(pageType == "partpayment"){								//Action orders requiring part payment
		document.oordersform.action = "partPayments.php";
		document.oordersform.currentPagePay.value = thePage;
		document.oordersform.submit(); 
	}else if(pageType == "partinvoicepayments"){								//Action orders requiring part payment
		document.oordersform.action = "partInvoicePayments.php";
		document.oordersform.currentPagePay.value = thePage;
		document.oordersform.submit(); 	
	}else if(pageType == "orders"){									//Action user orders 
		document.prevorderform.action = "userOrders.php";
		document.prevorderform.currentPageOrders.value = thePage;
		document.prevorderform.submit(); 
	}else if(pageType == "licenceman"){									//Action user orders 
		document.prevorderform.action = "licenceManagement.php";
		document.prevorderform.currentPageOrders.value = thePage;	
		document.prevorderform.submit(); 		
	}else if(pageType == "ordersResults"){							//Action order results 
		document.varform.action = "ordersResults.php";
		document.varform.currentPage.value = thePage;
		document.varform.submit(); 
	}else if(pageType == "adminorders"){									//Action admin user orders 
		document.varform.action = "userOrders.php";
		document.varform.currentPageOrders.value = thePage;
		document.varform.submit(); 
	}else if(pageType == "obliqueResults"){									//Action admin user orders 
		document.varform.action = "obliqueResults.php";
		document.varform.currentPage.value = thePage;
		document.varform.submit()		
	}else if(pageType == "previewsResults"){						//Action preview results 
		document.varform.action = "previewsResults.php";
		document.varform.currentPage.value = thePage;
		document.varform.submit(); 
	}else if(pageType == "deliveryResults"){						//Action delivery results 
		document.varform.action = "deliveryResults.php";
		document.varform.currentPage.value = thePage;
		document.varform.submit(); 
	}else if(pageType == "userPreviews"){							//Action user previews 
		document.varform.action = "userPreviews.php";
		document.varform.currentPage.value = thePage;
		document.varform.submit(); 		
	}else if(pageType == "userOrders"){									//Action admin user orders 
		document.varform.action = "userOrders.php";
		document.varform.currentPage.value = thePage;
		document.varform.submit(); 
	}		 
}
//*******************Submits the admin form setting the specified page.
function submitAdminForm(theAction){
	document.adminform.action = theAction + ".php";
	document.adminform.submit();
}
//*******************Shows the selected item
function getItem(theID,thePage,theName,theAction,formName){
	if(theAction == "up"){
		eval("document." + formName + ".action = '" +  thePage + ".php?action=up&" + theName + "=" + theID + "'");
		eval("document." + formName + ".submit()");	
	}	
}
//*******************Shows the selected user orders
function getUserOrders(theUserID){
	document.varform.userid.value = theUserID;
	document.varform.compid.value = "";
	document.varform.currentPage.value = "1";
	document.varform.action = "userOrders.php";	
	document.varform.submit();
}
//*******************Shows the selected user orders
function getCompOrders(theCompID){
	document.varform.compid.value = theCompID;
	document.varform.userid.value = "";
	document.varform.currentPage.value = "1";
	document.varform.action = "userOrders.php";
	document.varform.submit();
}
//*******************Shows the selected user details
function showUserDetails(theUserID){
	document.varform.userid.value = theUserID;
	document.varform.action = "user.php";
	document.varform.submit();
}
//*******************Shows the selected user transactions
function getUserTransactions(theUserID){
	document.varform.userid.value = theUserID;
	document.varform.action = "userTransactions.php";
	document.varform.submit();
}
//*******************Shows the selected company transactions
function getCompanyTransactions(theCompanyID){
	document.varform.companyid.value = theCompanyID;
	document.varform.action = "companyTransactions.php";
	document.varform.submit();
}
//*******************Shows the selected user MasterMap Preview requests
function getUserPreviews(theUserID){
	document.varform.userid.value = theUserID;
	document.varform.action = "userPreviews.php";
	document.varform.submit();
}
//*******************Show the invoice statement
function showInvoiceStatement(theNo,theSrc){
	if(theSrc == "admindisplay"){
		var theInvoiceType = "display";	
		document.usersform.cid.value = theNo;		
		document.usersform.action = "showStatement.php";
		document.usersform.target = "_blank";	
		document.usersform.submit();		
	}else if(theSrc == "userdisplay"){
		var theInvoiceType = "display";	
		document.oordersform.cid.value = theNo;		
		document.oordersform.action = "admin/showStatement.php";
		document.oordersform.target = "_blank";	
		document.oordersform.submit();
	}	
}
//*******************Show the company invoice statement (HTML old not used)
function showCompanyInvoiceStatement(theNo,theSrc,theForm){
	if(theSrc == "admindisplay"){			
		eval("document." + theForm + ".action = 'showCompanyStatement.php'");		
	}else if(theSrc == "customerdisplay"){	
		eval("document." + theForm + ".action = 'admin/showCompanyStatement.php'");
	}
	eval("document." + theForm + ".companyid.value = '" + theNo + "'");		
	eval("document." + theForm + ".target = '_blank'");	
	eval("document." + theForm + ".submit()");	
}
//*******************Show the company invoice statement (PDF version)
function showCompanyInvoiceStatementPDF(theNo,theSrc,statementIndex,linkMessage){
	if(theSrc == "customerdisplay"){
		tt_HideTip();				//Ensure tool tip is destroyed
	}
	document.getElementById("statementLink" + statementIndex).innerHTML = "<p style='text-align:right;'><em><img src='../images/loader.gif'>  Generating...</em></p>";
	var qstring = "companyid=" + theNo + "&theSrc=" + theSrc + "&statementIndex=" + statementIndex + "&linkMessage=" + linkMessage;
	if(theSrc == "admindisplay"){
		var statementPDFReq = new ajaxObject('showCompanyStatementPDF.php',statementPDFResponse);
	}else if(theSrc == "customerdisplay"){
		var statementPDFReq = new ajaxObject('admin/showCompanyStatementPDF.php',statementPDFResponse);
	}	
	statementPDFReq.update(qstring,'POST');
}
//*******************Response from generating statement as PDF
function statementPDFResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values	
		if(responseText != ""){	
			if(responseText.indexOf("TCPDF ERROR") != -1){
				showDialog('Error','There has been a problem generating the statement. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="reloadAfterInvoiceFail();" >','errordialog');
			}else{	
				var tempArray = new Array();
				tempArray = responseText.split("|");		
				if(tempArray[0] == "error"){	
					showDialog('Error','There has been a problem generating the statement. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
				}else{
					if(tempArray[2] == "admindisplay"){				
						document.getElementById("statementLink" + tempArray[4]).innerHTML = "<a href='javascript:showCompanyInvoiceStatementPDF(\"" + tempArray[1] + "\",\"" + tempArray[2] + "\",\"" + tempArray[4] + "\",\"" + tempArray[5] + "\");'>" + tempArray[5] + "</a>";
					}else{					
						document.getElementById("statementLink" + tempArray[4]).innerHTML = "<p style='text-align:right;'><a href='javascript:showCompanyInvoiceStatementPDF(\"" + tempArray[1] + "\",\"" + tempArray[2] + "\",\"" + tempArray[4] + "\",\"" + tempArray[5] + "\");' onmouseover='Tip(\"Click to view current statement of account\");'>" + tempArray[5] + "</a></p>";
					}
					//Ensure the url agrees with that of the current white label
					var tempURLArray = document.URL.split("/");
					var pdfPath ="";
					if(document.URL.indexOf("/admin/") == -1){		//Accessing from customer area
						var toMinus = 1;
						window.location="downloadPDF.php?name=" + tempArray[3] + ".pdf";
					}else{											//Accessing from admin area
						var toMinus = 2;
						window.location="../downloadPDF.php?name=" + tempArray[3] + ".pdf";
					}
					//OLD Show in popup
					//for(u=0;u < (tempURLArray.length-toMinus);u++){
					//	pdfPath += tempURLArray[u] + "/";
					//}
					//var pdfURL = pdfPath + "admin/excelexports/" + tempArray[3] + ".pdf";
					//var winName =  "pdfstatement";
					//var features = "toolbar=no,scrollbars=yes,resizable=yes,width=600,height=600";
					//window.open(pdfURL,winName,features); 
					 //OLD Show in new tab  
					/*if(document.getElementById("usersform") != null){		
						document.usersform.action = pdfURL;
						document.usersform.target = "_blank";	
						document.usersform.submit();
						document.usersform.action = "";
						document.usersform.target = "_self";		
					}else{
						document.invoiceform.action = pdfURL;
						document.invoiceform.target = "_blank";	
						document.invoiceform.submit();
						document.invoiceform.action = "";
						document.invoiceform.target = "_self";
					}*/				
				}
			}
		}else{
			showDialog('Error','There has been a problem generating the statement. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="reloadAfterInvoiceFail();" >','errordialog');
		}
	}
}
//*******************Shows the company info for multi-user account
function showCompany(){
	document.custform.action = "company.php";
	document.custform.submit();
}
//*******************Shows the company info for multi-user account - opened from the users listing
function showCompanyByID(passedCompID,passedUserID){
	document.varform.userid.value = passedUserID;    //usersform
	document.varform.companyid.value = passedCompID;
	document.varform.action = "company.php";	
	document.varform.submit();
}
//*******************Shows the company info (called from  company search pages)
function showCompanyInfo(compId){
	document.compform.companyid.value = compId;
	document.compform.action = "company.php";
	document.compform.submit();
}
//*******************Create a new company entry based on existing user's account
function createNewCompany(){
	document.custform.action = "newCompany.php";
	document.custform.submit();
}
//*******************Shows the multi-user info for multi-user account
function showMultiUser(){
	document.compform.filterofficename.value = document.compform.companyid.value;
	document.compform.action = "companyUsers.php";
	document.compform.submit();
}
//*******************Shows user details - called from link on the company users listing
function showMultiUserDetails(passedID){
	document.custform.userid.value = passedID;
	document.custform.action = "user.php";
	document.custform.submit();
}
//*******************Changes the year of the yearly transactions breakdown
function showTranactionsByYear(selObj,theType){	
	var theYear = selObj.options[selObj.selectedIndex].value;
	document.transactionsform.theSelectedYear.value = theYear;
	if(theType == "user"){
		document.transactionsform.action = "userTransactions.php";	
	}else{
		document.transactionsform.action = "companyTransactions.php";
	}
	document.transactionsform.target = '_self';
	document.transactionsform.submit();
}

//----------------------------------------------------------------------SEARCHING AND ASSOCIATED SCRIPTS

//*******************Defines the selected search criteria for showing user orders
function setSearchCriteria(theForm,theHidden,theValue,theCheckBox,theType){
	if(theType == "checkbox"){
		if(theCheckBox.checked){
			eval("document." + theForm + "." + theHidden + ".value = '" + theValue + "'");
		}else{
			eval("document." + theForm + "." + theHidden + ".value = ''");
		}
	}else{
		eval("document." + theForm + "." + theHidden + ".value = '" + theValue + "'");
	}
	eval("document." + theForm + ".submit()");					//Refresh page to reflect the query
}
//*******************Defines the selected search criteria for showing user cost
function setSearchCriteria2(theForm,theHidden,theValue,theCheckBox,theType){
	if(theType == "checkbox"){
		if(theCheckBox.checked){
			eval("document." + theForm + "." + theHidden + ".value = '" + theValue + "'");
			//Ensure all other check boxes are turned off
			for(c=1; c <= 4; c++){
				if(eval("document." + theForm + ".checkdate" + c + ".name") != theCheckBox.name){
					eval("document." + theForm + ".checkdate" + c + ".checked = false");
				}
			}
		}else{
			eval("document." + theForm + "." + theHidden + ".value = ''");
		}
	}else{
		eval("document." + theForm + "." + theHidden + ".value = '" + theValue + "'");
	}
}
//*******************Runs predefined user search
function quickUserSearch(theType){
	//Reset
	document.getElementById("quickSearchMulti").value = "";
	document.getElementById("quickSearchSingle").value = "";
	document.getElementById("quickSearchOrdered").value = "";
	//Set the type to query
	if(theType == "multi"){						//Multi accounts
		document.getElementById("quickSearchMulti").value = "on";
	}else if(theType == "single"){				//Single user accounts
		document.getElementById("quickSearchSingle").value = "on";
	}else if(theType == "ordered"){				//Orders this month 
		document.getElementById("quickSearchOrdered").value = "on";
	}
	document.searchform.submit();	
}
//*******************Defines the selected filter for the customer orders to display
function getFilterCriteria(selObj,theHidden){
	if(selObj.value == "off"){
		selObj.value = "on";
		eval("document.varform." + theHidden + ".value = 'on'");
	}else{
		selObj.value = "off";
		eval("document.varform." + theHidden + ".value = 'off'");
	}
	//Ensure show first page of new search criteria for saved and purchased orders.
	if(document.getElementById ("currentPageOrders") != null){
		document.varform.currentPageOrders.value = 1;   
	}
	if(document.getElementById ("currentPageSave") != null){
		document.varform.currentPageSave.value = 1;   
	}		
	document.varform.submit();
}
//*******************Defines the selected criteria for the customer search
function getSearchCriteria(selObj){
	if(selObj.value == "off"){
		selObj.value = "on";	
	}else{
		selObj.value = "off";
	}
}
//*******************Defines the selected criteria for the royalty returns search
function getReturnSearch(selObj,theHidden){
	document.searchform.retoptions.value = 'off';
	document.searchform.searchview.value = 'off';
	document.searchform.searchdraw.value = 'off';
	document.searchform.searchpc.value = 'off';
	document.searchform.searchprod.value = 'off';
	document.searchform.searchos.value = 'off';
	document.searchform.searchdel.value = 'off';
	document.searchform.searchgaz.value = 'off';
	document.searchform.searchob.value = 'off';
	document.searchform.searchadd.value = 'off';
	document.searchform.searchcosts.value = 'off';
	document.searchform.searchgm.value = 'off';
	selObj.value = "on";
	eval("document.searchform." + theHidden + ".value = 'on'");
	//Enable-disable the product supplier options	
	if((document.getElementById("ossupplier") != null) && (document.getElementById("othersupplier") != null)){
		if(theHidden == "searchprod"){
			document.getElementById("ossupplier").disabled = false;
			document.getElementById("othersupplier").disabled = false;
		}else{
			document.getElementById("ossupplier").disabled = true;
			document.getElementById("othersupplier").disabled = true;
		}
	}		
}
//*******************Defines the selected supplier for the product royalty returns search
function setSupplierFilter(selObj,passedSupplier){
	//Define the filter string by defining what options are checked
	if((document.getElementById("ossupplier").checked) && (document.getElementById("othersupplier").checked)){
		document.searchform.prodsupplier.value = "all";
	}else if(document.getElementById("ossupplier").checked){
		document.searchform.prodsupplier.value = "os";
	}else if(document.getElementById("othersupplier").checked){
		document.searchform.prodsupplier.value = "other";		
	}else{
		//Nothing checked - so don't allow this to be unchecked
		selObj.checked = true;	
	}
}
//*******************Defines if non-royalty items are shown for the product royalty returns search
function setRoyaltyFilter(selObj){
	if(document.getElementById("includenoroyalty").checked){
		document.searchform.shownonroyalty.value = "yes";
	}else{	
		document.searchform.shownonroyalty.value = "no";
	}
}
//*******************Get returns for 'Today'
function getTodays(theType){
	//Get today's date
	var aDate = new Date();
	var theDayValue = aDate.getDate();
	var theMonthValue = (aDate.getMonth() + 1);
	if(theMonthValue < 10){
		theMonthValue = "0" + String(theMonthValue);
	}
	var theYearValue = aDate.getFullYear();
	//Fill form boxes with values relating to today
	document.searchform.startday.value = theDayValue;
	document.searchform.startmonth.value = theMonthValue;
	document.searchform.startyear.value = theYearValue;
	document.searchform.endday.value = theDayValue;
	document.searchform.endmonth.value = theMonthValue;
	document.searchform.endyear.value = theYearValue;	
	//Submit form to show/export the returns/orders
	if(theType == "returns"){
		submitSearchForm("returnsResults");
	}else if(theType == "orders"){
		submitSearchForm("ordersResults");
	}else if(theType == "card"){
		submitSearchForm("cardResults");
	}else if(theType == "exportOrders"){
		submitSearchForm("exportOrders");
	}else if(theType == "exportReturns"){
		submitSearchForm("exportReturns");	
	}else if(theType == "exportCard"){
		submitSearchForm("exportCard");			
	}	
}
//*******************Submits the search form on the orders index page to show orders or previews
function submitSearchForm(theAction){
	var isOK = true;
	//Ensure check boxes have correct value (may be wrong if form is submitted after 'back' button used
	if((theAction == "ordersResults") || (theAction == "previewsResults") || (theAction == "userResults") || (theAction == "paymentsResults") || (theAction == "obliqueResults") || (theAction == "deliveryResults") || (theAction == "exportOrders") || (theAction == "exportOblique") || (theAction == "exportPreviews") || (theAction == "exportDelivery")){
		if(document.searchform.outlet.checked){
			document.searchform.outlet.value = "on";
		}else if(document.searchform.company.checked){
			document.searchform.company.value = "on";
		}else if(document.searchform.name.checked){
			document.searchform.name.value = "on";
		}	
	}	
	if((theAction == "ordersResults") || (theAction == "previewsResults") || (theAction == "obliqueResults") || (theAction == "exportOrders") || (theAction == "exportOblique")){
		if(document.searchform.companyid.checked){		
			document.searchform.companyid.value = "on";
		}
		isOK = checkStartDate();			//Check a start date has been entred
		if(isOK == false){
			showDialog('Warning','Ensure a start date has been entred.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');		
		}
	}
	if((theAction == "cardResults") || (theAction == "exportCard")){
		isOK = checkStartDate();			//Check a start date has been entred
		if(isOK == false){
			showDialog('Warning','Ensure a start date has been entred.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');		
		}
	}
	if(theAction == "userResults"){
		//Reset quick searches
		document.getElementById("quickSearchMulti").value = "";
		document.getElementById("quickSearchSingle").value = "";
		document.getElementById("quickSearchOrdered").value = "";	
		//Check necessary input added
		if((document.searchform.companyid.checked) && (document.searchform.compid.value == "")){
			isOK = false;
			showDialog('Warning','Ensure "Company ID" is entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}
		if((document.searchform.company.checked) && (document.searchform.compname.value == "")){
			isOK = false;
			showDialog('Warning','Ensure "Company Name" is entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}
		if((document.searchform.userid.checked) && (document.searchform.thecustid.value == "")){
			isOK = false;
			showDialog('Warning','Ensure "Customer ID" is entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}
		if((document.searchform.name.checked) && (document.searchform.custfirstname.value == "") && (document.searchform.custsecondname.value == "")){
			isOK = false;
			showDialog('Warning','Ensure "Name" is entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}
		if((document.searchform.outlet.checked) && (document.searchform.outcode.value == "")){
			isOK = false;
			showDialog('Warning','Ensure "Outlet Code" is entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}
		if(document.searchform.frozen.checked){
			document.searchform.frozen.value = "on";
		}else if(document.searchform.invoice.checked){
			document.searchform.invoice.value = "on";
		}	
	}
	if(theAction == "paymentsResults"){
		if(document.searchform.outstanding.checked){		
			document.searchform.outstanding.value = "on";
		}	
	}
	if(theAction == "companyResults"){
		if(document.searchform.companyname.checked){		
			document.searchform.companyname.value = "on";
		}
		if(document.searchform.companyid.checked){		
			document.searchform.companyid.value = "on";
		}	
	}
	if(theAction == "debtResults"){
		if(document.searchform.company.checked){		
			document.searchform.company.value = "on";
		}
		if(document.searchform.companyid.checked){		
			document.searchform.companyid.value = "on";
		}	
	}
	if((theAction == "returnsResults") || (theAction == "exportReturns")){
		isOK = checkStartDate();			//Check a start date has been entered
		if(isOK == false){
			showDialog('Warning','Ensure a start date has been entred.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');		
		}
	}
	//Check the period is not > than 100 days
	if((theAction == "ordersResults") || (theAction == "previewsResults") || (theAction == "userResults") || (theAction == "paymentsResults") || (theAction == "obliqueResults") || (theAction == "deliveryResults") || (theAction == "exportOrders") || (theAction == "exportOblique") || (theAction == "exportPreviews") || (theAction == "exportDelivery") || (theAction == "returnsResults") || (theAction == "exportReturns")){	
		var testStartDate = new Date(Number(document.searchform.startyear.value), Number(document.searchform.startmonth.value), Number(document.searchform.startday.value));
		var testEndDate = new Date(Number(document.searchform.endyear.value), Number(document.searchform.endmonth.value), Number(document.searchform.endday.value));
		var one_day=1000*60*60*24;
		var dayDifference = Math.ceil((testEndDate.getTime() - testStartDate.getTime())/(one_day))
		if(dayDifference > 100){
			isOK = false
			showDialog('Warning','Ensure your have not entered a period longer than 100 days.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');		
		}	
	}	
	if(isOK){
		if((theAction == "exportOrders") || (theAction == "exportOblique") || (theAction == "exportPreviews") || (theAction == "exportDelivery")){
			exportOrdersToXLS(theAction);
		}else if(theAction == "exportReturns"){
			exportReturnsToXLS(theAction);
		}else if(theAction == "exportCard"){	
			exportCardHistoryToXLS(theAction);
		}else{
			eval("document.searchform.action = '" + theAction + ".php'");
			document.searchform.submit();
		}
	}
}

//----------------------------------------------------------------------EXCEL EXPORTING SCRIPTS

//****************Runs script to save the orders query straight to Excel
function exportOrdersToXLS(theAction){	
	var qstring = "name=" + document.searchform.name.value;
	qstring += "&custfirstname=" + document.searchform.custfirstname.value;
	qstring += "&custsecondname=" + document.searchform.custsecondname.value;	
	qstring += "&outlet=" + document.searchform.outlet.value;
	qstring += "&outcode=" + document.searchform.outcode.value;
	qstring += "&userid=" + document.searchform.userid.value;
	qstring += "&thecustid=" + document.searchform.thecustid.value;
	qstring += "&company=" + document.searchform.company.value;
	qstring += "&compname=" + document.searchform.compname.value
	qstring += "&sales=" + document.searchform.sales.value;
	qstring += "&salesperson=" + document.searchform.salesperson.value
	qstring += "&startday=" + document.searchform.startday.value;
	qstring += "&startmonth=" + document.searchform.startmonth.value
	qstring += "&startyear=" + document.searchform.startyear.value;
	qstring += "&endday=" + document.searchform.endday.value
	qstring += "&endmonth=" + document.searchform.endmonth.value;
	qstring += "&endyear=" + document.searchform.endyear.value		
	//Show progress
	document.getElementById("exportprog").innerHTML = "<p align='right'><img src='../images/loader.gif'>  Please wait</p>";
	//Call the script to save as Excel
	var xlsReq = new ajaxObject(theAction + '.php', handleSaveXLSResponse);
	xlsReq.update(qstring,'POST');
}
//****************Runs script to save the card history query straight to Excel
function exportCardHistoryToXLS(theAction){	
	var qstring = "&startday=" + document.searchform.startday.value;
	qstring += "&startmonth=" + document.searchform.startmonth.value
	qstring += "&startyear=" + document.searchform.startyear.value;
	qstring += "&endday=" + document.searchform.endday.value
	qstring += "&endmonth=" + document.searchform.endmonth.value;
	qstring += "&endyear=" + document.searchform.endyear.value		
	//Show progress
	document.getElementById("exportprog").innerHTML = "<p align='right'><img src='../images/loader.gif'>  Please wait</p>";
	//Call the script to save as Excel
	var xlsReq = new ajaxObject(theAction + '.php', handleSaveXLSResponse);
	xlsReq.update(qstring,'POST');
}
//****************Runs script to save the returns query straight to Excel
function exportReturnsToXLS(theAction){
	var qstring = "&searchview=" + document.searchform.searchview.value;
	qstring += "&searchdraw=" + document.searchform.searchdraw.value;
	qstring += "&searchpc=" + document.searchform.searchpc.value;
	qstring += "&searchprod=" + document.searchform.searchprod.value;
	qstring += "&searchos=" + document.searchform.searchos.value;
	qstring += "&searchdel=" + document.searchform.searchdel.value;
	qstring += "&searchgaz=" + document.searchform.searchgaz.value;
	qstring += "&searchob=" + document.searchform.searchob.value;
	qstring += "&searchadd=" + document.searchform.searchadd.value;
	qstring += "&searchcosts=" + document.searchform.searchcosts.value;
	qstring += "&searchgm=" + document.searchform.searchgm.value;
	qstring += "&prodsupplier=" + document.searchform.prodsupplier.value;
	qstring += "&shownonroyalty=" + document.searchform.shownonroyalty.value;
	qstring += "&startday=" + document.searchform.startday.value;
	qstring += "&startmonth=" + document.searchform.startmonth.value
	qstring += "&startyear=" + document.searchform.startyear.value;
	qstring += "&endday=" + document.searchform.endday.value
	qstring += "&endmonth=" + document.searchform.endmonth.value;
	qstring += "&endyear=" + document.searchform.endyear.value			
	//Show progress
	document.getElementById("exportprog").innerHTML = "<p align='right'><img src='../images/loader.gif'>  Please wait</p>";
	//Call the script to save as Excel		
	var xlsReq = new ajaxObject(theAction + '.php', handleSaveXLSResponse);
	xlsReq.update(qstring,'POST');
}
//****************Response from generating the excel file
function handleSaveXLSResponse(responseText, responseStatus){
	if(responseStatus == 200){
		document.getElementById("exportprog").innerHTML = "";
		if(responseText != ""){
			var responseArray = responseText.split("|");	
			if(responseArray[1] == "OK"){											//Call page to download the created file				
				window.location="downloadExcel.php?name=" + responseArray[2];
			}else{
				showDialog('Error', responseArray[3] + '<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
			}
		}else{
			showDialog('Error','There has been a problem exporting. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');		
		}
	}	
}

//----------------------------------------------------------------------MULTI USER SCRIPTS

//*******************Returns list of users by search name (used to move customers to company account structure)
function findUserByName(passedRecordID){
	if((document.getElementById("custfirstname").value == "") && (document.getElementById("custsecondname").value == "")) {
		showDialog('Warning','Please enter a search value.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');	
	}else{
		var qstring = "custfirstname=" + document.getElementById("custfirstname").value + "&custsecondname=" + document.getElementById("custsecondname").value + "&recordid=" + passedRecordID + "&companysite=" + document.getElementById("companysite").value;
		var findUsersReq = new ajaxObject('findUserByName.php', findUsersResponse);		
		findUsersReq.update(qstring,'POST');
	}
}
//****************Response from finding users
function findUsersResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");
			if(tempArray[0] == "yes"){
				document.getElementById("searchresults").innerHTML = tempArray[2];
				document.getElementById("searchresults").style.display = "block";
			}else{								//Show the error message
				showDialog('Error',tempArray[1] + '<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
			}
		}else{
			showDialog('Error','There has been a problem searching. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
		}
	}
}
//****************Show the choosen customer in the input boxes ready to add as new user
function chooseUser(customerID,customerName,theRecordID){
	if(customerID != ""){
		document.getElementById("existingid_" + theRecordID).value = customerID;
		document.getElementById("dispcustname").value = customerName;
		document.getElementById("searchresults").style.display = "none";
	}
}
//*******************Returns list of users by search name (used to move customers to company account structure)
function findUserByID(passedRecordID){
	if(document.getElementById("existingid_" + passedRecordID).value == "") {
		showDialog('Warning','Please enter a customer ID.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');	
	}else{
		var qstring = "custid=" + document.getElementById("existingid_" + passedRecordID).value;
		var findUsersReq = new ajaxObject('findUserByID.php', findUsersResponse2);		
		findUsersReq.update(qstring,'POST');
	}
}
//****************Response from finding users
function findUsersResponse2(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");
			if(tempArray[0] == "yes"){
				document.getElementById("dispcustname").value = tempArray[2];
				
			}else{								//Show the error message
				showDialog('Error',tempArray[1] + '<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
			}
		}else{
			showDialog('Error','There has been a problem searching. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
		}
	}
}
//*******************Adds existing user as a multi-user in multi-user account
function addMultiUser(itemID,isAdmin){		
	var passedID = eval("document.custform.existingid_" + itemID  + ".value");
	var qstring = "cid=" + passedID + "&itemid=" + itemID;
	if(isAdmin == "yes"){
		var findOrdersReq = new ajaxObject('../getPrevOrders.php', prevOrdersResponse);
	}else{
		var findOrdersReq = new ajaxObject('getPrevOrders.php', prevOrdersResponse);
	}		
	findOrdersReq.update(qstring,'POST');	
}
//*******************Returns if previous orders and update office accordingly.
function prevOrdersResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");
			var hasOrders = tempArray[0];
			var custID = tempArray[1];
			var itemID = tempArray[2];
			//Update based on if there are existing users
			if(custID == ""){
				showDialog('Error','Could not find customer with this ID. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
			}else{	
				updateUserOffice(custID,itemID,hasOrders);
			}	
		}else{
			showDialog('Error','There has been a problem updating. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
		}
	}
}
//*******************Updates the multi-user's office in multi-user account
function updateUserOffice(custID,itemID,hasOrders){
	if(hasOrders == "false"){										//User has no existing orders update as usual
		var dialogContent = "This will update user information. Are you sure?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='applyUpdateUserOfficeitemID(\"" + custID + "\",\"" + itemID + "\",\"" + hasOrders + "\");'>  <input type='button' value='No' id='noButton' onclick='hideDialog();' >"
		showDialog('',dialogContent,'prompt');
	}else{														//User has existing orders provide options for moving the account			
		document.custform.upID.value = custID;		
		document.custform.upPmissions.value = eval("document.custform.permissions_" + itemID + ".value");
		document.custform.upCompany.value = eval("document.custform.company_" + itemID + ".value");			
		document.custform.action = "officeTransfer.php";
		document.custform.submit(); 		
	}
}
function applyUpdateUserOfficeitemID(custID,itemID,hasOrders){
	document.custform.upID.value = custID;
	document.custform.upAction.value = "move";  //"update";
	document.custform.upPmissions.value = eval("document.custform.permissions_" + itemID + ".value");
	document.custform.upCompany.value = eval("document.custform.company_" + itemID + ".value");			
	document.custform.submit(); 
}
//*******************Adds a completely new multi-user in multi-user account
function addNewMultiUser(itemID){
	var dialogContent = "This will add a new user to the company. Are you sure?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='applyAddNewMultiUser(\"" + itemID + "\");'>  <input type='button' value='No' id='noButton' onclick='hideDialog();' >"
	showDialog('',dialogContent,'prompt');
}
function applyAddNewMultiUser(itemID){
	var	allOK = true;	
	document.custform.upAction.value = "new";
	document.custform.upID.value = "";
	document.custform.upTitle.value = eval("document.custform.title_" + itemID  + ".value");
	document.custform.upFirstName.value = eval("document.custform.firstname_" + itemID  + ".value");
	document.custform.upSecondName.value = eval("document.custform.secondname_" + itemID  + ".value");
	document.custform.upUname.value = eval("document.custform.email_" + itemID  + ".value");
	document.custform.upPmissions.value = eval("document.custform.permissions_" + itemID + ".value");
	document.custform.upCompany.value = eval("document.custform.company_" + itemID + ".value");
	document.custform.upPwd.value = eval("document.custform.pwd_" + itemID + ".value");
	var testPwd = eval("document.custform.pwd1_" + itemID + ".value");			
	if(testPwd != document.custform.upPwd.value){
		showDialog('Warning','Password not confirmed correcty. Please type again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		allOK = false;
	}
	if(!document.custform.upPwd.value.match("^[a-z|A-Z|0-9]*$")) {
		showDialog('Warning','Invalid Password. Password must contain only numbers and letters.<br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');				
		allOK = false;		
	}
	if((document.custform.upPwd.value.length > 20) || (document.custform.upPwd.value.length < 6) ){
		showDialog('Warning','Please ensure "Password" is between 6 and 20 characters.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		allOK = false;
	}
	if((document.custform.upFirstName.value == "") || (document.custform.upSecondName.value == "") || (document.custform.upUname.value == "") || (document.custform.upPmissions.value == "") || (document.custform.upCompany.value == "") || (document.custform.upPwd.value == "")){
		showDialog('Warning','Please ensure all required input is entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		allOK = false;	
	}
	if(allOK){
		document.custform.submit(); 
	}
}
//*******************Shows company info when returning from multi-users page
function backFromMultiUsers(){
	document.custform.action = "company.php";
	document.custform.submit();		
}
//*******************Update the action when moving multi-user's company (cancel,move and clone and move)
function updateUserAction(theValue){
	document.custform.upAction.value = theValue;
}
//*******************Updates the multi-user permissions in multi-user account
function updateUserPermissions(custID,itemID){
	var dialogContent = "This will update user information. Are you sure?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='applyUserPermissionsUpdate(\"" + custID + "\",\"" + itemID + "\");'>  <input type='button' value='No' id='noButton' onclick='hideDialog();' >"
	showDialog('',dialogContent,'prompt');
}
function applyUserPermissionsUpdate(custID,itemID){
	document.custform.upID.value = custID;
	document.custform.upAction.value = "update";
	document.custform.upPmissions.value = eval("document.custform.permissions_" + itemID + ".value");
	document.custform.submit(); 
}
//*******************Defines the selected filter for multi-users to display
function getFilterCriteria2(theHidden1,theHidden2){
	if(eval("document.custform." + theHidden1 + ".value == 'off'")) {
		eval("document.custform." + theHidden1 + ".value = 'on'");
		eval("document.custform." + theHidden2 + ".value = 'off'");
	}else{
		eval("document.custform." + theHidden1 + ".value = 'off'");
		eval("document.custform." + theHidden2 + ".value = 'on'");
	}	
	document.custform.submit();
}
//*******************Defines the office filter for multi-users to display
function getOfficeFilter(selObj){
	var filterOffice = selObj.options[selObj.selectedIndex].value;
	if(filterOffice != ""){
		document.custform.filterofficename.value = filterOffice;
		document.custform.submit();
	}
}
//*******************Goes back to multi user listing from new office
function backToMultiUsers(){
	document.compform.action = "companyUsers.php";
	document.compform.submit();
}

//----------------------------------------------------------------------VALIDATION SCRIPTS

//*******************Form validation
function adminFormValidator(theForm,theType){
	if(theType == "user"){ 										//**Checking customer update details.
		//if (theForm.title.value == "") {
		//	showValidateErrorDialog("Title");
		//	return (false);
		//}
		if (theForm.firstname.value == "") {
			showValidateErrorDialog("First Name");
			return (false);
		}
		if (theForm.secondname.value == "") {
			showValidateErrorDialog("Second Name");
			return (false);
		}	
		if (theForm.email.value==""){
			showValidateErrorDialog("Email Address");
			return (false);
		}		
		if(emailCheck (theForm.email.value) == false){
			theForm.email.focus();
			return (false);	
		}
		return (true);		
	}else if(theType == "register"){ 										//**Checking customer update details.
		if (theForm.firstname.value == "") {
			showValidateErrorDialog("First Name");
			return (false);
		}
		if (theForm.secondname.value == "") {
			showValidateErrorDialog("Second Name");
			return (false);
		}	
		if (theForm.email.value==""){
			showValidateErrorDialog("Email Address");
			return (false);
		}		
		if(emailCheck (theForm.email.value) == false){
			theForm.email.focus();
			return (false);	
		}	
		//Check the 'Password' field			
		if (theForm.pwd1.value == "") {											//Password field must not be empty
			showDialog('Warning','Please enter a value for the "Password" field.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			return (false);
		}else if(!theForm.pwd1.value.match("^[a-z|A-Z|0-9]*$")) {
			showDialog('Warning','Invalid Password. Password must contain only numbers and letters.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');				
			return (false);		
		}else if(theForm.pwd1.value != theForm.pwd2.value) {
			showDialog('Warning','"Password" not verified correctly.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			return (false);
		}
		return (true);	
	}else if(theType == "product"){											//**Checking product update details.
		if(theForm.category.value == "") {
			showValidateErrorDialog("Category");
			return (false);
		}
		if(theForm.product.value == "") {
			showValidateErrorDialog("Product");
			return (false);
		}
		if(theForm.style.value == "") {
			showValidateErrorDialog("Style");
			return (false);
		}
		if(theForm.orderindex.value == "") {
			showValidateErrorDialog("Display Order Index");
			return (false);
		}
		if(theForm.licences.value == "") {
			showValidateErrorDialog("Available Licences");
			return (false);
		}
		if(theForm.proddesc.value == "") {
			showValidateErrorDialog("Product Description");
			return (false);
		}
		if(theForm.fulldesc.value == "") {
			showValidateErrorDialog("Full Product Description");
			return (false);
		}
		if(theForm.maxsize.value == "") {
			showValidateErrorDialog("Maximum Order Size");
			return (false);
		}
		if(theForm.minorder.value == "") {
			showValidateErrorDialog("Minimum Order");
			return (false);
		}
		if(theForm.tilesize.value == "") {
			showValidateErrorDialog("Tiled Data Order");
			return (false);
		}
		if(theForm.prodcode.value == "") {
			showValidateErrorDialog("Product Code");
			return (false);
		}
		if(theForm.scale.value == "") {
			showValidateErrorDialog("Product Scale");
			return (false);
		}
		if(theForm.type.value == "") {
			showValidateErrorDialog("Product Type");
			return (false);
		}
		if(theForm.price.value == "") {
			showValidateErrorDialog("Product Price");
			return (false);
		}
		if(theForm.formats.value == "") {
			showValidateErrorDialog("Available Formats");
			return (false);
		}
		if(theForm.showit.value == "") {
			showValidateErrorDialog("Display on Interface");
			return (false);
		}
		if(theForm.areadisc.value == "") {
			showValidateErrorDialog("Area Discount Type");
			return (false);
		}	
		return (true);		
	}else if(theType == "sales"){								//**Checking sales person update details.
		if (theForm.salesname.value == "") {
			showValidateErrorDialog("Name");
			return (false);
		}
		if (theForm.site.value == "") {
			showValidateErrorDialog("Site Code");
			return (false);
		}	
		//Check pasword match
		if(document.getElementById("userpwd2") != null){
			if(theForm.userpwd.value != theForm.userpwd2.value) {
				showDialog('Warning','Passwords do not match.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				return (false);
			}
		}
		return (true);
	}else if(theType == "tariffs"){								//**Checking tariff code update details.
		if (theForm.tariffcode.value == "") {
			showValidateErrorDialog("Tariff Code");
			return (false);
		}
		if (theForm.site.value == "") {
			showValidateErrorDialog("Site Code");
			return (false);
		}	
		return (true);		
	}else if(theType == "category"){								//**Checking category update details.
		if (theForm.category.value == "") {
			showValidateErrorDialog("Category");
			return (false);
		}
		if (theForm.catdesc.value == "") {
			showValidateErrorDialog("Category Description");
			return (false);
		}
		if (theForm.orderindex.value == "") {
			showValidateErrorDialog("Category Order");
			return (false);
		}	
		return (true);
	}else if(theType == "style"){								//**Checking style details.
		if(theForm.style.value == "") {
			showValidateErrorDialog("Style");
			return (false);
		}
		if(theForm.styledesc.value == "") {
			showValidateErrorDialog("Style Description");
			return (false);
		}
		if(theForm.orderindex.value == "") {
			showValidateErrorDialog("Style Order");
			return (false);
		}	
		return (true);	
	}else if(theType == "licence"){								//**Checking licence details.
		if(theForm.licence.value == "") {
			showValidateErrorDialog("Licence");
			return (false);
		}
		if(theForm.licdesc.value == "") {
			showValidateErrorDialog("Licence Description");
			return (false);
		}
		if((theForm.licprice.value == "") || (theForm.licprice.value == "0")) {
			showValidateErrorDialog("Licence Price");
			return (false);
		}
		return (true);	
	}else if(theType == "royaltyinfo"){								//**Checking royalty info details.
		if(theForm.supplier.value == "") {
			showValidateErrorDialog("Supplier");
			return (false);
		}
		if(theForm.prodcode.value == "") {
			showValidateErrorDialog("Product Code");
			return (false);
		}
		if(theForm.royaltycode.value == "") {
			showValidateErrorDialog("Royalty Code");
			return (false);
		}
		if(theForm.theregion.value == "") {
			showValidateErrorDialog("Region");
			return (false);
		}
		if(theForm.areadisc.value == "") {
			showValidateErrorDialog("Terminal Discount");
			return (false);
		}
		return (true);			
	}else if(theType == "format"){								//**Checking details format details.
		if(theForm.format.value == "") {
			showValidateErrorDialog("Format");
			return (false);
		}
		if(theForm.formatdesc.value == "") {
			showValidateErrorDialog("Format Description");
			return (false);
		}
		return (true);		
	}else if(theType == "discount"){								//***Checking discount details.
		if((theForm.promo.value == "") && (theForm.outlet.value == "") && (theForm.blom.value == "")) {
			showDialog('Warning','Please enter a value for either "Promotional Code", "Outlet Code" or "BlomURBEX Code".<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			return (false);
		}
		if((theForm.promo.value != "") && (theForm.outlet.value != "") && (theForm.blom.value != "")) {
			showDialog('Warning','Please enter a value for either "Promotional Code", "Outlet Code" or "BlomURBEX Code".<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			return (false);
		}	
		if(theForm.discount.value == "") {
			showValidateErrorDialog("Discount");
			return (false);
		}
		if(theForm.site.value == "") {
			showValidateErrorDialog("Site Code");
			return (false);
		}
		if((Number(theForm.discount.value) < 0) || (Number(theForm.discount.value) > 1)){
			showDialog('Warning','Please enter a valid value for the "Discount" field. (0 - 1).<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			return (false);
		}
		return (true);	
	}else if(theType == "overlay"){								//**Checking overlays details.
		if(theForm.name.value == "") {
			showValidateErrorDialog("Overlay Name");
			return (false);
		}
		if(theForm.ovcode.value == "") {
			showValidateErrorDialog("Overlay Code");
			return (false);
		}
		if(theForm.ovprice.value == "") {
			showValidateErrorDialog("Overlay Price");
			return (false);
		}			
		return (true);
	}else if(theType == "royaltyrate"){								//**Checking overlays details.
		if(theForm.royalref.value == "") {
			showValidateErrorDialog("Reference");
			return (false);
		}
		if(theForm.royalrate.value == "") {
			showValidateErrorDialog("Rate");
			return (false);
		}
		if(theForm.expires.value == "") {
			showValidateErrorDialog("Expiry Date");
			return (false);
		}			
		return (true);	
	}else if(theType == "delivery"){								//**Checking delivery method details.
		if(theForm.method.value == "") {
			showValidateErrorDialog("Delivery Method");
			return (false);
		}
		if(theForm.delprice.value == "") {
			showValidateErrorDialog("Delivery Price");
			return (false);
		}
		if(theForm.site.value == "") {
			showValidateErrorDialog("Site Code");
			return (false);
		}			
		return (true);	
	}else if(theType == "finish"){								//**Checking print finish details.
		if(theForm.finish.value == "") {
			showValidateErrorDialog("Print Finish");
			return (false);
		}
		if(theForm.finishprice.value == "") {
			showValidateErrorDialog("Print Finish Price");
			return (false);
		}
		if(theForm.site.value == "") {
			showValidateErrorDialog("Site Code");
			return (false);
		}			
		return (true);		
	}else if(theType == "markup"){								//**Checking product markup details.
		if(theForm.prodcode.value == "") {
			showValidateErrorDialog("Product Code");
			return (false);
		}
		if(theForm.markup.value == "") {
			showValidateErrorDialog("Product Markup");
			return (false);
		}
		if(theForm.site.value == "") {
			showValidateErrorDialog("Site Code");
			return (false);
		}			
		return (true);
	}else if(theType == "minPrice"){								//**Checking min price details.
		if(theForm.prodcode.value == "") {
			showValidateErrorDialog("Product Code");
			return (false);
		}
		if(theForm.variantcode.value == "") {
			showValidateErrorDialog("Variant Code");
			return (false);
		}
		if(theForm.minprice.value == "") {
			showValidateErrorDialog("Minimum Price");
			return (false);
		}			
		return (true);				
	}else if(theType == "fixedstyle"){								//**Checking fixed style details.
		if(theForm.fcode.value == "") {
			showValidateErrorDialog("Code");
			return (false);
		}
		if(theForm.fcolour.value == "") {
			showValidateErrorDialog("Colour");
			return (false);
		}
		if((theForm.fsize.value == "") || (isNaN(theForm.fsize.value))) {
			showValidateErrorDialog("Size");
			return (false);
		}	
		return (true);
	}else if(theType == "site"){								//***Checking site details.
		if(theForm.whitelabel.value == "") {
			showValidateErrorDialog("White Label");
			return (false);
		}
		if(theForm.sitename.value == "") {
			showValidateErrorDialog("Site Name");
			return (false);
		}
		if(theForm.site.value == "") {
			showValidateErrorDialog("Site ID");
			return (false);
		}
		if(theForm.siteurl.value == "") {
			showValidateErrorDialog("Site URL");
			return (false);
		}
		if(theForm.geninvoice.value == "") {
			showValidateErrorDialog("Generate Invoices");
			return (false);
		}
		if(theForm.showaerial.value == "") {
			showValidateErrorDialog("Show Aerial Imagery");
			return (false);
		}
		if(theForm.showblom.value == "") {
			showValidateErrorDialog("Show blomURBEX");
			return (false);
		}
		if(theForm.adminemail.value == "") {
			showValidateErrorDialog("Admin. Email");
			return (false);
		}
		if(theForm.orderprefix.value == "") {
			showValidateErrorDialog("Order Prefix");
			return (false);
		}
		if(theForm.licno.value == "") {
			showValidateErrorDialog("Licence Number");
			return (false);
		}	
		if(theForm.emailfooter.value == "") {
			showValidateErrorDialog("Email Footer Info. (Plain Text)");
			return (false);
		}
		if(theForm.emailfooterhtml.value == "") {
			showValidateErrorDialog("Email Footer Info. (HTML)");
			return (false);
		}	
		if(theForm.secpayuser.value == "") {
			showValidateErrorDialog("Secpay User Name");
			return (false);
		}
		if(theForm.secpaypwd.value == "") {
			showValidateErrorDialog("Secpay Password");
			return (false);
		}
		if(theForm.secpaydig.value == "") {
			showValidateErrorDialog("Secpay Digest");
			return (false);
		}
		if((theForm.urban.value == "0") || (theForm.urban.value == "") || (isNaN(theForm.urban.value)) || (theForm.rural.value == "0") || (isNaN(theForm.rural.value)) || (theForm.rural.value == "") || (theForm.moorland.value == "0") || (isNaN(theForm.moorland.value)) || (theForm.moorland.value == "")) {
			showValidateErrorDialog("OS Mastermap run on print charges");
			return (false);
		}	
		if((theForm.tenkprintprice.value == "0") || (isNaN(theForm.tenkprintprice.value)) || (theForm.tenkprintprice.value == "")) {
			showValidateErrorDialog("OS 10K run on print charges");
			return (false);
		}
		return (true);
	}else if(theType == "siteusers"){					//***Checking site user details.
		if(theForm.whitelabel.value == "") {
			showValidateErrorDialog("White Label");
			return (false);
		}
		if(theForm.username.value == "") {
			showValidateErrorDialog("User Name");
			return (false);
		}
		if(theForm.usertype.value == "") {
			showValidateErrorDialog("User Type");
			return (false);
		}	
		if(theForm.usertype.value == "admin2") {
			if (theForm.site.value == "") {
				showValidateErrorDialog("Site ID");
				return (false);
			}
		}	
		//Check the 'Password' field			
		if (theForm.userpwd.value == "") {											//Password field must not be empty
			showDialog('Warning','Please enter a value for the "Password" field.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			return (false);
		}else if(!theForm.userpwd.value.match("^[a-z|A-Z|0-9|\.]*$")) {
			showDialog('Warning','Invalid Password. Password must contain only numbers and letters.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');				
			return (false);		
		}
		//Check pasword match
		if(document.getElementById("userpwd2") != null){
			if(theForm.userpwd.value != theForm.userpwd2.value) {
				showDialog('Warning','Passwords do not match.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				return (false);
			}
		}
		return (true);		
	}else if(theType == "company"){ 				//***Checking company update details.
		if(theForm.company.value == "") {
			showValidateErrorDialog("Company Name");
			return (false);
		}
		if(theForm.address1.value == "") {
			showValidateErrorDialog("Address");
			return (false);
		}
		if(theForm.town.value == "") {
			showValidateErrorDialog("Town");
			return (false);
		}
		/*if(theForm.county.value == "") {
			showValidateErrorDialog("County");
			return (false);
		}*/
		if(theForm.postcode.value == "") {
			showValidateErrorDialog("Postcode");
			return (false);
		}
		if(theForm.country.value == "") {
			showValidateErrorDialog("Country");
			return (false);
		}
		if(theForm.telephone.value == "") {
			showValidateErrorDialog("Telephone");
			return (false);
		}
		var phoneOK = phoneCheck(theForm.telephone.value);
		if(phoneOK == false){
			return (false);
		}
		if(theForm.paymentmethod.value == "") {
			showValidateErrorDialog("Payment Method");
			return (false);
		}
		if(theForm.tenkdata.value == "") {
			showValidateErrorDialog("10k Data");
			return (false);
		}
		return (true);
	}			
}
//*******************Shows the error dialog box for failed validation
function showValidateErrorDialog(theLabel){
	showDialog('Warning','Please enter a value for the "' + theLabel + '" field.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
}
//*******************Telephone vailiidity check
function phoneCheck(checkStr) {
	var checkOK = "0123456789-+() \t\r\n\f";
	var allValid = true;
	for (i = 0;  i < checkStr.length;  i++){
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		if (ch == checkOK.charAt(j))
		break;
		if (j == checkOK.length){
		allValid = false;
		break;
		}
	}		
	if (!allValid){
		showDialog('Warning','Please enter only digit, whitespace and "+()" characters in the "Telephone" field.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		return (false);
	}
}
//*******************Email vailiidity check
function emailCheck (emailStr) {
	/* 1.1.4: Fixed a bug where upper ASCII characters (i.e. accented letters
	international characters) were allowed.
	1.1.3: Added the restriction to only accept addresses ending in two
	letters (interpreted to be a country code) or one of the known
	TLDs (com, net, org, edu, int, mil, gov, arpa), including the
	new ones (biz, aero, name, coop, info, pro, museum).  One can
	easily update the list (if ICANN adds even more TLDs in the
	future) by updating the knownDomsPat variable near the
	top of the function.  Also, I added a variable at the top
	of the function that determines whether or not TLDs should be
	checked at all.  This is good if you are using this function
	internally (i.e. intranet site) where hostnames don't have to 
	conform to W3C standards and thus internal organization e-mail
	addresses don't have to either.
	Changed some of the logic so that the function will work properly
	with Netscape 6.	
	1.1.2: Fixed a bug where trailing . in e-mail address was passing
	(the bug is actually in the weak regexp engine of the browser; I
	simplified the regexps to make it work).	
	1.1.1: Removed restriction that countries must be preceded by a domain,
	so abc@host.uk is now legal.  However, there's still the 
	restriction that an address must end in a two or three letter
	word.	
	1.1: Rewrote most of the function to conform more closely to RFC 822.
	1.0: Original  */
	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */
	var checkTLD=1;
	/* The following is the list of known TLDs that an e-mail address must end with. */
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */
	var emailPat=/^(.+)@(.+)$/;
	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address. 
	These characters include ( ) < > @ , ; : \ " . [ ] */
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	/* The following string represents the range of characters allowed in a 
	username or domainname.  It really states which chars aren't allowed.*/
	var validChars="\[^\\s" + specialChars + "\]";
	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")";
	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	/* The following string represents an atom (basically a series of non-special characters.) */
	var atom=validChars + '+';
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")";
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	/* Finally, let's start trying to figure out if the supplied address is valid. */	
	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */
		showDialog('Warning','Email address seems incorrect (check @ and .\'s).<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			showDialog('Warning','This username contains invalid characters.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			return false;
		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			showDialog('Warning','This domain name contains invalid characters.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			return false;
		}
	}
	// See if "user" is valid 
	if (user.match(userPat)==null) {
		// user is not valid
		showDialog('Warning','The username does not seem to be valid.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		return false;
	}
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		// this is an IP address
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				showDialog('Warning','Destination IP address is invalid.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				return false;
		   	}
		}
		return true;
	}	
	// Domain is symbolic name.  Check if it's valid.
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			showDialog('Warning','The domain name does not seem to be valid.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			return false;
	   	}
	}
	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
		showDialog('Warning','"The address must end in a well-known domain or two letter country.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		return false;
	}
	// Make sure there's a host name preceding the domain.
	if (len<2) {
		showDialog('Warning','This address is missing a hostname.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		return false;
	}
	// If we've gotten this far, everything's valid!
	return true;
}

//----------------------------------------------------------------------ROYALTY SCRIPTS

//****************Run script to calucalte missing royalties
function calcMissingRoyalties(){
	document.getElementById("updateprog").innerHTML = "<p align='right'><img src='../images/loader.gif'>  Please wait</p>";	
	var theOIDList = document.getElementById("oidlist").value;
	//Define the query string to pass variables
	var qstring = "oidlist=" + theOIDList;
	var royalReq = new ajaxObject('backCalcRoyalty.php', updateBackRoyaltyResponse);
	royalReq.update(qstring,'POST');
}
//****************Response from updating missing Royalties
function updateBackRoyaltyResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values
		document.getElementById("updateprog").innerHTML = "";
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");
			showDialog('',tempArray[1] + ' order items updated. Please refresh the page.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','prompt');	
		}else{
			showDialog('Error','There has been a problem updating. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
		}
	}
}

//----------------------------------------------------------------------GENERAL SCRIPTS

//************************Removes leading and trailing spaces from the passed string.
function trim(inputString) {
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while ((ch == " ") || (ch.charCodeAt(0) == 9)) { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while ((ch == " ") || (ch.charCodeAt(0) == 9)) { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   //Remove return/new line characters from front of string
   var testCode = retValue.charCodeAt(0);
   var testCode2 = retValue.charCodeAt(1);
   if((testCode == "13") || (testCode2 == 10)){
   		retValue = retValue.substring(2, retValue.length);
   }
   return retValue;
} 
//*******************Replace any '&' in the query string
function escapeAmp(inputString){
	var outputString = inputString.replace(/&/g,"-amp-"); 
	return outputString;
}
//*******************Replace any reg and copyright symbols with HTML code eg &reg; and &copy;
function encodeAsHTML(inputString){
	var theRegExp = new RegExp(String.fromCharCode(174), "gi");
	var outputString = inputString.replace(theRegExp,"-amp-reg;"); 
	var theRegExp = new RegExp(String.fromCharCode(169), "gi");
	var outputString2 = outputString.replace(theRegExp,"-amp-copy;");
	var outputString3 = outputString2.replace(/&/g,"-amp-"); 
	return outputString3;
}
//*******************Check if a start date has been entered for returns/order listings
function checkStartDate() {	
	//Get the entered values
	var searchStartDay = document.searchform.startday.value;
	var searchStartMonth = document.searchform.startmonth.value;
	var searchStartYear = document.searchform.startyear.value;
	//Check
	var dateOk = true;	
	if((searchStartDay == "") || (isNaN(searchStartDay) == true)){
		dateOk = false;
	}else{
		if((Number(searchStartDay) < 1) || (Number(searchStartDay) > 31)){
			$dateOk = false;
		}	
	}	
	if(searchStartMonth == ""){
		dateOk = false;
	}
	if((searchStartYear == "") || (isNaN(searchStartYear) == true)){
		dateOk = false;
	}else{
		if((Number(searchStartYear) < 1000) || (Number(searchStartYear) > 9999)){
			$dateOk = false;
		}	
	}
	return dateOk;
}

//----------------------------------------------------------------------INVOICE/STATEMENT SCRIPTS

//*******************Check the invoice date is entered correctly and show the relevant info
function checkInvoiceDate(theAction){
	var isOk = true;					
	if (document.searchform.startmonth.value == "") {
		showDialog('Warning','Please enter a value for the "Starting Month".<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		isOk = false;
	}
	if (Number(document.searchform.startyear.value) < 2005){
		showDialog('Warning','Please enter a valid value for the "Starting Year" (2005 +).<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		isOk = false;
	}
	document.searchform.theaction.value = theAction;
	//Define what to do - show invoices or transactions	
	if(theAction == "trans"){
		document.searchform.action = "transResults.php";
	}else{
		document.searchform.action = "invoiceResults.php";
	}	
	if(isOk){
		if(theAction == "create"){
			//Check if the invoice date is in the future
			var nowDate=new Date()			
			var currentMonth = nowDate.getMonth() + 1;
			var currentYear = nowDate.getFullYear();
			if((Number(document.searchform.startyear.value) >= currentYear) && (Number(document.searchform.startmonth.value) >= currentMonth)){
				showDialog('Warning','The input invoice date is for a month that has not ended.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			}else{
				var dialogContent = "Really generate invoice for '" + document.searchform.startmonth.value + "-" + document.searchform.startyear.value + "'?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='genTheInvoice();'>  <input type='button' value='No' id='noButton' onclick='hideDialog();' >"
				showDialog('',dialogContent,'prompt');		
			}
		}else{
			document.searchform.submit();
		}
	}
}
//*******************Generate invoices by submiting the form (this page shows a list of customers to invoice)
function genTheInvoice(){
	document.searchform.submit();
}
//*******************Ajax process to generate each invoice in turn
function generateInvoices(statementIndex){
	if(document.invoiceform.allCompIDs.value == ""){
		showDialog('Warning','No accounts found for invoice generation.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{
		//Get list as array
		var tempCompIDArray = document.invoiceform.allCompIDs.value.split(",");		
		//if(statementIndex == 3){ //TEMP TESTING
		if(tempCompIDArray.length == statementIndex){			//We have reached the end of all the companies to invoice
			//showDialog('Success', 'All accounts have been invoiced. Ensure notification emails are sent.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >' ,'success');			
			showDialog('Success', 'All accounts have been invoiced and notification emails sent.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >' ,'success');			
		}else{
			var companyIDToInvoice = tempCompIDArray[statementIndex];		
			document.getElementById("invoicestatus" + String(statementIndex+1)).innerHTML = "<em><img src='../images/loader.gif'>  Generating...</em>";
			var qstring = "statementIndex=" + statementIndex + "&passedCompanyID=" + companyIDToInvoice	+ "&startmonth=" + document.invoiceform.startmonth.value + "&startyear=" + document.invoiceform.startyear.value;
			var genInvoiceReq = new ajaxObject('generateTheInvoice.php',genInvoiceResponse);
			genInvoiceReq.update(qstring,'POST');
		}
	}
}
//****************Response from raising the invoice
function genInvoiceResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");			
			//Show the relevat messages	
			document.getElementById("invoicestatus" + tempArray[1]).innerHTML = tempArray[2];  
			document.getElementById("emailstatus" + tempArray[1]).innerHTML = tempArray[3]; 
			//Store the reference of the invoice created
			document.getElementById("invoicno" + tempArray[1]).value = tempArray[4];
			//Raise invoice for the next company
			//generateInvoices("",Number(tempArray[1]));
			//Send confirmation email
			generateInvoiceEmails((Number(tempArray[1])-1));	
		}else{
			showDialog('Error','There has been a problem generating. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
		}
	}
}
//*******************Ajax process to generate each invoice email notification in turn
function generateInvoiceEmails(statementIndex){
	//if(theIDs != ""){				//If all id's are passed update the hidden field (this will happen on the instigation of the function)
	//	document.invoiceform.allCompIDs.value = theIDs;
	//}
	//Get list as array
	var tempCompIDArray = document.invoiceform.allCompIDs.value.split(",");	
	//if(statementIndex == 1){ //TEMP TESTING
	//if(tempCompIDArray.length == statementIndex){			//We have reached the end of all the companies to invoice
		//showDialog('Success', 'All notification emails have been sent.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >' ,'success');			
	//}else{
		if(document.getElementById("emailstatus" + String(statementIndex+1)).innerHTML == "<em>Pending...</em>"){
			var companyIDToInvoice = tempCompIDArray[statementIndex];		
			document.getElementById("emailstatus" + String(statementIndex+1)).innerHTML = "<em><img src='../images/loader.gif'>  Emailing...</em>";
			var qstring = "statementIndex=" + statementIndex + "&passedCompanyID=" + companyIDToInvoice + "&invoiceNo=" + document.getElementById("invoicno" + String(statementIndex+1)).value;  // + "&tempEmail=" + document.getElementById("tempEmail").value;			
			var genInvoiceEmailReq = new ajaxObject('generateInvoiceEmail.php',genInvoiceEmailsResponse);
			genInvoiceEmailReq.update(qstring,'POST');
		}else{			//Can't or don't need to send email. Get the next account
			//generateInvoiceEmails("",(statementIndex+1));
			generateInvoices((statementIndex+1));
			
		}
	//}
}
//****************Response from generating invoice email notifications
function genInvoiceEmailsResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");			
			//Show the message	
			document.getElementById("emailstatus" + tempArray[1]).innerHTML = tempArray[2]; 
			//Raise invoice for the next company
			//generateInvoiceEmails("",Number(tempArray[1]));
			//Raise invoice for the next company
			generateInvoices(Number(tempArray[1]));			
		}else{
			showDialog('Error','There has been a problem sending email confirmations. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
		}
	}
}
//*******************TEMP CODE TO SEND EMAIL NOTIFICATION FOR INDIVIDUAL INVOICES
function generateInvoiceEmails2(statementIndex){	
	var tempInvoiceNoArray = document.invoiceform.allInvoiceIDs.value.split(",");	
	if(tempInvoiceNoArray.length == statementIndex){			//We have reached the end of all the companies to invoice
		alert("done")
	}else{
		var temparray = tempInvoiceNoArray[statementIndex].split(".")
		var companyIDToInvoice = temparray[1] + "-" + temparray[2];
		var theInvoiceNo = tempInvoiceNoArray[statementIndex];			
		//document.write(theInvoiceNo + " - ");
		document.getElementById("messagearea").innerHTML = document.getElementById("messagearea").innerHTML + "<br/>" + theInvoiceNo;
		var qstring = "statementIndex=" + statementIndex + "&passedCompanyID=" + companyIDToInvoice + "&invoiceNo=" + theInvoiceNo; 				
		var genInvoiceEmailReq = new ajaxObject('generateInvoiceEmail.php',genInvoiceEmailsResponse2);
		genInvoiceEmailReq.update(qstring,'POST');
	}
}
function genInvoiceEmailsResponse2(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");			
			//Show the message	
			//document.write(tempArray[2] + "<br/>"); 
			document.getElementById("messagearea").innerHTML = document.getElementById("messagearea").innerHTML + tempArray[2] ;
			//Raise invoice for the next company
			generateInvoiceEmails2(Number(tempArray[1]));
			//Raise invoice for the next company
			//generateInvoices(Number(tempArray[1]));			
		}else{
			alert("Problem sending email");
		}
	}
}
//*******************Show the invoice payment transactions for the passed invoice no.
function showTrans(theInvoiceNo){
	document.invoiceform.action = "transResults.php";
	document.invoiceform.currentInvoiceNo.value = theInvoiceNo;	
	document.invoiceform.submit();
}
//*******************Submits the admin form setting the specified page.
function backFromTrans(theAction){
	document.adminform.action = theAction;	
	document.adminform.submit();
}
//****************Update invoice comments and refund notes
function updateNotes(theOID,theType,recID){
	document.invoiceform.upNotesID.value = theOID;
	document.invoiceform.upNotesType.value = theType;
	if(theType == "comments"){
		document.invoiceform.upNotes.value = document.getElementById("comments" + recID).value;
	}else if(theType == "refund"){
		document.invoiceform.upNotes.value = document.getElementById("rcomments" + recID).value;
	}
	document.invoiceform.submit();
}
//*******************Show the selected invoice 
function showInvoice(theNo,theSrc,showPaymentInfo){
	//Define the type of invoice
	if(theNo.indexOf(".") == -1){									//Is single user invoice (legacy invoice)
		document.invoiceform.invoicetype.value = "invoice";
	}else{															//Is account holder invoice
		document.invoiceform.invoicetype.value = "officeinvoice";
	}	
	document.invoiceform.showpaymentinfo.value = showPaymentInfo;   //Define if payment info is to be shown on the invoice
	document.invoiceform.invoicenotopass.value = theNo;
	if(theSrc == "admindisplay"){
		document.invoiceform.action = "showInvoice.php";
	}else if(theSrc == "userdisplay"){
		document.invoiceform.action = "admin/showInvoice.php";
	}
	document.invoiceform.target = "_blank";	
	document.invoiceform.submit();
}
//*******************Prints all invoices
function printInvoice(theNo){
	document.invoiceform.allIvoiceIds.value = theNo;
	document.invoiceform.action = "allInvoices.php";
	document.invoiceform.target = "_blank";	
	document.invoiceform.submit();
}
//*******************Shows list of all overdue invoices - ready for statement emailing
function emailStatement(theType){
	document.searchform.statementType.value = theType
	document.searchform.action = 'emailStatements.php'
	document.searchform.submit();
}
//*******************Ajax process to email each comapny in turn
function emailStatementStep2(statementIndex){
	//Get list as array
	var tempCompIDArray = document.overdueform.allCompIDs.value.split(",");
	var tempNumberOverdueArray = document.overdueform.overdueTotals.value.split(",");	
	if((document.overdueform.allCompIDs.value == "") && (document.overdueform.overdueTotals.value == "")){
		showDialog('Warning','No accounts found to contact.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{
		//if(statementIndex == 5){
		if(tempCompIDArray.length == statementIndex){			//We have reached the end of all the companies to email
			showDialog('Success', 'All Emails have been sent.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >' ,'success');			
		}else{
			var companyIDToEmail = tempCompIDArray[statementIndex];
			var noOverdue = tempNumberOverdueArray[statementIndex];		
			for(c=1;c <= Number(noOverdue);c++){
				document.getElementById(companyIDToEmail + "_" + String(c)).innerHTML = "<em><img src='../images/loader.gif'>  Emailing...</em>";
			}	
			var qstring = "statementIndex=" + statementIndex + "&passedCompanyID=" + companyIDToEmail + "&statementType=" + document.overdueform.statementType.value + "&noOverdue=" + noOverdue;  // + "&tempEmail=" + document.overdueform.tempEmail.value;			
			var emailStatementReq = new ajaxObject('emailTheStatement.php',emailStatementResponse);
			emailStatementReq.update(qstring,'POST');
		}
	}
}
//****************Response from emailing a statement
function emailStatementResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values
		if(responseText != ""){
			var tempArray = new Array();
			tempArray = responseText.split("|");
			//Show the message	
			for(c=1;c <= tempArray[3];c++){
				document.getElementById(tempArray[2] + "_"  +String(c)).innerHTML = tempArray[0];
			}
			//Email the next company
			emailStatementStep2(Number(tempArray[1]) + 1);
		}else{
			showDialog('Error','There has been a problem emailing. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
		}
	}
}
//*******************Generate the invoice
function showInvoicePDF(theNo,theSrc,showPaymentInfo,progID){
	//Define the type of invoice
	if(theNo.indexOf(".") == -1){									//Is single user invoice (legacy invoice)
		var theInvoiceType = "invoice";
	}else{															//Is account holder invoice
		var theInvoiceType = "officeinvoice";
	}	
	document.getElementById(progID).innerHTML = "<em><img src='../images/loader.gif'>  Generating...</em>";
	var qstring = "showpaymentinfo=" + showPaymentInfo + "&invoicetype=" + theInvoiceType + "&invoicenotopass=" + theNo + "&theProgId=" + progID + "&theSrc=" + theSrc;
	if(theSrc == "admindisplay"){
		var invoicePDFReq = new ajaxObject('showInvoicePDF.php',invoicePDFResponse);
	}else if(theSrc == "userdisplay"){
		var invoicePDFReq = new ajaxObject('admin/showInvoicePDF.php',invoicePDFResponse);
	}	
	invoicePDFReq.update(qstring,'POST');
}
//****************Response from generating invoice
function invoicePDFResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Get the returned values	
		if(responseText != ""){
			if(responseText.indexOf("TCPDF ERROR") != -1){
				showDialog('Error','There has been a problem generating the invoice. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="reloadAfterInvoiceFail();" >','errordialog');
			}else{
				var tempArray = new Array();
				tempArray = responseText.split("|");		
				//Replace the pipe for accounts with external invoice ID
				tempArray[1] = tempArray[1].replace(/<pipe>/g,"|");
				tempArray[5] = tempArray[5].replace(/<pipe>/g,"|")
				if((tempArray[4] == "userdisplay") && (tempArray[3] == "yes")){		//Link shows as view for payemet receipts in the customer area
					var linkMessage = "<strong>View</strong>";
				}else{																//Link is the invoice no
					var linkMessage = tempArray[1];
				}		
				document.getElementById(tempArray[0]).innerHTML = "<a href='javascript:showInvoicePDF(\"" + tempArray[1] + "\",\"" + tempArray[4] + "\",\"" + tempArray[3] + "\",\"" +  tempArray[0] + "\");'>" + linkMessage + "</a>";
				//Ensure the url agrees with that of the current white label
				var tempURLArray = document.URL.split("/");
				var pdfPath ="";
				if(document.URL.indexOf("/admin/") == -1){		//Accessing from customer area
					var toMinus = 1;
					window.location="downloadPDF.php?name=" + tempArray[5] + ".pdf";
				}else{											//Accessing from admin area
					var toMinus = 2;
					window.location="../downloadPDF.php?name=" + tempArray[5] + ".pdf";
				}	
				//OLD Show in popup
				//for(u=0;u < (tempURLArray.length-toMinus);u++){
				//	pdfPath += tempURLArray[u] + "/";
				//}
				//var pdfURL = pdfPath + "admin/excelexports/" + tempArray[5] + ".pdf";
				//var winName =  "pdfinvoice";
				//var features = "toolbar=no,scrollbars=yes,resizable=yes,width=600,height=600";
				//window.open(pdfURL,winName,features);  //OLD Show in popup
				//OLD Show in new tab
				//document.invoiceform.action = pdfURL;
				//document.invoiceform.target = "_blank";	
				//document.invoiceform.submit();
			}
		}else{
			showDialog('Error','There has been a problem generating the invoice. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="reloadAfterInvoiceFail();" >','errordialog');
		}
	}
}
//*******************Refreshes the page to show the receipt links when the receipt process fails
function reloadAfterInvoiceFail(){
	hideDialog();
	document.invoicingform.submit();
}
//----------------------------------------------------------------------PAYMENT SCRIPTS
//*******************Show the invoice payment transactions for the passed invoice no.
function adminMakePayment(theInvoiceNo){
	document.invoiceform.action = "makePayment.php";
	document.invoiceform.currentInvoiceNo.value = theInvoiceNo;	
	document.invoiceform.submit();
}
//*******************Submits form to perform account search on the make paymet page
function searchPaymentAccount(){
	document.payform.reloadaction.value = "search";	
	document.payform.submit();
}
//*******************Allocate payment recieved to outstaning invoices
function allocatePayment(totalInvoicesOwing){
	//Check payment info has been added (Not necessary if just allocating an overpayment)
	var isOk = true;	
	//Check what overpayments have been allocated to the invoices
	var theCredits = 0;
	var overPaymentOnly = false;
	var totalOverpayments = Number(document.getElementById("overpaidCnt").value);
	for(var c=1;c <= totalOverpayments;c++){
		if(c ==1){
			theCredits = Number(document.getElementById("creditamount" + c).value);
		}else{
			theCredits +=  Number(document.getElementById("creditamount" + c).value);
		}
	}
	//Check if overpayments have been allocated and define if user input needs to be checked
	if(theCredits != 0){
		var overPaymentOnly = true;
		//If a payment amount entered ensure it is valid and type and date also entered
		if(document.getElementById("inputpayamount").value != ""){
			if((document.getElementById("inputpayamount").value == "0") || (document.getElementById("inputpayamount").value == "") || (isNaN(document.getElementById("inputpayamount").value))){
				showDialog('Warning','Please ensure an amount has been entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				isOk = false;
			}
			if(document.getElementById("pmethod").value == ""){
				showDialog('Warning','Please ensure a payment method has been entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				isOk = false;
			}
			if(document.getElementById("pdate").value == ""){
				showDialog('Warning','Please ensure a payment date has been entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				isOk = false;
			}
		}	
	}
	//Ensure it is payment is valid and type and date also entered
	if(overPaymentOnly == false){
		if((document.getElementById("inputpayamount").value == "0") || (document.getElementById("inputpayamount").value == "") || (isNaN(document.getElementById("inputpayamount").value))){
			showDialog('Warning','Please ensure an amount has been entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			isOk = false;
		}
		if(document.getElementById("pmethod").value == ""){
			showDialog('Warning','Please ensure a payment method has been entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			isOk = false;
		}
		if(document.getElementById("pdate").value == ""){
			showDialog('Warning','Please ensure a payment date has been entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			isOk = false;
		}
	}
	if(isOk){
		var amountRecieved = Number(document.getElementById("inputpayamount").value);
		var paymentMethod = document.getElementById("pmethod").value;
		var paymentDate = document.getElementById("pdate").value;
		var paymentNote = document.getElementById("paynote").value;	
		//Check what has been allocated to the invoices
		var allocatedTotal =0;
		for(var c=1;c <= totalInvoicesOwing;c++){
			allocatedTotal += Number(document.getElementById("payamount" + c).value);
		}
		//Ensure script does not add any spurious decinal places.
		allocatedTotal = Math.round(allocatedTotal*100)/100;
		if((allocatedTotal == 0) && (theCredits == 0)){ 			//**Payment not allocated to an invoice
			var dialogContent = "You have not allocated the payment to an outstanding invoice<br/>Click 'Cancel' to amend, alternatively click 'Continue' to be mark this as an overpayment on the account.<br/><input type='button' value='Continue' id='yesButton' onclick='runAllocation();'>  <input type='button' value='Cancel' id='noButton' onclick='hideDialog();' >"
			showDialog('',dialogContent,'prompt');
		}else if((allocatedTotal > amountRecieved) && (allocatedTotal != 0)){			//More has been allocated that recieved - prompt to amend
			showDialog('Warning','You have allocated more than the amount recieved.<br/>Please re-allocate<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}else if((allocatedTotal < amountRecieved) && (allocatedTotal != 0)) {		//More has been recieved than owing
			var dialogContent = "You have allocated less than the amount recieved<br/>Click 'Cancel' to amend, alternatively click 'Continue' to be mark this as an overpayment on the account.<br/><input type='button' value='Continue' id='yesButton' onclick='runAllocation();'>  <input type='button' value='Cancel' id='noButton' onclick='hideDialog();' >"
			showDialog('',dialogContent,'prompt');
		}else{
			runAllocation();
		}
	}
}
//*******************Run the script to allocate payment as defined by user
function runAllocation(){
	hideDialog();
	//Set defaults 
	var theInvoiceIDS = "";
	var thePayments = "";
	var totalPayments = 0;
	var theCreditIDS = "";
	var theCredits = "";	
	//Check what overpayments have been allocated to the invoices
	var totalOverpayments = Number(document.getElementById("overpaidCnt").value);
	for(var c=1;c <= totalOverpayments;c++){
		if(c ==1){
			theCreditIDS = document.getElementById("creditID" + c).value;
			theCredits = document.getElementById("creditamount" + c).value;
		}else{
			theCreditIDS = theCreditIDS + "|" + document.getElementById("creditID" + c).value;
			theCredits = theCredits + "|" + document.getElementById("creditamount" + c).value;
		}
	}
	//Define the list of invoice ids owing an amount allocate
	var totalInvoicesOwing = Number(document.getElementById("unpaidCnt").value);
	for(var c=1;c <= totalInvoicesOwing;c++){
		if(c ==1){
			theInvoiceIDS = document.getElementById("invoiceID" + c).value;
			thePayments = document.getElementById("payamount" + c).value;
			totalPayments = Number(document.getElementById("payamount" + c).value);
		}else{
			theInvoiceIDS = theInvoiceIDS + "|" + document.getElementById("invoiceID" + c).value;
			thePayments = thePayments + "|" + document.getElementById("payamount" + c).value;
			totalPayments += Number(document.getElementById("payamount" + c).value);
		}
	}
	//Define if any overpayment
	var overPayment = Number(document.getElementById("inputpayamount").value) - totalPayments;
	theInvoiceIDS = theInvoiceIDS + "|-99";
	thePayments = thePayments + "|" + overPayment;	
	//Define the query string to pass variables
	var qstring = "themethod=" + document.getElementById("pmethod").value + "&paynote=" + document.getElementById("paynote").value + "&paydate=" + document.getElementById("pdate").value + "&payments=" + thePayments + "&invoiceids=" + theInvoiceIDS + "&credits=" + theCredits + "&creditids=" + theCreditIDS + "&invoiceCompany=" + document.getElementById("invoiceCompany").value;		
	var payReq = new ajaxObject('payInvoice.php', updatePayInvoiceResponse);
	payReq.update(qstring,'POST')	
}
//*******************Response from updating site content
function updatePayInvoiceResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Ensure no returns and other unwanted characters get passed back
		responseText = trim(responseText);	
		responseText = responseText.replace(/\n/g,"").replace(/\r/g,"");
		//Get the returned values			
		if(responseText != ""){			
			if(responseText == "ok"){							
				showDialog('Success', 'Payments allocated successfully.<br/><br/><input type="button" value="Close" id="closeButton" onclick="updatePaymentListing();" >' ,'success');			
			}else{												
				//Show error message
				showDialog('Warning','Problems allocating payment.Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			}		
		}else{
			//Show error message
			showDialog('Warning','Problems allocating payment.Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}
	}	
}
//*******************Refresh the payment page after a payment has been allocated successfully
function updatePaymentListing(){
	hideDialog();				
	document.adminform.submit();   //Refresh page
}
//*******************Allocate full amount owing to the selected invoice
function allocateFull(totalInvoicesOwing,allocationType){	
	if(allocationType == "payment"){
		document.getElementById("payamount" + totalInvoicesOwing).value = document.getElementById("invoiceBalance" + totalInvoicesOwing).value;
	}else{
		document.getElementById("creditamount" + totalInvoicesOwing).value = document.getElementById("creditBalance" + totalInvoicesOwing).value;
	}
	totalTheAllocated();			//Update allocated total	
}
//*******************Show the total allocated
function totalTheAllocated(){
	/*OLDvar allocatedTotal = 0;
	var totalOverpayments = Number(document.getElementById("overpaidCnt").value);
	for(var c=1;c <= totalOverpayments;c++){
		allocatedTotal += Number(document.getElementById("creditamount" + c).value);
	}
	var totalInvoicesOwing = Number(document.getElementById("unpaidCnt").value);
	for(var c=1;c <= totalInvoicesOwing;c++){
		allocatedTotal += Number(document.getElementById("payamount" + c).value);
	}
	document.getElementById("allocatedTotal").innerHTML = "<strong>" + formatPrice(Math.round(allocatedTotal*100)/100) + "</strong>";  
	*/
	//WORKIN!!!!!!!!!!!!!!!!!!!!!!!
	var allocatedTotal1 = 0;
	var totalOverpayments = Number(document.getElementById("overpaidCnt").value);
	for(var c=1;c <= totalOverpayments;c++){
		allocatedTotal1 += (Number(document.getElementById("creditamount" + c).value) * -1);
	}
	var allocatedTotal2 = 0;
	var totalInvoicesOwing = Number(document.getElementById("unpaidCnt").value);
	for(var c=1;c <= totalInvoicesOwing;c++){
		allocatedTotal2 += Number(document.getElementById("payamount" + c).value);
	}
	//????????????????????????????
	//if((Number(allocatedTotal1)  < 0) && (Number(allocatedTotal2) != 0)){
	//	fullAllocatedTotal = (Number(allocatedTotal1) * -1) + Number(allocatedTotal2);
	//}else{
		fullAllocatedTotal = Number(allocatedTotal1) + Number(allocatedTotal2);
	//}
	document.getElementById("allocatedTotal").innerHTML = "<strong>" + formatPrice(Math.round(fullAllocatedTotal*100)/100) + "</strong>";  	
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
//******************Calculates total allocated as the user types the value in
function keyPressDown(e,inIndex,allocationType){
	evt = e || window.event;	
	var unicode=evt.keyCode? evt.keyCode : evt.charCode
	if(    (((unicode < 48) || (unicode > 57)) && ((unicode < 96) || (unicode > 105)))   && (unicode != 8) && (unicode != 190) && (unicode != 37) && (unicode != 39)         ){
		showDialog('Warning','Ensure only numbers are entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{
		//Ensure amount added is less than or equal that owing on the invoice or the overpayment
		if(allocationType == "payment"){			
			if(Number(document.getElementById("payamount" + inIndex).value) > Number(document.getElementById("invoiceBalance" + inIndex).value)){
				document.getElementById("payamount" + inIndex).value = document.getElementById("invoiceBalance" + inIndex).value;
			}
		}else{
			if(Number(document.getElementById("creditamount" + inIndex).value) > Number(document.getElementById("creditBalance" + inIndex).value)){
				document.getElementById("creditamount" + inIndex).value = document.getElementById("creditBalance" + inIndex).value;
			}
		}		
		totalTheAllocated();	
	}	
}
//*******************Submits the admin form setting the specified page.
function backFromPayment(){
	document.adminform.action = "invoiceResults.php";	
	document.adminform.submit();
}
//*******************Assigns the passed company account when search returns more than one
function choosePaymentAccount(passedCompId){	
	//Assign the passed account ID an submit
	document.payform.reloadaction.value = "search";
	document.payform.companyid.value = "on";
	document.payform.companyid.checked = true;
	document.payform.compid.value = passedCompId;	
	document.payform.submit();
}

//----------------------------------------------------------------------DEBTORS CODE

//*******************Debtor report date vailidity check
function dateCheck() {	
	//Get the entered values
	var searchStartDay = document.searchform.startday.value;
	var searchStartMonth = document.searchform.startmonth.value;
	var searchStartYear = document.searchform.startyear.value;
	//Check
	var dateOk = true;	
	if((searchStartDay == "") || (isNaN(searchStartDay) == true)){
		dateOk = false;
		showDialog('Warning','Report day not specified correctly.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{
		if((Number(searchStartDay) < 1) || (Number(searchStartDay) > 31)){
			$dateOk = false;
			showDialog('Warning','Report day not specified correctly.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}	
	}	
	if(searchStartMonth == ""){
		dateOk = false;
		showDialog('Warning','Report month not specified correctly.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}
	if((searchStartYear == "") || (isNaN(searchStartYear) == true)){
		dateOk = false;
		showDialog('Warning','Report year not specified correctly.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{
		if((Number(searchStartYear) < 1000) || (Number(searchStartYear) > 9999)){
			$dateOk = false;
			showDialog('Warning','Report year not specified correctly.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}	
	}
	if(dateOk){
		submitSearchForm("debtResults");
	}
}

//----------------------------------------------------------------------EXCEL EXPORT CODE

//****************Retrieves info from page and calls export code
function saveXLS(passedRows,passedColumns,listType){
	//Show progress
	document.getElementById("exportprog").innerHTML = "<p align='right'><img src='../images/loader.gif'>  Please wait</p>";
	//Create string of all data
	var dataString = "";
	for(var r=1; r <= passedRows; r++){
		if(r > 1){
			dataString += "~";
		}
		for(var c=1; c <= passedColumns; c++){
			var cellRef = String.fromCharCode(64+c) + String(r);			
			
			//temp for testing
			//if((r==2) && (c==1)){
			//	document.getElementById(cellRef).value = "ABC|" + document.getElementById(cellRef).value
			//}
			
			if(c == 1){
				//dataString += document.getElementById(cellRef).value;    //.innerHtml??	
				dataString += document.getElementById(cellRef).value.replace(/\|/g,"-");
			}else{
				dataString += "|" + document.getElementById(cellRef).value.replace(/\|/g,"-");
			}					
		}
	}
	//Call the script to save as Excel
	var qstring = "datastring=" + escapeAmp(dataString) + "&thetype=" + listType;
	var xlsReq = new ajaxObject('saveXLS.php', handleSaveXLSResponse2);
	xlsReq.update(qstring,'POST');
}
//****************Response from exporting to Excel
function handleSaveXLSResponse2(responseText, responseStatus){
	if(responseStatus == 200){
		document.getElementById("exportprog").innerHTML = "";
		if(responseText != ""){
			var responseArray = responseText.split("|");
			if(responseArray[0] == "OK"){											//Call page to download the created file				
				window.location="downloadExcel.php?name=" + responseArray[1];
			}else{
				showDialog('Error','There has been a problem exporting. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
			}
		}else{
			showDialog('Error','There has been a problem exporting. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');		
		}
	}	
}

/*----------------------OLD FOR OBLIQUE ORDERS - NOT NEEDED
function updateObliqueOrderStatus(theOrderNo,theRecno,licID){
	//Cancel in centremaps database
	document.ordersform.pupdatevalue.value = eval("document.ordersform.cancelled" + theRecno + ".value");
	document.ordersform.pupdateflag.value = theOrderNo;
	document.ordersform.submit();
	//Cancel licence in Blom database
	if(document.ordersform.pupdatevalue.value == "yes"){	
		theURL = "http://shop.centremapslive.co.uk/blomURBEX/urbexLIC/licenseAction.php?action=cancel&lic_id=" + licID; 
		winName =  "cancelOblique";  
		features = "menubar=no,toolbar=no,scrollbars=no,resizable=no,width=200,height=200";
		window.open(theURL,winName,features);
	}
}
//*******************Shows the selected user Oblique Imagery requests
function getUserObliqueOrders(theUserID){
	document.varform.userid.value = theUserID;
	document.varform.action = "userObliqueOrders.php";
	document.varform.submit();
}
*/

//-------------------------------------------------------------------------

//************End of file
