//--------------------------------------------------------
//centremaps.js
//CentreMaps
//Lovell Johns Ltd.
//Code to deal with ordering, login and customer details
//-------------------------------------------------------

//*******************Globals
var areaYextent = 1100000;										//Total Y extent of the whole map area (UK)
var storedJobNameValue;											//Current values of the text boxes when got focus	
var storedTitleValue;
var storedInfoValue;
var storedClientValue;
var storedJobrefValue;
var centreX;
var centreY;
var timerID;
var http;

//------------------------------------------------------------------GENERAL SCRIPTS

//*******************Opens the main application in a new window
function openApp(theURL){
	w = screen.width <= 800? 750 : 950;
	h = screen.width <= 800? 500 : 700;	
	var winName =  "cmaps";  
	var features = "menubar=no,toolbar=no,scrollbars=yes,resizable=yes,width=" + w + ",height=" + h;
	window.open(theURL,winName,features);
}

//*******************Set focus on the login form
function setFocus(){
	document.varform.name.focus();
}

//*******************Show a previous custom product the user has bought data for in the main map window.
function showIt(passedGeom,theData,OVString,prodType,extentInput,theScale,theAllowOverlays,theMaxSize,theDiscountModel,theMinPrice,thePriceperkm,theStyle,theOnlineSize,theDataName,theFullDataName,thePriceCode,theUserShapes,passedGSInfo,passedScales,ismulti,hasSuppliers,theRegion,theInterface,isLimited,fromSB){		
	if(fromSB == "frombasket"){
		var theFormName = "confirmform";
	}else{
		var theFormName = "varform";
	}
	//Remove MySQL formating
	var sep1 = passedGeom.indexOf("((");	
	var sep2 = passedGeom.indexOf("))");	
	extentGeom =  passedGeom.substring((sep1+2),sep2);
	
	//Defining a centre point for main mapping 
	getCentrePoint(extentGeom,"custom");

	//Define the type of map extent input
	if((extentInput != "radius") && (extentInput != "extent") && (extentInput != "user")  && (extentInput != "ground") && (extentInput != "draw") && (extentInput != "") && (extentInput != "gspoint") && (extentInput != "gsarea") && (extentInput != "gsmap") && (extentInput != "mapping")){   
		eval("document." + theFormName + ".extentinput.value = 'paper'");
	}else{
		eval("document." + theFormName + ".extentinput.value = '" + extentInput + "'");
	}
	
	//Store info of the selected previous order in hidden fields
	eval("document." + theFormName + ".papersize.value = '" + extentInput + "'");
	eval("document." + theFormName + ".extent.value = '" + extentGeom + "'");
	eval("document." + theFormName + ".style.value = '" + theStyle + "'");
	eval("document." + theFormName + ".data.value = '" + theData + "'");
	eval("document." + theFormName + ".overlay.value = '" + OVString + "'");
	eval("document." + theFormName + ".cx.value = '" + centreX + "'");
	eval("document." + theFormName + ".cy.value = '" + centreY + "'");
	eval("document." + theFormName + ".dataformat.value = '" + prodType + "'");
	eval("document." + theFormName + ".scale.value = '" + theScale + "'");
	eval("document." + theFormName + ".dataDescript.value = '" + theDataName + "'");
	eval("document." + theFormName + ".priceperkm.value = '" + thePriceperkm + "'");
	eval("document." + theFormName + ".minprice.value = '" + theMinPrice + "'");
	eval("document." + theFormName + ".maxsize.value = '" + theMaxSize + "'");
	eval("document." + theFormName + ".onlineorder.value = '" + theOnlineSize + "'");
	eval("document." + theFormName + ".allowOver.value = '" + theAllowOverlays + "'");
	eval("document." + theFormName + ".discountModel.value = '" + theDiscountModel + "'");
	eval("document." + theFormName + ".fullDataName.value = '" + theFullDataName + "'");
	eval("document." + theFormName + ".extentzoom.value = 'yes'");
	eval("document." + theFormName + ".pricecode.value = '" + thePriceCode + "'");
	eval("document." + theFormName + ".productoption.value = 'custom'");	
	if(fromSB == "frombasket"){
		eval("document." + theFormName + ".currentSavedShapes.value = '" + theUserShapes + "'");
		eval("document." + theFormName + ".shapesFrom.value = 'basket'");	
	}
	eval("document." + theFormName + ".userShapes.value = '" + theUserShapes + "'");
	eval("document." + theFormName + ".gsInfo.value = '" + passedGSInfo + "'");
	eval("document." + theFormName + ".thescales.value = '" + passedScales + "'");
	eval("document." + theFormName + ".ismultiextent.value = '" + ismulti + "'");
	eval("document." + theFormName + ".suppliers.value = '" + hasSuppliers + "'");
	eval("document." + theFormName + ".region.value = '" + theRegion + "'");
	eval("document." + theFormName + ".interface.value = '" + theInterface + "'");
	eval("document." + theFormName + ".availibility.value = '" + isLimited + "'");

	//Reload the page
	if(fromSB == "frombasket"){
		submittheform('reshow');
	}else{
		submittheform('reorder');		
	}
}

//*******************Show a previous fixed product the user has bought data for in the main map window.
function showItFixed(passedGeom,theData,prodType,thePriceperkm,theStyle,theDataName,theFullDataName,theFixedId,theRegion,theInterface){
	
	//Remove MySQL formating
	var sep1 = passedGeom.indexOf("((");	
	var sep2 = passedGeom.indexOf("))");	
	extentGeom =  passedGeom.substring((sep1+2),sep2);

	//Defining a centre point for main mapping 
	getCentrePoint(extentGeom,"fixed");

	//Store info of the selected previous order in hidden fields
	document.varform.data.value = theData;
	document.varform.dataformat.value = prodType;
	document.varform.allowOver.value = "no";
	document.varform.priceperkm.value = thePriceperkm;
	document.varform.style.value = theStyle;
	document.varform.fullDataName.value = theFullDataName;
	document.varform.dataDescript.value = theDataName;
	document.varform.cx.value = centreX;
	document.varform.cy.value = centreY;
	document.varform.productoption.value = "fixed";
	document.varform.fixselected.value = theData + "|" + theFixedId;   
	document.varform.lod.value = "3";				//Always zoom to second level of detail
	document.varform.viewextent.value = "2150";		//At this view extent (m)
	document.varform.extent.value = extentGeom;
	document.varform.fixedzoom.value = "yes";
	document.varform.region.value = theRegion;
	document.varform.interface.value = theInterface;
	
	//Reload the page
	submittheform('reorder');

}

//*******************Define centre point of the passed extent
function getCentrePoint(extentGeom,theType){	
	var theCoords = extentGeom.split(",");
	var newCoorString = "";
	for(var n=0;n<theCoords.length;n++){
		var sep = theCoords[n].indexOf(" ");
		var theX = Number(theCoords[n].substring(0,sep));
		var theY = Number(theCoords[n].substring((sep+1),theCoords[n].length));		
		
		if(n==0){
			var minX = theX;
			var minY = theY;
			var maxX = theX;
			var maxY = theY;
		}else{
			if(theX < minX){
				minX = theX;
			}		
			if(theX > maxX){
				maxX = theX;
			}		
			if(theY < minY){
				minY = theY;
			}		
			if(theY > maxY){
				maxY = theY;
			}
		}	
	}
	
	//Define the centre point
	if(theType == "custom"){
		centreX = String(minX + ((maxX - minX) /2));
		centreY = String(areaYextent - (minY + ((maxY - minY) /2)));	
	}else{
		centreX = String(minX + ((maxX - minX) /2));
		centreY = String((minY + ((maxY - minY) /2)));   //Fixed Y in actual os coordinates
	}	
	
}

//*******************Pay now/continue to confirm page/request invoice
function buyIt(theType){
	if(theType == "continue"){
		if(document.custform.permissions.value == "save"){ 				
			document.custform.action = "placeorder.php";
			document.custform.submit();
		}else{			
			if(document.custform.compid.value == ""){				//Not part of company account - need to check the details
				theForm = eval("document.custform");
				if(form_validator(theForm,"reduced")){
					document.custform.action = "placeorder.php";
					document.custform.submit();
				}else{
					return (false);
				}			
			}else{
				document.custform.action = "placeorder.php";
				document.custform.submit();			
			}						
		}		
	}else if(theType == "invoice"){	
		document.toinvoice.action ="ordered.php";
		document.toinvoice.submit();
	}else if(theType == "cancel"){	
		document.toinvoice.action ="cancelorder.php";
		document.toinvoice.submit();
	}else if(theType == "paynow"){	
		document.topass.submit();     								//******UNCOMMENT WHEN LIVE
	}else if(theType == "save"){	
		document.toinvoice.action ="ordersaved.php";
		document.toinvoice.savedfrom.value = "placeorder";			//Define where order saved from - placeorder page
		document.toinvoice.submit()
	}else if(theType == "savefrombasket"){	
		document.confirmform.action ="ordersaved.php";
		document.confirmform.savedfrom.value = "basket";			//Define where order saved from - shopping basket
		document.confirmform.submit()
	}
		
	return (true);	
}

//****************Formats number to 2 decimal places.
function formatString(inString){	
	var temp = Number(inString) % 1;
	var temp1 = Number(inString) - temp;
	var temp2 = Math.round(temp * 100);
	var formattedString = String(temp1) + "." ;
	if(temp2 < 10){
		formattedString = formattedString + "0" + String(temp2);
	}else{
		formattedString = formattedString + String(temp2);
	}
	return formattedString;
}

//-------------------------------------------------------------------REGISTRATION SCRIPTS
//*******************Defines options from check boxes 
function setCheckOptions(theControl,theSource){
	if(theControl == "mmaccess"){
		if(document.custform.mmaccesschk.checked){
			document.custform.mmaccess.value = "pending";
			if(theSource == "new"){
				regShowHide("show");
			}
		}else{
			document.custform.mmaccess.value = "no";
			if(theSource == "new"){
				regShowHide("hide");
			}	
		}	
	}else if(theControl == "accaccess"){
		if(document.custform.accaccesschk.checked){
			document.custform.accaccess.value = "pending";
			if(theSource == "new"){
				regShowHide("show");
			}	
		}else{
			document.custform.accaccess.value = "no";
			if(theSource == "new"){
				regShowHide("hide");
			}
		}	
	}else if(theControl == "mailing1"){
		if(document.custform.mailing1chk.checked){
			document.custform.mailing1.value = "yes";	
		}else{
			document.custform.mailing1.value = "no";
		}	
	}else if(theControl == "mailing2"){
		if(document.custform.mailing2chk.checked){
			document.custform.mailing2.value = "yes";	
		}else{
			document.custform.mailing2.value = "no";
		}	
	}else if(theControl == "notifyadmin"){
		if(document.custform.notifyadminchk.checked){
			document.custform.notifyadmin.value = "yes";	
		}else{
			document.custform.notifyadmin.value = "no";
		}
	}else if(theControl == "notifyuser"){
		if(document.custform.notifyuserchk.checked){
			document.custform.notifyuser.value = "yes";	
		}else{
			document.custform.notifyuser.value = "no";
		}
	}

}

//*******************Hides or shows further registartion details
function regShowHide(theAction){
	var test = checkBrowser('svg');
	if (is_nav6up) {										//Navigator6/Firefox
		var theObj = document.getElementById("regdetails");		
		if(theAction == "show"){
			theObj.className = 'bodyon';	
		}
		else{
			theObj.className = 'bodyoff';			
		}									
	}else{													//Opera/IE		
		if(theAction == "show"){
			var toEval = "regdetails.className='bodyon'";	
		}else{
			var toEval = "regdetails.className='bodyoff'";
		}
		eval(toEval);
	}	
}

//-------------------------------------------------------------------MULTI USER SCRIPTS
/*******************Remove the multi-user info in multi-user accout
function updateMultiUser(custID,itemID){

	var answer = confirm ("This will update user information. Are you sure?");
	if (answer){	
		if(check_multiOK(itemID)){
			document.custform.upID.value = custID;
			document.custform.upName.value = eval("document.custform.name_" + itemID + ".value");
			document.custform.upUname.value = eval("document.custform.email_" + itemID  + ".value");
			document.custform.upPwd.value = eval("document.custform.pwd_" + itemID + ".value");
			document.custform.upPmissions.value = eval("document.custform.permissions_" + itemID + ".value");			
			document.custform.action = "multiusers.php";
			eval("document.custform.submit()"); 
		} 
	}
}*/

/*******************Remove the multi-user from the multi-user accout
function removeMultiUser(theID){
	var answer = confirm ("This will completely remove this user. Are you sure?");
	if (answer){
		document.custform.rem.value = theID;		
		document.custform.action = "multiusers.php";
		eval("document.custform.submit()");  
	}
}*/

//*******************Form validation for updates to multi users
function check_multiOK(itemID){

	// Name field must not be empty
	if (eval("document.custform.name_" + itemID + ".value") == "") {
		alert("Please enter a value for the \"Name\" field.");
		return (false);
	}		
	// Email Address field must not be empty
	if (eval("document.custform.email_" + itemID  + ".value") == ""){
		alert("Please enter a value for the \"Email Address\" field.");
		return (false);
	}
	if(emailCheck (eval("document.custform.email_" + itemID  + ".value")) == false){
		return (false);	
	}		
	// Password field must not be empty
	if (eval("document.custform.pwd_" + itemID + ".value") == "") {
		alert("Please enter a value for the \"Password\" field.");
		return (false);
	}	
	if((eval("document.custform.pwd_" + itemID + ".value.length") > 20) || (eval("document.custform.pwd_" + itemID + ".value.length") < 6) ){
		alert("Please ensure \"Password\" is between 6 and 20 characters.");
		return (false);
	}	
	// if all Ok, return true
	return (true);
	
}

//*******************Removes the saved order item
function removeSavedItem(theOrderID){
	var answer = confirm ("This will completely remove this item. Are you sure?");
	if (answer){
		document.saveorderform.rem.value = theOrderID;		
		document.saveorderform.action = "usersavedorders2.php";
		eval("document.saveorderform.submit()");  
	}
}

//-------------------------------------------------------------------RESUPPLY SCRIPTS

//*******************Store the ID of the order when the user chooses that this is to be resupplied.
function getResupplyID(selObj,theID){

	//Add ID to the value
	if(selObj.checked){
		selObj.value = theID;
		var theAction = "add";
	}else{
		selObj.value = "";
		var theAction = "rem";
	}
	
	var currentVal = document.prevorderform.toresupply.value;	
	if(theAction == "add"){										//Add to list of IDS
		if(currentVal != ""){
			var newVal = currentVal + "," + theID
		}else{
			var newVal = theID
		}
	}else{														//Remove from list of IDS
		var theResupplyIDS = new Array();
		theResupplyIDS = currentVal.split(',');
		newVal = "";
		for(var c=0;c<(theResupplyIDS.length);c++){
			if(theResupplyIDS[c] != theID){
				if(newVal == ""){
					newVal = theResupplyIDS[c];
				}else{
					newVal += "," + theResupplyIDS[c]; 
				}	
			}
		}
	}
	
	document.prevorderform.toresupply.value = newVal;
}

//*******************Set the resupply delivery price and method
function setDeliveryPrice(selObj){
	var tempString = selObj.options[selObj.selectedIndex].value;
	if(tempString != "#"){	
		var theSep = tempString.indexOf(",");
		//var deliveryPrice = tempString.substring(0, theSep);
		//var deliveryMethod = tempString.substring((theSep + 1), tempString.length);
		var deliveryInfo =  tempString.split(",");
		var deliveryPrice = deliveryInfo[0];
		var deliveryMethod = deliveryInfo[1];
		var deliveryID = deliveryInfo[2];

		document.resupplyform.resupplydelprice.value = formatString(deliveryPrice);		
		if(deliveryPrice == "0"){
			document.getElementById("totdelprice").innerHTML = "N/A";
		}else{
			document.getElementById("totdelprice").innerHTML =  formatPrice(deliveryPrice);
		
		}
		document.resupplyform.resupplymethod.value = deliveryID;

		//Update the total order value and VAT
		totalItems = Number(document.resupplyform.ressuplyItemCnt.value);
		totalPrice = 0;
		totalVAT = 0;
		for(c=1;c<=totalItems;c++){
			if(eval("Number(document.resupplyform.reitemprice_" + c + ".value)") > 0){		
				totalPrice += eval("Number(document.resupplyform.reitemprice_" + c + ".value)");
				totalVAT += eval("(Number(document.resupplyform.reitemprice_" + c + ".value) * 0.175)");
			}
		}

		//Add delivery
		delPrice = Number(document.resupplyform.resupplydelprice.value);
		//Add international delivery
		intDelPrice = Number(document.resupplyform.intdelprice.value);
		if((delPrice != 0) && (intDelPrice != 0)){
			if (is_nav6up){
				var theObj = document.getElementById("intdelinfo");		
				theObj.className = 'bodyon';
			}else{	
				var toEval = "intdelinfo" + ".className='bodyon'";
				eval(toEval);	
			}
			intDelPrice = Number(document.resupplyform.intdelprice.value);
			document.resupplyform.ressuplyIntCharge.value = intDelPrice;			
		}else{
			intDelPrice = 0;
			if (is_nav6up){
				var theObj = document.getElementById("intdelinfo");		
				theObj.className = 'bodyoff';
			}else{	
				var toEval = "intdelinfo" + ".className='bodyoff'";
				eval(toEval);	
			}
			document.resupplyform.ressuplyIntCharge.value = intDelPrice;
		}
		
		//Store in hidden and show to screen	
		document.resupplyform.resupplyvatprice.value = Math.round(totalVAT*100)/100;
		document.resupplyform.resupplydataprice.value = Math.round(totalPrice*100)/100;
		document.resupplyform.resupplytotprice.value = Math.round((totalPrice + totalVAT + delPrice + intDelPrice)*100)/100;
		document.getElementById("totvatprice").innerHTML = formatPrice(Math.round(totalVAT*100)/100);
		document.getElementById("datatotprice").innerHTML = formatPrice(Math.round(totalPrice*100)/100);
		document.getElementById("totprice").innerHTML = "<strong>" + formatPrice(Math.round((totalPrice + totalVAT + delPrice + intDelPrice)*100)/100) + "</strong>";
	
	}	
}

//*******************Go back to My Account page from the resupply pages
function backToMyAccount(){
	window.document.location = "customer_details.php?toshow=orders";
}
//****************Send request to get the resupply price
function getResupplyPrice(theOrderNo,itemindex){
	var qstring = "orderno=" + theOrderNo + "&itemindex=" + itemindex; 
	http = createRequestObject(qstring);
	http.open('get', 'getResupplyPrice.php?' + qstring); 
	http.onreadystatechange = handleResupplyPriceResponse;
	http.send(null);
}
//****************Handles the response from getting the price
function handleResupplyPriceResponse() {
	if(http.readyState == 4){
		var response = http.responseText;
		//alert(response)
		if(response != ""){																//Check data returned
			if(response.indexOf('|' != -1)) {
				var tempArray = new Array();
				tempArray = response.split('|');
				var theAction = tempArray[0];
				if(theAction == "simplecalc"){								
					document.varform.minprice.value = tempArray[7];
					document.varform.extentArea.value =  tempArray[4];
					document.varform.priceperkm.value = tempArray[1];
					document.varform.overlayPrice.value = tempArray[6];
					document.varform.maxsize.value = tempArray[2];	
					document.varform.discountModel.value = tempArray[3];
					document.varform.data.value = tempArray[5];
					var itemIndex = tempArray[8];
	
					//Call price calculation
					calcPrice();
				}else{
					var itemIndex = tempArray[3];
					document.varform.orderprice.value = tempArray[2];			//Store returned price on hidden
				}
				
				//Store price (minus discount) and display to page
				var basePrice = Number(document.varform.orderprice.value);				
				var discountVal = eval("Number(document.resupplyform.reitemdisc_" + itemIndex + ".value)");
				
				var adjustedPrice = basePrice - (basePrice * discountVal);
				adjustedPrice = formatPrice(Math.round(adjustedPrice*100)/100);	
				eval("document.resupplyform.reitemprice_" + itemIndex + ".value = " + adjustedPrice);
				eval("document.resupplyform.reitemdiscamount_" + itemIndex + ".value = " + formatPrice(Math.round((basePrice * discountVal)*100)/100));					
				eval("document.getElementById('reprice_" + itemIndex + "').innerHTML = " + "formatPrice(" + adjustedPrice + ")");
				
				//Update the total order value and VAT
				totalItems = Number(document.resupplyform.ressuplyItemCnt.value);
				totalPrice = 0;
				totalVAT = 0;
				for(c=1;c<=totalItems;c++){
					if(eval("Number(document.resupplyform.reitemprice_" + c + ".value)") > 0){
						totalPrice += eval("Number(document.resupplyform.reitemprice_" + c + ".value)");
						totalVAT += eval("(Number(document.resupplyform.reitemprice_" + c + ".value) * 0.175)");
					}
					if(c==1){
						document.resupplyform.resupplyprices.value = eval("document.resupplyform.reitemprice_" + c + ".value");
						document.resupplyform.resupplydiscounts.value = eval("document.resupplyform.reitemdiscamount_" + c + ".value");
					}else{
						document.resupplyform.resupplyprices.value = document.resupplyform.resupplyprices.value + "," + eval("document.resupplyform.reitemprice_" + c + ".value");
						document.resupplyform.resupplydiscounts.value = document.resupplyform.resupplydiscounts.value + "," + eval("document.resupplyform.reitemdiscamount_" + c + ".value");
					}
				}
				//Add delivery
				delPrice = Number(document.resupplyform.resupplydelprice.value);
				//Add international delivery
				if(delPrice != 0){
					if (is_nav6up){
						var theObj = document.getElementById("intdelinfo");		
						theObj.className = 'bodyon';
					}else{	
						var toEval = "intdelinfo" + ".className='bodyon'";
						eval(toEval);	
					}
					intDelPrice = Number(document.resupplyform.intdelprice.value);
					document.resupplyform.ressuplyIntCharge.value = intDelPrice;
				}else{
					intDelPrice = 0;
					if (is_nav6up){
						var theObj = document.getElementById("intdelinfo");		
						theObj.className = 'bodyoff';
					}else{	
						var toEval = "intdelinfo" + ".className='bodyoff'";
						eval(toEval);	
					}
					document.resupplyform.ressuplyIntCharge.value = intDelPrice;
				}
			
				//Store in hidden and show to screen	
				document.resupplyform.resupplyvatprice.value = Math.round(totalVAT*100)/100;
				document.resupplyform.resupplydataprice.value = Math.round(totalPrice*100)/100;
				document.resupplyform.resupplytotprice.value = Math.round((totalPrice + totalVAT + delPrice + intDelPrice)*100)/100;
				document.getElementById("totvatprice").innerHTML = formatPrice(Math.round(totalVAT*100)/100);
				document.getElementById("datatotprice").innerHTML = formatPrice(Math.round(totalPrice*100)/100);
				document.getElementById("totprice").innerHTML = "<strong>" + formatPrice(Math.round((totalPrice + totalVAT + delPrice + intDelPrice)*100)/100) + "</strong>";
					
			}
		}
	}
}

//*******************Check if user has defined a resupply method
function resupplyValidator(theForm){
	//Check delivery choosen
	if((theForm.thedelmethod.value == "") || (theForm.thedelmethod.value == "#")) {
		alert("Please define a \"Delivery Method\".");
		return (false);
	}	
	//Check all item prices have been checked
	totalItems = Number(document.resupplyform.ressuplyItemCnt.value);
	for(c=1;c<=totalItems;c++){
		if(eval("Number(document.resupplyform.reitemprice_" + c + ".value)") == 0){
			alert("Please check the price for item " + c );
			return (false);
		}
	}
	return (true);
}

//-------------------------------------------------------------------BUY SAVED ORDERS SCRIPTS
//*******************Store the ID of the saved order when the user chooses that this is to be purchasd now.
function getBuyNowID(selObj,theID){

	//Add ID to the value
	if(selObj.checked){
		selObj.value = theID;
		var theAction = "add";
	}else{
		selObj.value = "";
		var theAction = "rem";
	}
	
	var currentVal = document.saveorderform.tobuynow.value;			
	if(theAction == "add"){											//Add to list of IDS
		if(currentVal != ""){
			var newVal = currentVal + "," + theID
		}else{
			var newVal = theID
		}
	}else{															//Remove from list of IDS
		var theBuyNowIDS = new Array();
		theBuyNowIDS = currentVal.split(',');
		newVal = "";
		for(var c=0;c<(theBuyNowIDS.length);c++){
			if(theBuyNowIDS[c] != theID){
				if(newVal == ""){
					newVal = theBuyNowIDS[c];
				}else{
					newVal += "," + theBuyNowIDS[c]; 
				}	
			}
		}
	}
	
	document.saveorderform.tobuynow.value = newVal;
}

//-------------------------------------------------------------------SHOPPING BASKET SCRIPTS
//*******************Remove selected product from current order
function removeProduct(theID,typeToDelete){
	var answer = confirm ("This will completely remove this product. Are you sure?");
	if (answer){
		document.confirmform.rem.value = theID;
		document.confirmform.updatethis.value = "remove";
		document.confirmform.productupdate.value = typeToDelete;
		document.confirmform.action = "basket.php";
		document.confirmform.submit();  
	}			
}

//*******************Reload the shooping basket page
function reloadBasket(){
	document.confirmform.action = "basket.php";
	document.confirmform.submit();  		
}

//*******************Reload the shopping basket page setting the chosen option
function chooseOption(selObj,theID,theInput,recCnt,itemType){
	var theValue = selObj.options[selObj.selectedIndex].value;
	eval("document.confirmform." + theInput + ".value = '" + theValue + "'");
	eval("document.confirmform.updatethis.value = '" + theInput + "'");
	document.confirmform.up.value = theID;
	var theValueTopass = theValue.replace(/\+/, "plus");			//Ensure "+" not passes	
		
	//Define query string to pass info regarding update
	var qstring = "updatethis=" + document.confirmform.updatethis.value + "&up=" + document.confirmform.up.value + "&" + theInput + "=" + theValueTopass + "&itemno=" + String(recCnt);
	aDate = new Date();
	qstring += "&thetime=" + String(aDate.getTime());
	updateBasketElement(qstring);		

}

//*******************Reload the shopping basket page setting the chosen format
function chooseFormat(selObj,theID,theInput,recCnt,theType){
	//Set hidden field to store new format info to update on reloading the page.
	var theValues = (selObj.options[selObj.selectedIndex].value).split(",");	
	eval("document.confirmform.supplyas.value = '" + theValues[0] + "'");
	eval("document.confirmform.supplyasid.value = '" + theValues[1] + "'");
	eval("document.confirmform.updatethis.value = '" + theInput + "'");	
	eval("document.confirmform.productupdate.value = '" + theType + "'");
	var isTiled = eval("document.confirmform.istiled" + String(recCnt) + ".value");			//Get isTiled value
	if(isTiled == ""){
		isTiled = "no";
	}
	//Check if iten contain user shapes and warn if new format not PDF or TIFF
	if((eval("document.confirmform.hasshapes" + recCnt + ".value") == "yes") && ((theValues[0].substring(0,3) != "pdf") && (theValues[0].substring(0,3) != "tif"))){
		alert("Please note this item contains elements drawn by the user which can only be written to TIFF and PDF output.");
	}
	document.confirmform.up.value = theID;

	//Define query string to pass info regarding update
	var qstring = "updatethis=" + document.confirmform.updatethis.value + "&up=" + document.confirmform.up.value + "&supplyas=" + document.confirmform.supplyas.value + "&supplyasid=" + document.confirmform.supplyasid.value + "&productupdate=" + document.confirmform.productupdate.value + "&istiled=" + isTiled + "&itemno=" + String(recCnt);
	aDate = new Date();
	qstring += "&thetime=" + String(aDate.getTime());
	
	updateBasketElement(qstring);
	
}

//****************Send request to get update shopping basket items
function updateBasketElement(qstring) {
	http = createRequestObject();
	http.open('get', 'updatebasketelement.php?' + qstring); 
	http.onreadystatechange = handleUpBasketResponse;
	http.send(null);
}

//****************Handles the responce from updatebasketelement.php to update shopping basket items
function handleUpBasketResponse() {
	if(http.readyState == 4){
		var response = http.responseText;	
		var theResponses = new Array();
		theResponses = response.split("|");
		if(theResponses[0] == "no"){
			alert("There has been a problem updating information. Please try again.");		
		}else{			
			if(theResponses[1] == "supplyas"){
				if(((theResponses[2].toLowerCase() == "pdf") || (theResponses[2].toLowerCase() == "pdfx")) && (theResponses[3] != "yes")){		//Make margin info visible
					if (is_nav6up){
						var theObj = document.getElementById("margininfo" + theResponses[4]);		
						theObj.className = 'bodyon';
					}else{	
						var toEval = "margininfo" + theResponses[4] + ".className='bodyon'";
						eval(toEval);	
					}												
				}else{																								//Make margin info invisible
					if (is_nav6up){
						var theObj = document.getElementById("margininfo" + theResponses[4]);		
						theObj.className = 'bodyoff';
					}else{
						var toEval = "margininfo" + theResponses[4] + ".className='bodyoff'";
						eval(toEval);			
					}	
				}
			}
			
			//Some updates to shopping basket items update pricing information (This is easier to update all the relevant info by reloading the page)
			if((theResponses[1] == "printcopies") || (theResponses[1] == "printfinish") || (theResponses[1] == "terminals") || (theResponses[1] == "fixedterminals") || (theResponses[1] == "fixeddelmethod") || (theResponses[1] == "delmethod") || (theResponses[1] == "fixedlictype") || (theResponses[1] == "lictype")|| (theResponses[1] == "printlicences")){
				if(theResponses[1].indexOf("fixed") == 0){
					document.confirmform.action = "basket.php#fixeditem" + theResponses[3];
				}else{
					document.confirmform.action = "basket.php#item" + theResponses[3];
				}
				eval("document.confirmform.submit()");
			}			
		}		
	}
}


//*******************Check if tabs and returns are in the input string
function checkChars(checkStr){
	var invalids = "\t\r\n\f";	
	var allValid = true;
	newString = "";
	for (i=0;i<checkStr.length; i++){
		ch = checkStr.charAt(i);
		isFound = false;
		for (j=0; j<invalids.length;j++){
			if (ch == invalids.charAt(j)){
				isFound = true;
				break;		
			}
		}		
		if(ch == "'"){
			ch = "\'";
		}else if (ch == '"'){		//Ignore double quotes
			isFound = true;
		}			
		if(isFound == false){
			newString = newString + ch;
		}
	}
	return newString;
}

//*******************Encodes returns to display correctly in the textarea when reloading page - (Called for Marginalia info only)
function checkChars2(checkStr){
	var invalids1 = "\t\f";
	var invalids2 = "\r\n";	
	var allValid = true;
	newString = "";
	for (i=0;i<checkStr.length; i++){
		ch = checkStr.charAt(i);
		isFound = false;
		for (j=0; j<invalids1.length;j++){
			if (ch == invalids1.charAt(j)){
				isFound = true;
				break;		
			}
		}
		if(isFound == false){
			for (j=0; j<invalids2.length;j++){
				if (ch == invalids2.charAt(j)){
					if(j==0){
						ch = "\\r";
					}else{
						ch = "\\n";
					}
					break;		
				}
			}	
			if(ch == "'"){
				ch = "\'";
			}else if (ch == '"'){		//Ignore double quotes
				isFound = true;
			}			
			if(isFound == false){
				newString = newString + ch;
			}
		
		}
	}
	return newString;
}

//*******************Store the current values of the text boxes when got focus
function storeEntered(theID,recCnt,theType){
	if(theType == "job"){
		storedJobNameValue = eval("document.confirmform.jobname" + recCnt + ".value");
		eval("document.confirmform.currentActive.value='" + "jobname" + recCnt + "'");
	}else if(theType == "client"){	
		storedClientValue = eval("document.confirmform.client" + recCnt + ".value");
		eval("document.confirmform.currentActive.value='" + "client" + recCnt + "'");
	}else if(theType == "jobref"){	
		storedJobNameValue = eval("document.confirmform.jobref" + recCnt + ".value");
		eval("document.confirmform.currentActive.value='" + "jobref" + recCnt + "'");	 	 
	}else if(theType == "title"){	
		storedTitleValue = eval("document.confirmform.printtitle" + recCnt + ".value");
		eval("document.confirmform.currentActive.value='" + "printtitle" + recCnt + "'");
	}else if(theType == "info"){	
		storedInfoValue = eval("document.confirmform.printinfo" + recCnt + ".value");
		eval("document.confirmform.currentActive.value='" + "printinfo" + recCnt + "'");
	}else if(theType == "printno"){
		storedInfoValue = eval("document.confirmform.printcopies" + recCnt + ".value");
		eval("document.confirmform.currentActive.value='" + "printcopies" + recCnt + "'");
	}else if(theType == "proj"){
		storedInfoValue = eval("document.confirmform.projname" + recCnt + ".value");
		eval("document.confirmform.currentActive.value='" + "projname" + recCnt + "'");
	}else if(theType == "fixedjob"){
		storedInfoValue = eval("document.confirmform.fixedjobname" + recCnt + ".value");
		eval("document.confirmform.currentActive.value='" + "fixedjobname" + recCnt + "'");
	}else if(theType == "fixedjobref"){
		storedInfoValue = eval("document.confirmform.fixedjobref" + recCnt + ".value");
		eval("document.confirmform.currentActive.value='" + "fixedjobref" + recCnt + "'");
	}else if(theType == "fixedclient"){
		storedInfoValue = eval("document.confirmform.fixedclient" + recCnt + ".value");
		eval("document.confirmform.currentActive.value='" + "fixedclient" + recCnt + "'");
	}
				
}

//*******************Check if the input need updating (checks input  after focus lost with input before focus) - called when exiting all text input boxes.
function checkEntered(theID,recCnt,theType){
	var updateIt = true;
	var itemType = "custom";
	if(theType == "jobname"){
		var theValue1 = eval("document.confirmform.jobname" + recCnt + ".value")
		if(storedJobNameValue == theValue1){
			 updateIt = false;
		}
	}else if(theType == "client"){
		var theValue1 = eval("document.confirmform.client" + recCnt + ".value")
		if(storedClientValue == theValue1){
			updateIt = false;
		}		
	}else if(theType == "jobref"){
		var theValue1 = eval("document.confirmform.jobref" + recCnt + ".value")
		if(storedJobrefValue == theValue1){
			updateIt = false;
		}		
	}else if(theType == "printtitle"){
		var theValue1 = eval("document.confirmform.printtitle" + recCnt + ".value")
		if(storedTitleValue == theValue1){
 			updateIt = false;
		}
	}else if(theType == "printinfo"){
		var theValue1 = eval("document.confirmform.printinfo" + recCnt + ".value")
		if(storedInfoValue == theValue1){
			 updateIt = false;
		}
	}else if(theType == "printcopies"){
		var theValue1 = eval("document.confirmform.printcopies" + recCnt + ".value")		
		if(Number(theValue1) >= 0){
			if(storedInfoValue == theValue1){
				 updateIt = false;
			}
		}else{
			eval("document.confirmform.printcopies" + recCnt + ".value = '0'")	
		}
	}else if(theType == "projname"){
		var theValue1 = eval("document.confirmform.projname" + recCnt + ".value")
		if(storedInfoValue == theValue1){
			 updateIt = false;
		}
	}else if(theType == "fixedjobname"){
	 	itemType = "fixed";
		var theValue1 = eval("document.confirmform.fixedjobname" + recCnt + ".value")
		if(storedInfoValue == theValue1){
			 updateIt = false;
		}
	}else if(theType == "fixedjobref"){
	 	itemType = "fixed";
		var theValue1 = eval("document.confirmform.fixedjobref" + recCnt + ".value")
		if(storedInfoValue == theValue1){
			 updateIt = false;
		}
	}else if(theType == "fixedclient"){
	 	itemType = "fixed";
		var theValue1 = eval("document.confirmform.fixedclient" + recCnt + ".value")
		if(storedInfoValue == theValue1){
			 updateIt = false;
		}
	}
	
	if(updateIt){
		updateProduct(theID,recCnt,itemType,theType);
	}

}

//*******************Stores the active form element when it recieves focus (used to ensure it still has focus when the page reloaded)
function storeActive(recCnt,theType){
	eval("document.confirmform.currentActive.value='" + theType + recCnt + "'");
}

//*******************Sets the focus of the active element before reloading when reloading the basket
function setElementFocus(){
	if(document.confirmform.currentActive.value != ""){
		var testObj = document.getElementById(document.confirmform.currentActive.value);      //getElementbyid ("document.confirmform." +  document.confirmform.currentActive);	
		if(testObj != null){
			var toEval = "document.confirmform." +  document.confirmform.currentActive.value + ".focus()";
			timerID = setInterval("setTheFocus('" + toEval + "')",1000);
		}
	}
}
function setTheFocus(toEval){
	eval(toEval);
	clearInterval(timerID);
}

//*******************Update the selected item in the shopping basket
function updateProduct(theID,recCnt,itemType,theType){

	//Check input and amend on the form if necessary
	theValue1 = eval("document.confirmform." + theType + recCnt + ".value");
	
	//Relace any invalid characters in input
	if(theType != "printinfo"){	
		theValue = checkChars(theValue1);			
	}else{
		theValue = checkChars2(theValue1);
	}
	
	var theValue = theValue.replace(/\&/g, "-amp-");
	var toEval ='document.confirmform.' + theType + '.value = "' + theValue + '"'
	eval(toEval);

	document.confirmform.up.value = theID;
	document.confirmform.updatethis.value = theType;

	//Define query string to pass info regarding update
	var qstring = "updatethis=" + document.confirmform.updatethis.value + "&up=" + document.confirmform.up.value + "&" + theType + "=" + theValue + "&itemno=" + String(recCnt);;
	aDate = new Date();
	qstring += "&thetime=" + String(aDate.getTime());
	updateBasketElement(qstring);
	
}

//*******************Go back to main ordering page from confirmation page
function reOrder(){
	//Reset hidden variable to ensure new uk map is set on opening the maim map page if ordering custome products
	if(document.confirmform.productoption.value == "custom"){			
		document.confirmform.lod.value='';
		document.confirmform.extent.value = "";
		document.confirmform.data.value = "";
		document.confirmform.overlay.value = "";
		document.confirmform.style.value = "";
		document.confirmform.scale.value = "";
		document.confirmform.papersize.value = "";
		document.confirmform.dataDescript.value = "";
		document.confirmform.priceperkm.value = "";
		document.confirmform.cx.value = "";
		document.confirmform.cy.value = "";	
		document.confirmform.minprice.value = "";
		document.confirmform.onlineorder.value = "";
		document.confirmform.maxsize.value = "";
		document.confirmform.allowOver.value = "";
		document.confirmform.discountModel.value = "";
		document.confirmform.currentSavedShapes.value = "";
		document.confirmform.pricecode.value = "";	
		document.confirmform.fullDataName.value = "";
		document.confirmform.extentinput.value = "";
		document.confirmform.extentzoom.value = "";	
		document.confirmform.viewextent.value = "";
		document.confirmform.dataformat.value = "";	
		document.confirmform.fixselected.value = "";
		document.confirmform.productoption.value = "custom";
	}
	
	if(document.confirmform.mapsize.value != ""){
		mapToUse = document.confirmform.mapsize.value;
	}		
	document.confirmform.action = mapToUse;
	document.confirmform.submit();  		
}

//******************Rebuild order components to display on main page
function reBuildOrder(theAction,theOID){
	if(theAction == "alter"){
		document.confirmform.alter.value = theOID; 		//Set that the item is to be altered when reeturning to basket by storing the order ID 
	}		
	//Get the item details
	aDate = new Date()	
	var qstring = "theoid=" + theOID + "&thetime=" + String(aDate.getTime());
	sndRebuildOrderReq(qstring);		
}
//****************Send request to get all info on the selected order item 
function sndRebuildOrderReq(qstring) {
	http = createRequestObject();
	var test = checkBrowser('svg');
	if(is_nav6up){			//CHECK!!!
		http.open('get', 'rebuildorder.php?' + qstring); 
	}else{
		http.open('get', 'rebuildorder.php?' + qstring, false); 
	}	
	http.onreadystatechange = handleRebuildOrderResponse;
	http.send(null);
}
//****************Handles the responce from rebuildorder.php to get all info on the selected order item 
function handleRebuildOrderResponse() {
	if(http.readyState == 4){
		var response = http.responseText;
		if(response != ""){
			var passedParams = new Array();
			passedParams = response.split('|');
			if(passedParams[0] == "ok"){				
				var sep = passedParams[1].indexOf("'frombasket'");
				if(sep != -1){
					var toPass = passedParams[1].substring(0,(sep+12));
					eval("showIt(" + toPass + ")");								//Pass all info to show on the main order page
				}else{
					alert("There has been an error retrieving order item information")
				}	
			}else{
				alert("There has been an error retrieving order item information")
			}
		}else{
			alert("There has been an error retrieving order item information")
		}
	}
}

//-------------------------------------------------------------------VALIDITY CHECK SCRIPTS

//*******************Email validity 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. */

		alert("Email address seems incorrect (check @ and .'s)");
		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) {
			alert("Ths username contains invalid characters.");
			return false;
		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("Ths domain name contains invalid characters.");
			return false;
		}
	}

	// See if "user" is valid 
	if (user.match(userPat)==null) {
		// user is not valid
		alert("The username doesn't seem to be valid.");
		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) {
				alert("Destination IP address is invalid!");
				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) {
			alert("The domain name does not seem to be valid.");
			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) {
		alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
		alert("This address is missing a hostname!");
		return false;
	}

	// If we've gotten this far, everything's valid!
	return true;
}

//*******************Form validation
function form_validator(theForm,theType){

	// Name field must not be empty
	if (theForm.name.value == "") {
	alert("Please enter a value for the \"Name\" field.");
	theForm.name.focus();
	return (false);
	}
	
	// Address field must not be empty
	if (theForm.address1.value == "") {
	alert("Please enter a value for the \"Address\" field.");
	theForm.address1.focus();
	return (false);
	}
	
	if(theType != "reduced"){
		// Town field must not be empty
		if (theForm.town.value == "") {
		alert("Please enter a value for the \"Town\" field.");
		theForm.town.focus();
		return (false);
		}
	}
	
	// Post Code field must not be empty
	if (theForm.postcode.value == "") {
	alert("Please enter a value for the \"Post Code\" field.");
	theForm.postcode.focus();
	return (false);
	}
	
	//Check Telephone for telephone number
	if (theForm.telephone.value == ""){
		alert('Please enter a value for the \"Telephone\" field.');
		theForm.telephone.focus();
		return (false);
	}
	
	var checkOK = "0123456789-+() \t\r\n\f";
	var checkStr = theForm.telephone.value;
	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){
		alert("Please enter only digit, whitespace and \"+()\" characters in the \"Telephone\" field.");
		theForm.telephone.focus();
		return (false);
	}
		
	if(theType == "full"){
		// Email Address field must not be empty
		if (theForm.email.value==""){
		alert("Please enter a value for the \"Email Address\" field.");
		theForm.email.focus();
		return (false);
		}	
		if(emailCheck (theForm.email.value) == false){
			theForm.email.focus();
			return (false);	
		}	
		// Password field must not be empty
		if (theForm.pwd1.value == "") {
		alert("Please enter a value for the \"Password\" field.");
		theForm.pwd1.focus();
		return (false);
		}		
	}
	// if all Ok, return true
	return (true);
}

//*******************Form validation for intial registration check name, email and password only.
function form_validator1(theForm,theType){

	// Name field must not be empty
	if (theForm.name.value == "") {
	alert("Please enter a value for the \"Name\" field.");
	theForm.name.focus();
	return (false);
	}
		
	// Email Address field must not be empty
	if (theForm.email.value==""){
	alert("Please enter a value for the \"Email Address\" field.");
	theForm.email.focus();
	return (false);
	}
		
	if(emailCheck (theForm.email.value) == false){
		theForm.email.focus();
		return (false);	
	}
		
	// Password field must not be empty
	if (theForm.pwd1.value == "") {
	alert("Please enter a value for the \"Password\" field.");
	theForm.pwd1.focus();
	return (false);
	}
	
	if((theForm.pwd1.value.length > 20) || (theForm.pwd1.value.length < 6) ){
	alert("Please ensure \"Password\" is between 6 and 20 characters.");
	theForm.pwd1.focus();
	return (false);
	}
	
	// Check passwords match (initial registration only)
	if((theType == "new") || (theType == "multi")){		
		if (theForm.pwd1.value != theForm.pwd2.value) {
			alert("\"Password\" not verified correctly.");
			theForm.pwd2.focus();
			theForm.pwd2.value = "";
			return (false);
		}
	}
	
	if(theType != "multi"){	
		//If user requested MasterMap or Account address must be supplied
		if ((theForm.mmaccess.value != "no") || (theForm.accaccess.value != "no")){
			if(form_validator(theForm,"full")){
				return (true);
			}
			else{
				return (false);
			}
		}
	}
	// if all Ok, return true
	return (true);
	
	
}

//*******************Check the data supply format, terminals, licence type and jobname has been defined before proceeding to buy
//						Also check licence has been agreed to
function checkFormat(nofProducts,nofFixedProducts,theAction,passedPrice){
	var isOK = true;
	if((nofProducts ==0) && (nofFixedProducts == 0)){			//No products selected
		alert("No products have been selected.");
		isOK = false;
	}else{
		//Check custom products
		if(nofProducts != 0){	
			for(var p=0; p<nofProducts;p++){
				var totest1 = eval("document.confirmform.theformat" + String(p+1) + ".value");
				var totest2 = eval("document.confirmform.theterminals" + String(p+1) + ".value");
				var totest3 = eval("document.confirmform.theLicence" + String(p+1) + ".value");
				var totest4 = eval("document.confirmform.jobname" + String(p+1) + ".value");
				if (totest1 == ""){
					alert("Please ensure all product supply formats are defined.");
					isOK = false;
					break;
				}
				if (totest2 == ""){
					alert("Please ensure all no. of terminals are defined.");
					isOK = false;
					break;
				}
				if (totest3 == ""){
					alert("Please ensure all licence types have been defined.");
					isOK = false;
					break;
				}
				if (totest4 == ""){
					alert("Please ensure all job names/refernces have been defined.");
					isOK = false;
					break;
				}	
			}
		}
		//Check fixed products	
		if(nofFixedProducts != 0){	
			for(var p=nofProducts; p<(nofProducts + nofFixedProducts);p++){
				var totest1 = eval("document.confirmform.theformat" + String(p+1) + ".value");
				if (totest1 == ""){
					alert("Please ensure all product supply formats are defined.");
					isOK = false;
					break;
				}	
			}
		}	
	}
	
	if((theAction == "proceed") || (theAction == "proceed_confirm")){					//Only check terms check if proceeding with purchase
		if(document.confirmform.terms.checked == false){
			alert("Please 'Terms and conditions' have been read and accepted.");
			isOK = false;
		}
	}
	if(document.confirmform.requireupdate.value == "yes"){
		alert("Items on the shopping basket require updating. Please review.");
		isOK = false;
	}		
		
	if((isOK) && (theAction == "proceed_confirm")){
		document.orderform.action = "order.php";
		document.orderform.submit();  
	}else if((isOK) && (theAction == "proceed")){
		document.orderform.action = "ordered.php?passprice=" + passedPrice;
		document.orderform.submit();
	}
	else if((isOK) && (theAction == "save")){
		eval("document.orderform.submit()");  
		buyIt("savefrombasket");
	}
	
}

//*******************Login validation and submit of the form on the login page.
function runLogin(){

	var isOK = true;
	// Name field must not be empty
	if (document.varform.name.value == "") {
		alert("Please enter a value for the \"User name\" field.");
		isOK = false;
	}
	
	// Address field must not be empty
	if (document.varform.pwd.value == "") {
		alert("Please enter a value for the \"Password\" field.");
		isOK = false;
	}
	
	if(isOK){
		document.varform.login.value = "yes";
		document.varform.action = "loggedin.php"; //"login.php";	
		document.varform.submit();
	}
	
}

//************End of file