/*--------------------------------------------------------------
products.js
For CentreMapsLive Ver. 2
Code for retrieving products and info about selected products
Lovell Jonhs Ltd.
01/01/10
--------------------------------------------------------------*/

//----------------------------------------------------------GLOBALS
var maxProducts = 5;							//Maximum no. of selecte products allowed
var catList;									//List of category ids
var combineItems = new Array();					//Product combination items
var combineInfo = new Array();					//Product combination info
var combCnt = -1;
var selectedIndex = -1;							//The index of the current selected item in the selected products list
var addingNew = false;							//Defines if a selected product is added as a new item in the selected products list
var productCnt = 0;								//Number of products to add to the basket
var okToAddToBasket = true;						//Flags if any errors that mean cannot proceed to the basket	

//----------------------------------------------------------SCRIPTS TO RETRIEVE AND SELECT DATA PRODUCTS

//****************Show product info content
function showProductInfo(e,content1,content2,content3){
	evt = e || window.event;		
	var infoContent =   "<div style='position:absolute;top:5px;right:10px;'><a href='javascript:closePoductInfo();'>Close [x]</a></div>" ;  // "<a href='javascript:closePoductInfo();'>Close [X]</a></p>";
    infoContent += "<h2>" + content1 + "</h2><p>" + content2 + "</p><br/></br/>";	
	if(content3 == "yes"){
		infoContent += "<p><strong>Overlays Available</strong><br/>To add administrative boundaries to your mapping, simply order your OS product and then add boundaries in the shopping basket. You can choose from county-level, district-level, ward or parish boundaries.</p>";
	}	
	document.getElementById("productInfoContent").style.top =  Number(evt.clientY) + 5 + "px"; 
	document.getElementById("productInfoContent").style.left =  Number(evt.clientX) + 5 + "px"; 
	document.getElementById("productInfoContent").innerHTML = infoContent;
	document.getElementById("productInfoContent").style.display = "block";
	callCufon();
}
//****************Hide product info content
function closePoductInfo(){
	document.getElementById("productInfoContent").innerHTML = "";
	document.getElementById("productInfoContent").style.display = "none";
}
//****************Get categories
function getProductCategories(theRegion){
	var getProductCatsReq = new ajaxObject('getProductCats.php', handleGetProductCatsResponse);
	getProductCatsReq.update("region=" + theRegion,'POST');
}
//****************Handles the response from getProductCats.php to get all product categories.
function handleGetProductCatsResponse(responseText, responseStatus){
	if(responseStatus == 200){		
		if(responseText != ""){
			var responseArray = responseText.split("|");     //0=list of cat ids,1=cat for main section,2=other categories	
			document.getElementById("productListLayer").innerHTML = "<ul class='productList'>" + responseArray[1] + "</ul>";
			document.getElementById("otherProductListLayer").innerHTML = "<ul class='productList'>" + responseArray[2] + "</ul>";			
			catList = responseArray[0].split("~");
			for(c=0;c<catList.length;c++){
				$('zchm'+(c+1)).addEvent('click', function(e){
				e.stop();
				zchm.slideIn();
				hideMapLayers();  //Ensure road aerial tab closed
				var zchmIndex = Number(this.id.substring(4,this.id.length))-1;
				getProductsInCategory(catList[zchmIndex]);					
				});
			}
			//Create the dropdown list to choos category for previous orders
			var previousCategoriesString = "Category: <select name='optPrevCat' id='optPrevCat' onchange='refreshPrevious();' style='font-size:12px;'>";
			catNameList = responseArray[3].split("~");
			for(c=0;c<catNameList.length;c++){
				previousCategoriesString += "<option value='" + catList[c] + "'>" + catNameList[c] + "</option>";	
			}
			previousCategoriesString += "</select>";
			document.getElementById("previousCats").innerHTML = previousCategoriesString;		
		}else{
			document.getElementById("otherProductListLayer").innerHTML = "<p>No products found.</p>";
		}		
		timerId = setTimeout("showAvailable()",2500);			
	}
}
//****************Hide progress gif and show that products are available (instead of actually running the look up)
function showAvailable(){
	clearTimeout(timerId);
	document.getElementById("total_aerial").innerHTML = "<p class='prodsavailable'>(Available)</p";
	document.getElementById("total_height").innerHTML = "<p class='prodsavailable'>(Available)</p";
}
//****************Get the selected product category and send request to get data products
function getProductsInCategory(theCat){
	canHideIt = false;									//Stop the top tools automatically hiding  
	//Kill any existing supplier requests
	cancelSupplierReq("aerial");
	cancelSupplierReq("height");	
	//Add loading animation while retrieving products 
	document.getElementById("productsAvailable").innerHTML = "<br/>&nbsp;&nbsp;<img src='images/loading.gif' alt='loading...'/>";  
	//Set query string and send request to get data products
	var qstring = "cat=" + theCat + "&type=" + document.varform.productoption.value + "&ispriv=" + document.varform.isprivilege.value + "&cid=" + document.varform.cid.value + "&thereg=" + document.varform.region.value;		
	var getProductsReq = new ajaxObject('getProducts.php', handleGetProductsResponse);
	getProductsReq.update(qstring,'POST');
}
//****************Handles the response from getProducts.php to get all product info for the selected category
function handleGetProductsResponse(responseText, responseStatus){
	if(responseStatus == 200){				
		if(responseText != ""){																//Check data returned (See "getProduct.php" for format)		
			if(responseText.indexOf('|' != -1)) {								
				//For each product selected add to the view
				var dataProducts = responseText.split("~");								//Assign passed products to array	
				var tempArray = dataProducts[dataProducts.length-1].split('|');			//Get the category name (Cat info is in the final array element)
				var catName = tempArray[0];
				var colCnt = 0;
				var added = new Array();
				var acnt = -1;
				var needToGetSupplierInfo = false;
				var needToGetOverlaySupplierInfo = false;
				var outputString = "<table width='700px' border='0' cellspacing='8' cellpadding='0'><tr><td colspan='4'><table><tr><td><img src='images/titles/" + catName.replace(" ","") + ".png' width='625' height='26' alt='Category header' /></td><td><a href='#' id='zchmOut'>Close [x]</a></td></tr></table></td></tr><tr valign='top'>";					
				for(d=0;d<(dataProducts.length);d++){									
					var dataOptions = dataProducts[d].split('|');
					if(d == (dataProducts.length-1)){								//Final array element stores category information
						break;
					}else{
						colCnt +=1;
						if(colCnt == 5){
							colCnt = 1;
							outputString += "</tr><tr valign='top'>"; 
						}		
						//Get the full name
						if(dataOptions[2] != dataOptions[0]){
							var prodNameToPrint = dataOptions[0] + ": " + dataOptions[2];
						}else{
							var prodNameToPrint = dataOptions[0];
						}
						//Get sample image name
						if(dataOptions[7] == "yes"){
							var sampleImageName = dataOptions[1] + ".gif";	
						}else{
							var sampleImageName = "na.jpg";
						}
						sampleImageName = sampleImageName.replace(":","");
						sampleImageName = sampleImageName.replace(/,/g,"");					
						//Output to the page
						outputString += "<td width='150px' align='center'><img src='images/samples/" + sampleImageName + "' alt='sample image' width='150' height='100' style='cursor:help;border:1px solid #24318D;' onclick='showProductInfo(event,\"" + prodNameToPrint + "\",\"" + dataOptions[3] + "\",\"" + dataOptions[4] + "\");' onmouseover='Tip(\"Click to for more info on this product\");'/></a><br/><p class='prodname'><input type='radio' id='productChoice' name='productChoice' value='" + dataOptions[1] + "' onclick='getProductInfo(\"" + dataOptions[1] + "\",\"new\");' style='border:none;'/> " + prodNameToPrint + "</p><p class='proddetails'>From &pound;" + formatPrice(dataOptions[6]) + " (" + dataOptions[5] + ")</p></td>";
					}
					if((dataOptions[1] == "NULL_HEIGHT") || (dataOptions[1] == "NULL_AERIAL")){
						needToGetSupplierInfo = true;
						document.varform.data.value = dataOptions[1];						
					}else if(dataOptions[8] == "yes"){
						needToGetOverlaySupplierInfo = true;
					}					
				}
				
			
				if(colCnt == 0){
					outputString += "<td colspan='4'><p class='error'>No products were found in this category.</p></td></tr>";
				}else{				
					//Add extra cells to pad out (if necessary)
					if(colCnt < 4){
						var toAdd = 4 - colCnt;
						var toAddWidth = toAdd * 150;
						outputString += "<td colspan='" + toAdd + "' width='" + toAddWidth  + "px'><div id='supplierMessages'>&nbsp;</div></td></tr>";
					}else{
						outputString += "</tr><tr><td colspan='4' width='600px'><div id='supplierMessages'>&nbsp;</div></td><tr/>";
					}
				}
					
				//Show note that overlays available for MasterMap
				if(catName == "OS MasterMap"){
					outputString += "<tr><td colspan='4'><p align='center' style='color:#24318D;'><strong>Enhance your MasterMap:</strong> a range of Height and Aerial overlays will be offered when you define your data area</p></td></tr>";
				}	
						
				//Add area for supplier info
				outputString += "<tr><td colspan='4'><div id='supplierinfoAerial_layer' style='margin:10px;'></div><div id='supplierinfoHeight_layer' style='margin:10px;'></div></td></tr>";			
				outputString += "</table>"; 
				//Add HTML to the page												
				document.getElementById("productsAvailable").innerHTML = outputString;	
				if(needToGetSupplierInfo){
					getSupplierInfo(false);
				}else if(needToGetOverlaySupplierInfo){
					//To turn back on
					//getOverlaySupplierInfo("aerial",false);
					//timerId = setTimeout("getOverlaySupplierInfo('height',false)",5000);
					//getOverlaySupplierInfo("height",false);
				}						
				//Set event for collapse of info
				$('zchmOut').addEvent('click', function(e){
					e.stop();
					zchm.slideOut();
					//kill any height-aerial lookups
					cancelSupplierReq("aerial");
					cancelSupplierReq("height");
				});		
			}
		}
	}
}
//****************Get all the info about the selected product and store in hidden on the form (Called when selecting a new product)
function getProductInfo(thePassed,theType){						
	if((theType == "new") || (theType == "reorder") || (theType == "lookup")){
		var passedProdCode = thePassed;
	}else if(theType == "selected"){										//If called when highlighting a selected product get from the hidden field
		var passedProdCode = document.getElementById("data"+thePassed.value).value;  	
	}
	if(passedProdCode != ""){												//Set query string and send request to get product info
		passedProdCode = passedProdCode.replace("+","-plus-");				//Ensure '+' not included in the product code
		var qstring = "prodcode=" + passedProdCode + "&type=" + theType;	
		var getProductInfoReq = new ajaxObject('getProductInfo.php', handleGetProductInfoResponse);
		getProductInfoReq.update(qstring,'POST');
	}
}
//****************Get all the info about the selected product and store in hidden on the form (Called when highlighing the product in the user's list of selected products)
function getProductInfo2(thePassed,theType){
	//Define if this product is already highlighted (do nothing) or ensure the (hidden) radio button is checked
	var alreadySelected = false;
	for (var i=0; i < document.frmSelected.selectedproducts.length; i++){	
		if(document.frmSelected.selectedproducts[i].value == thePassed){
			if(document.frmSelected.selectedproducts[i].checked){
				alreadySelected = true;
			}else{
				document.frmSelected.selectedproducts[i].checked = true;		
			}
			break;	
		}
	}
	//Highlight this product
	if(alreadySelected == false){
		if((theType == "new") || (theType == "reorder") || (theType == "lookup")){
			var passedProdCode = thePassed;
		}else if(theType == "selected"){										//If called when highlighting a selected product get from the hidden field
			var passedProdCode = document.getElementById("data"+thePassed).value;  	
		}
		if(passedProdCode != ""){												//Set query string and send request to get product info
			passedProdCode = passedProdCode.replace("+","-plus-");				//Ensure '+' not included in the product code
			var qstring = "prodcode=" + passedProdCode + "&type=" + theType;
			var getProductInfoReq = new ajaxObject('getProductInfo.php', handleGetProductInfoResponse);
			getProductInfoReq.update(qstring,'POST');
		}
	}
}
//****************Handles the responce from getProductinfo.php to get all product info for the selected product	(Store all the passed info in hidden fields)
function handleGetProductInfoResponse(responseText, responseStatus){
	if(responseStatus == 200){						
		if(responseText != ""){	
			var tempArray1 = responseText.split("~");
			if(tempArray1[1] != "error"){
				if(tempArray1[0] == "lookup"){	
					addThisProduct(responseText);						//Call routine to add the product to selected list				
				}else{
					defineProductAction(responseText,"prompt");			//Define what to do with the selcted product (ie. add as new or replace selected)				
				}
			}else{
				showDialog('Error','There has been a problem retrieving product info.<br/>Please try again or choose another product.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
				zchm.slideOut();					//Hide product options
			}			
		}else{
			showDialog('Error','There has been a problem retrieving product info.<br/>Please try again or choose another product.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
			zchm.slideOut();					//Hide product options
		}
	}
}
//****************Define what to do with the selected product (Nothing, add as new product or reoplace the existing)
function defineProductAction(responseText,theAction){
	responseText = unescape(responseText);	
	var tempArray1 = responseText.split("~");
	var tempArray = tempArray1[1].split("|");
	var totalProducts = Number(document.getElementById("nofProducts").value);
	selectedIndex = -1;
	addingNew = false;
	if((tempArray1[0] == "new") && (totalProducts > 0)){					//Check if a product is currently selected							
		selectedIndex = getSelectedProductIndex();
		if(selectedIndex != -1){		
			if(theAction == "prompt"){		
				var dialogContent = "What do you want to do with this product?<br/><br/><input type='button' value='Add as New Product' id='newButton' onclick='defineProductAction(\"" + escape(responseText) + "\",\"new\");'>  <input type='button' value='Replace Existing' id='existButton' onclick='defineProductAction(\"" +  escape(responseText) + "\",\"replace\");'> <input type='button' value='Cancel' id='cancelButton' onclick='defineProductAction(\"" +  escape(responseText) + "\",\"cancel\");'>"
				showDialog('',dialogContent,'prompt');
			}else if(theAction == "new"){
				hideDialog();								
				selectedIndex = getNextEmptyIndex();							//Add as new product
				addingNew = true;
				addThisProduct(responseText);	
			}else if(theAction == "replace"){
				hideDialog();
				addThisProduct(responseText);
			}else if(theAction == "cancel"){
				hideDialog();
				zchm.slideOut();												//Hide product options
			}
		}else{
			selectedIndex = getNextEmptyIndex();								//Add as new product
			addingNew = true;
			addThisProduct(responseText);
		}
	}else{																	//Define the selected index as the next available 
		selectedIndex = getNextEmptyIndex();
		addingNew = true;
		addThisProduct(responseText);
	}
}
//****************Add the product to the selected list
function addThisProduct(responseText){
	responseText = unescape(responseText);
	var tempArray1 = responseText.split("~");
	if(tempArray1[0] == "lookup"){			// THIS CAN BE DELETED!!!Store all info for the lookup product ("Height" and "Aerial") (Format:(prodcode|scale|product|catid|partial|fulldesc|fullname|thescales|multiextent|suppliers|maxsize)							
		var tempArray = tempArray1[1].split("|");	
		//--Data type.	
		document.varform.data.value = tempArray[0]; 
		//--Scale 
		document.varform.scale.value = tempArray[1];			
		//--Full product name
		document.varform.dataDescript.value = tempArray[2];
		//--The coverage available
		document.varform.availibility.value = tempArray[4];
		//--The full data description 
		document.varform.fullDataDesc.value = tempArray[5];	
		//--Full product name 
		document.varform.fullDataName.value = tempArray[6];											
		//--Available Scales
		document.varform.thescales.value = tempArray[7];
		//--Is multi extent product
		document.varform.ismultiextent.value = tempArray[8];			
		//--Has Data suppliers
		document.varform.suppliers.value = tempArray[9];
		//--Max order size
		document.varform.maxsize.value = tempArray[10];	
		//--Order option custom or fixed
		document.varform.productoption.value = tempArray[11];
		//Get the 'overview' supplier list (ie @ the map centre)
		getSupplierInfo(false);					
	}else{				
		var tempArray = tempArray1[1].split("|");
		var totalProducts = Number(document.getElementById("nofProducts").value);
		var tooManyProducts = false;				
		if((tempArray1[0] == "new") && (addingNew) && ((totalProducts+1) > maxProducts)){					//Is a new product added to the selected list - Ensure it does not exceed the max no. (5)
			showDialog('Warning','Maximum number of selected products has been reached.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			tooManyProducts = true;
		}
		if(((tempArray1[0] == "new") || (tempArray1[0] == "reorder")) && (tooManyProducts == false)){												//Add a new product or replace an existing one		
			//Adding a new product - update the total number selected
			if(addingNew){		
				document.getElementById("nofProducts").value = Number(document.getElementById("nofProducts").value) + 1;
				hideShowProductMessage();
				var theAction = "new";											//Is a new product added to the list
			}else{
				var theAction = "change";										//Is a change to an existing selected product
			}
			//If changing the product check if the extent is valid for the new product
			if(theAction == "change"){
				var theExtentType = "";
				var theCurrentExtentID = document.getElementById("extent" + String(selectedIndex)).value;
				for(p=0; p < extentLayer.features.length;p++){
					if(extentLayer.features[p].attributes.id == theCurrentExtentID){
						if(String(extentLayer.features[p].geometry).indexOf("POINT") == 0){
							theExtentType = "point";
						}else{
							theExtentType = "poly";
						}
					}	
				}
				if(theExtentType != ""){
					var isOK = checkProductExtentAgree(tempArray[0],tempArray[8],theExtentType,theCurrentExtentID);
				}else{
					var isOK = true;
				}
				if(isOK == false){													//Cannot replace - add as a new item if possible
					if((totalProducts+1) > maxProducts){			
						showDialog('Warning','Cannot replace the current selected product as current extent type is incompatible.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
					}else{
						showDialog('Warning','Cannot replace the current selected product as current extent type is incompatible. This product will be added as a new item.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
						selectedIndex = getNextEmptyIndex();
						document.getElementById("nofProducts").value = Number(document.getElementById("nofProducts").value) + 1; //Update the total number of products accordingly.
						hideShowProductMessage();
						var theAction = "new";
					}		
				}
			}
		}	
		if(tooManyProducts == false){					
			//Store all info for the selected product (Format:(prodcode|scale|product|catid|partial|fulldesc|fullname|thescales|multiextent|suppliers|maxsize)							
			//--Data type.	
			document.varform.data.value = tempArray[0]; 
			//--Scale 
			document.varform.scale.value = tempArray[1];			
			//--Full product name
			document.varform.dataDescript.value = tempArray[2];
			//--The coverage available
			document.varform.availibility.value = tempArray[4];
			//--The full data description 
			document.varform.fullDataDesc.value = tempArray[5];	
			//--Full product name 
			document.varform.fullDataName.value = tempArray[6];											
			//--Available Scales
			document.varform.thescales.value = tempArray[7];
			//--Is multi extent product
			document.varform.ismultiextent.value = tempArray[8];			
			//--Has Data suppliers
			document.varform.suppliers.value = tempArray[9];		
			//--Product type (custom or fixed)
			document.varform.productoption.value = tempArray[11];
			//Define if not available extents should show
			if(document.varform.availibility.value != ""){		
				getNA("yes");
			}else{									//Clear existing Not Available extents
				getNA("no");
			}
			if((tempArray1[0] == "new") || (tempArray1[0] == "reorder")){												//Add a new product or replace an existing one
				
				//Clear previously stored info
				clearSelectedProductInfo(selectedIndex);
				
				//Show the selected product in list of selcted products
				document.getElementById("Product " + selectedIndex + "container").style.display = "block";		//Show layer to display selected product info
				if(tempArray[2] != tempArray[6]){
					var descToPrint = tempArray[2] + ": " + tempArray[6];
				}else{
					var descToPrint = tempArray[2];
				}
				//If a Groundsure or multi supplier product - need to show link for further info
				if((tempArray[0].indexOf("GS") == 0) && (tempArray[0].indexOf("GS1") == -1)){				
					document.getElementById("furtherInfo" + selectedIndex).innerHTML = "<a href='javascript:showFurtherInfo(\"gs\"," + selectedIndex + ");'>Click to show required extra info.</a>";	
					document.getElementById("furtherInfo" + selectedIndex).style.display = "block";
				}else if((tempArray[0] == "NULL_AERIAL") || (tempArray[0] == "NULL_HEIGHT")){
					document.getElementById("furtherInfo" + selectedIndex).innerHTML = "<a href='javascript:showFurtherInfo(\"suppliers\"," + selectedIndex + ");'>Click to show data suppliers</a>";
					document.getElementById("furtherInfo" + selectedIndex).style.display = "block";
				}else if (document.varform.suppliers.value == "yes"){
					document.getElementById("furtherInfo" + selectedIndex).innerHTML = "<a href='javascript:showFurtherInfo(\"mastermap\"," + selectedIndex + ");'>Add Aerial/Height?</a>";
					document.getElementById("furtherInfo" + selectedIndex).style.display = "block";
				}else{
					document.getElementById("furtherInfo" + selectedIndex).innerHTML = "&nbsp;";
					document.getElementById("furtherInfo" + selectedIndex).style.display = "none";
				}																		
				document.getElementById("product" + selectedIndex + "content").innerHTML = "<p style='font-weight:bold;font-size:12px;color:#24318D;'>" + descToPrint + "</p>";
				document.getElementById("data" + selectedIndex).value = tempArray[0];
				document.getElementById("datadesc" + selectedIndex).value = tempArray[2];
				document.getElementById("scale" + selectedIndex).value = tempArray[1];
				document.getElementById("maxsize" + selectedIndex).value = tempArray[10];
				document.getElementById("fulldataname" + selectedIndex).value = descToPrint;
				document.getElementById("hassuppliers" + selectedIndex).value = tempArray[9];	
										
				//Update the avaialable scales
				//Empty the scales combo box
				var noCurrentOptions = eval("document.frmSelected.theScales" + selectedIndex + ".options.length");
				for(var m=noCurrentOptions; m >= 0; m--){
					eval("document.frmSelected.theScales" + selectedIndex + ".options[m] = null");
				}
				noCurrentOptions = 0;			
				if( document.varform.scale.value != "-99"){
					document.getElementById("theScales" + selectedIndex).disabled = false;
					//Default scale of the data
					var theItemLabel = "1:" + document.varform.scale.value;
					var theItemValue = document.varform.scale.value;
					eval("document.frmSelected.theScales" + selectedIndex + ".options[noCurrentOptions]=new Option(theItemLabel,theItemValue)");	
					noCurrentOptions += 1;			
					if(document.varform.thescales.value != ""){								//No scales - set as the specified																	//Alternate scales defined - set default as the specified and add to drop down list
						var theScalesArray = new Array();
						theScalesArray = document.varform.thescales.value.split(",");
						//Add new scales values
						for(var m=0; m < theScalesArray.length; m++){
							if(theScalesArray[m] !=  document.varform.scale.value){
								var theItemLabel = "1:" + theScalesArray[m];
								eval("document.frmSelected.theScales" + selectedIndex + ".options[noCurrentOptions]=new Option(theItemLabel,theScalesArray[m])");
								noCurrentOptions += 1;
							}
						}
					}
				}else{
					document.getElementById("theScales" + selectedIndex).disabled = true;
					var theItemLabel = "N/A";
					var theItemValue = document.varform.scale.value;
					eval("document.frmSelected.theScales" + selectedIndex + ".options[noCurrentOptions]=new Option(theItemLabel,theItemValue)");
				}
				//Check if we need to apply the drawn extent to this product automatically (ie extent drawn and the first product now being choosen)
				var applyCurrentDrawnExtent = false;
				if((getSelectedProductIndex() == -1) && (getNumExtents() == 1)){					
					applyCurrentDrawnExtent = true;
				}
				//Ensure this radio button is selected
				for (var i=0; i < document.frmSelected.selectedproducts.length; i++){	
					if(Number(document.frmSelected.selectedproducts[i].value) == selectedIndex){
						document.frmSelected.selectedproducts[i].checked = true;		
						break;	
					}
				}	
				//If selected product is changed need to update the price (providing an extent is associated)
				if(theAction == "change"){
					if(document.getElementById("extent" + selectedIndex).value != ""){
						updatePrice(selectedIndex);
					}
				}else if(applyCurrentDrawnExtent){     //Apply the existing drawn extent to this product
					applyExtentToSelected(selectedIndex,"Extent 1",1);
				}
			}					
			//Retrieve supplier info if necessary
			if((document.varform.suppliers.value != "no") && (document.varform.suppliers.value != "")){
				//Set event for collapse of info										
				//$('zchmOut').addEvent('click', function(e){
				//	e.stop();
				//	zchm.slideOut();
				//});	
				if(document.varform.data.value.substring(0,4) == "OSMM"){			
					/*if(tempArray1[0] == "selected"){
						document.getElementById("productsAvailable").innerHTML = "<div id='supplierinfoAerial_layer'></div><div id='supplierinfoHeight_layer'></div>";
						getOverlaySupplierInfo("aerial",true);
						getOverlaySupplierInfo("height",true);
					}else{
						getOverlaySupplierInfo("aerial",false);
						getOverlaySupplierInfo("height",false);
					}*/
				}else{	
					if(tempArray1[0] == "selected"){
						zchm.slideIn();
					//	getSupplierInfo(true);		//Ensure area for results are shown	
					//}else if(tempArray1[0] == "new"){
						//getSupplierInfo(false);
					}
				}
			}											
		}		
		//If re-showing a product from the user's account -draw the extent now	
		if(tempArray1[0] == "reorder"){			
			//Recreate any extents or associated annotation
			if(storedHasUserShapes != ""){				//Redraw any passed user annotations (redraw the passed map extent when all retrieved)
				getUserShapes(storedHasUserShapes,storedShapesFrom);
			}else if(storedPassedExtent != ""){			//Redraw passed map extent
				if(tempArray[0].toLowerCase().indexOf("gs1") == 0){ 				//Multi-extent (Map packs) (ADD OS MAP PACKS!!!!)
					//Get the centoid of the passed extent with which to define the multi-map extents	
					var tempExtentArray = storedPassedExtent.split(",");
					for(c=0;c < tempExtentArray.length;c++){
						var XYArray = tempExtentArray[c].split(" ");
						if(c==0){
							var extentblx = Number(XYArray[0]);	
							var extentbly = Number(XYArray[1]);
							var extenttrx = Number(XYArray[0]);	
							var extenttry = Number(XYArray[1]);
						}else{
							if(Number(XYArray[0]) < extentblx){extentblx = Number(XYArray[0])}
							if(Number(XYArray[0]) > extenttrx){extenttrx = Number(XYArray[0])}
							if(Number(XYArray[1]) < extentbly){extentbly = Number(XYArray[1])}
							if(Number(XYArray[1]) > extenttry){extenttry = Number(XYArray[1])}
						}
					}
					var theCentreX = extentblx + ((extenttrx - extentblx)/2);
					var theCentreY = extentbly + ((extenttry - extentbly)/2);
					var theCaptureShape = String(theCentreX) + " " + String(theCentreY);
					defineFixedMapExtents(theCaptureShape,"reshow");
				}else if(tempArray[0].toLowerCase().indexOf("gs2") != 0){ 			//Standard polygon extent
					if(document.varform.extentinput.value == "paper"){
						//Set the passed scale and show in the list of scales as selected
						document.getElementById("theScales" + selectedIndex).value = storedSelectedScale;
						mapScale = storedSelectedScale;
						//Draw the extent	
						drawPaperDataExtent(0,0,mapScale,storedPassedExtent,true);
					}else{
						drawDataExtent(storedPassedExtent,"poly");
					}
				}else{																//Groundsure point extent
					drawDataExtent(storedPassedExtent,"point");
				}
				//Need to ensure passed Groundsure info is stored with the order
				if((tempArray[0].toLowerCase().indexOf("gs2") != -1) || (tempArray[0].toLowerCase().indexOf("gs3") != -1)){
					storeGSInfo2(storedGSInfoString);
				}
			}	
		}
		//Get index for selected prodct
		if(tempArray1[0] == "selected"){
			selectedIndex = getSelectedProductIndex();
		}
		//Show the selected product as highlighed and activate the drop down extent selecter for the selected product item
		for(i=1; i < 6;i++){
			if(i == selectedIndex){
				document.getElementById("selectedextent" + String(i)).disabled = false;
				/*document.getElementById("selectedrow" + String(i) + "_1").style.backgroundColor = "#CCCCCC";
				document.getElementById("selectedrow" + String(i) + "_2").style.backgroundColor = "#CCCCCC";
				document.getElementById("selectedrow" + String(i) + "_3").style.backgroundColor = "#CCCCCC";
				
				border-style:solid;
				border-color:red;
				border:3px dashed #ED0489;*/
				document.getElementById("Product " + String(i) + "container").style.border = "3px dashed #ED0489";
				document.getElementById("Product " + String(i) + "container").style.backgroundColor = "#CCCCCC";
				
			}else{
				if(document.getElementById("selectedextent" + String(i)) != null){
					document.getElementById("selectedextent" + String(i)).disabled = true;
					/*document.getElementById("selectedrow" + String(i) + "_1").style.backgroundColor = "#FFFFFF";
					document.getElementById("selectedrow" + String(i) + "_2").style.backgroundColor = "#FFFFFF";
					document.getElementById("selectedrow" + String(i) + "_3").style.backgroundColor = "#FFFFFF";*/
					document.getElementById("Product " + String(i) + "container").style.border = "none";
					document.getElementById("Product " + String(i) + "container").style.backgroundColor = "#FFFFFF";
						
				}
			}
		}
		//Hide product options if we are not retrieving suppliers
		//if((document.varform.suppliers.value == "no") && (document.varform.suppliers.value = "")){
		//if(applyCurrentDrawnExtent == false){		
		if((applyCurrentDrawnExtent == false) && (document.varform.suppliers.value == "no") && (document.varform.suppliers.value = "")){	
			if(document.varform.data.value == "NULL_AERIAL"){
				cancelSupplierReq("aerial");
			}else if(document.varform.data.value == "NULL_HEIGHT"){
				cancelSupplierReq("height");
			}else if(document.varform.suppliers.value == "yes"){
				cancelSupplierReq("aerial");
				cancelSupplierReq("height");
			}					
		}
		//Show the define extent area
		displayTools("Define");
		showTools("Define");
		toolbox.slideIn();
		callCufon();		
		//Need to cancel lookups if just simply selecting the product
		if((tempArray1[0] != "reorder") && (document.varform.suppliers.value != "no") && (document.varform.suppliers.value != "")){
			if(document.varform.data.value == "NULL_AERIAL"){
				cancelSupplierReq("aerial");
			}else if(document.varform.data.value == "NULL_HEIGHT"){
				cancelSupplierReq("height");
			}else if(document.varform.suppliers.value == "yes"){
				cancelSupplierReq("aerial");
				cancelSupplierReq("height");
			}
		}	
		//Esure zchm content is hidden
		zchm.slideOut();		
		//Retrieve supplier info if necessary (if product has been selected in the user selected list)
		if((document.varform.suppliers.value != "no") && (document.varform.suppliers.value != "") && (tempArray1[0] == "selected")){	
			if(document.varform.data.value.substring(0,4) == "OSMM"){
				/*if(tempArray1[0] == "selected"){
					document.getElementById("productsAvailable").innerHTML = "<div id='supplierinfoAerial_layer'></div><div id='supplierinfoHeight_layer'></div>";
					getOverlaySupplierInfo("aerial",true);
					getOverlaySupplierInfo("height",true);
				}else{
					getOverlaySupplierInfo("aerial",false);
					getOverlaySupplierInfo("height",false);
				}*/
			}else{	
				if(tempArray1[0] == "selected"){
					//zchm.slideIn();
					getSupplierInfo(true);		//Ensure area for results are shown	
				//}else if(tempArray1[0] == "new"){
					//getSupplierInfo(false);
				}
			}
		}else{
		/*
			//Show the define extent area
			displayTools("Define");
			showTools("Define");
		
			//document.getElementById("toolsArea").style.height = "100px";
			toolbox.slideIn();
		
		*/
		}			
		//Destroy the fixed product overlay layer if one exists
		if(fixedLayer != null){
			fixedLayer.destroy();
			fixedLayer = null;
		}	
		//Show the fixed points as an overlay
		if(document.varform.productoption.value == "fixed"){
			showFixedProducts();
		}
		callCufon();					
	}	
}
//*******************
function clearSelectedProductInfo(selectedIndex){
	//document.getElementById("extentcoords" + selectedIndex).value = "";
	//document.getElementById("extent" + selectedIndex).value = "";
	document.getElementById("data" + selectedIndex).value = "";
	document.getElementById("datadesc" + selectedIndex).value = "";
	document.getElementById("mmpercents" + selectedIndex).value = "";
	document.getElementById("orderprice" + selectedIndex).value = "";			
	document.getElementById("layersPrice" + selectedIndex).value = "";
	document.getElementById("scale" + selectedIndex).value = "";
	document.getElementById("maxsize" + selectedIndex).value = "";
	document.getElementById("gsinfo" + selectedIndex).value = "";
	document.getElementById("productLayers" + selectedIndex).value = "";
	document.getElementById("papersize" + selectedIndex).value = "";
	document.getElementById("fulldataname" + selectedIndex).value = "";
	document.getElementById("mmlicenceused" + selectedIndex).value = "";
	document.getElementById("combinationinfo" + selectedIndex).value = "";
	document.getElementById("fixselected" + selectedIndex).value = "";
	document.getElementById("layeroverlays" + selectedIndex).value = "";
	document.getElementById("calcprice" + selectedIndex).value = "";
	document.getElementById("layersPrices" + selectedIndex).value = "";							          
}
//*******************Show the further info (GS, suppliers) from the i link in selcted products
function showFurtherInfo(theType,thePassedSelected){
	//Check that the info clicked is for the selected product
	var selectedProductIndex = getSelectedProductIndex();
	if(thePassedSelected == selectedProductIndex){
		if(theType == "gs"){					//Grounsure info
			showGSInfo();
		}else if(theType == "suppliers"){		//Height aerial suppliers
			getSupplierInfo(true);
		}else if(theType == "mastermap"){		//Mastermap overlay suppliers
			showHeightAerialSuppliers('mastermap');
		}else if(theType == "mastermapaerial"){		//Mastermap overlay suppliers
			showHeightAerialSuppliers('mastermapaerial');
		}else if(theType == "mastermapheight"){		//Mastermap overlay suppliers
			showHeightAerialSuppliers('mastermapheight');
		}
	}else{
		showDialog('Warning','Please ensure this item is selected before retrieving info.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}	
}
//*******************Get the index of the selected product
function getSelectedProductIndex(){
	var selectedProductIndex = -1;
	for (var i=0; i < document.frmSelected.selectedproducts.length; i++){	
		if(document.frmSelected.selectedproducts[i].checked){	
			selectedProductIndex = (i+1);	
			break;	
		}
	}
	return selectedProductIndex;
}
//*******************Get the indices of products with the passed extent id
function getAssociatedExtents(thePassedExtentID){
	var selectedProductIndices = [];
	for (var i=0; i < document.frmSelected.selectedproducts.length; i++){
		if(document.getElementById("extent" + String(i+1)).value == thePassedExtentID){
			selectedProductIndices.push(String(i+1));	
		}
	}
	return selectedProductIndices;
}
//************************Delete the selected product
function delSelectedProduct(selectedIndex){
	//Clear out the stored info for this product
	document.getElementById("product" + selectedIndex + "content").innerHTML = "";
	document.getElementById("prodmessage" + selectedIndex).innerHTML = "";
	document.getElementById("showdataprice" + selectedIndex).innerHTML = "<p>&pound; **.**</p>";
	document.getElementById("data" + selectedIndex).value = "";
	document.getElementById("datadesc" + selectedIndex).value = "";
	document.getElementById("scale" + selectedIndex).value = "";
	document.getElementById("maxsize" + selectedIndex).value =  "";
	document.getElementById("mmpercents" + selectedIndex).value =  "";
	document.getElementById("layersPrice" + selectedIndex).value =  "";
	document.getElementById("productLayers" + selectedIndex).value =  "";
	document.getElementById("orderprice" + selectedIndex).value =  "";
	document.getElementById("calcprice" + selectedIndex).value =  "";
	document.getElementById("gsinfo" + selectedIndex).value =  "";
	document.getElementById("extent" + selectedIndex).value =  "";
	document.getElementById("prod" +  selectedIndex + "_0").selected = true;
	document.getElementById("selectedextent" + selectedIndex).style.backgroundColor = "#FFFFFF";
	//Clear out general stored info
	document.varform.data.value = ""; 
	document.varform.scale.value = "";			
	document.varform.dataDescript.value = "";
	document.varform.availibility.value = "";
	document.varform.fullDataDesc.value = "";	
	document.varform.fullDataName.value = "";											
	document.varform.thescales.value = "";
	document.varform.ismultiextent.value = "";			
	document.varform.suppliers.value = "";		
	document.varform.productoption.value = "";		
	//Destroy the fixed product overlay layer if one exists
	if(fixedLayer != null){
		fixedLayer.destroy();
		fixedLayer = null;
	}
	//Clear existing Not Available extents
	getNA("no");
	//Unselect it
	for (var i=0; i < document.frmSelected.selectedproducts.length; i++){	
		if(i == (selectedIndex-1)){
			document.frmSelected.selectedproducts[i].checked = false;		
			break;	
		}
	}
	//Hide layer to display selected product info
	document.getElementById("Product " + selectedIndex + "container").style.display = "none";	
	//Update number of selected products
	document.getElementById("nofProducts").value = (Number(document.getElementById("nofProducts").value)-1);
	hideShowProductMessage();
	updateTotalPrice();					//Update the total price to add the new product price	
}
//************************Get the next empty space in the list of selected in which to add the newly selected product
function getNextEmptyIndex(){
	var newIndex = -1;
	for (var i=0; i < document.frmSelected.selectedproducts.length; i++){
		if(document.getElementById("data" + (i+1)).value == ""){	
			newIndex = (i+1);		
			break;	
		}
	}
	return newIndex;
}
//************************Hide or show selected product message
function hideShowProductMessage(){
	if(Number(document.getElementById("nofProducts").value) == 0){		//Nothing selected show message
		document.getElementById("selectedProductsList").style.display = "block";
	}else{																	//Hide message
		document.getElementById("selectedProductsList").style.display = "none";
	}
}

//-------------------------------------------------------------------------ADDING PRODUCT TO BASKET

//************************Checks everything defined corectly for selected products before adding to the shopping basket
function preBasketCheck(startIndex){	
	if(document.varform.cid.value != ""){							//Check user is logged in	
		if(startIndex == 0){
			productCnt = 0;
			okToAddToBasket = true;
		}
		var showSuppliersChoice = false;
		var promptToCombine = false;
		if(startIndex >=  document.frmSelected.selectedproducts.length){		//Everything should be OK add to basket
			addToBasket();
		}else{
			for (var i=startIndex; i < document.frmSelected.selectedproducts.length; i++){
				document.getElementById("combinationinfo" + String(i+1)).value = "";				//Clear combination info
				if(document.getElementById("data" + String(i+1)).value != ""){
					productCnt += 1;
					//Check extent defined or  items selected for a fixed product
					if((document.getElementById("extent" + String(i+1)).value == "") && (document.getElementById("fixselected" + String(i+1)).value == "")){
						showDialog('Warning','Please assign an extent or select items for order item "' + String(i+1) + '"<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
						okToAddToBasket = false;
						break;			
					}
					//Check order price
					if(okToAddToBasket){	
						if((document.getElementById("orderprice" + String(i+1)).value == "") || (document.getElementById("orderprice" + String(i+1)).value == "0")){
							showDialog('Warning','Please retrieve price for order item "' + String(productCnt) + '" by clicking the<br/><strong>"Get Price"</strong> link in Your Selected Products.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
							okToAddToBasket = false;
							//Auto retrieve price!!! (!!!Need to ensure we have retrieved this before adding to basket)
							//if(document.getElementById("extent" + String(i+1)).value != ""){
							//	retrievePrice("show",String(i+1),document.getElementById("extent" + String(i+1)).value);
							//}			
						}else if(document.getElementById("orderprice" + String(i+1)).value == "offline"){
							showDialog('Warning','There are order items that are too big to order on-line. These will not be added to the basket.<br/>Please contact CentreMaps direct for large data requirements.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
							productCnt -= 1;		
						}
					}
					//Check Groundsure info. if appropriate
					if(okToAddToBasket){
						if(document.getElementById("data" + String(i+1)).value.toLowerCase().indexOf("gs3") == 0){ 
							okToAddToBasket = checkSiteReportOptions(String(i+1));
						}
					}
					//Check if supplier defined (if necessary)
					if(okToAddToBasket){
						if(((document.getElementById("hassuppliers" + String(i+1)).value != "") && (document.getElementById("hassuppliers" + String(i+1)).value != "no")) && (document.getElementById("productLayers" + String(i+1)).value == "")){
							if(document.getElementById("data" + String(i+1)).value.indexOf("NULL") == 0){	
								showDialog('Warning','No data options selected for order item "' + String(productCnt) + '". Please wait for choices to be displayed.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
								okToAddToBasket = false;
								getSupplierInfo(true);
								break;
							}else{			 //- NOT NECESSARY
							//	okToAddToBasket = false;	
							//	showSuppliersChoice = true;
							//	break;			
							}
						}
						
						if(((document.getElementById("hassuppliers" + String(i+1)).value != "") && (document.getElementById("hassuppliers" + String(i+1)).value != "no")) && (document.getElementById("productLayers" + String(i+1)).value != "")){
							if((document.getElementById("data" + String(i+1)).value == "OSMM_PRINT") || (document.getElementById("data" + String(i+1)).value.indexOf("OSMMBW") != -1) || (document.getElementById("data" + String(i+1)).value.indexOf("OSMMBF") != -1)) {
								promptToCombine = true;
								okToAddToBasket = false;
								break
							}
						}							
					}	
				}
			}
			//The product can have supplier layers adding (prompt it the user wants to do this) - NOT NECESSARY
			//if(showSuppliersChoice){
			//	var dialogContent = "Only base mapping selected for order item '" + String(i+1) + "'.<br/>Click 'Continue' to proceed with the order or click 'Cancel' to view optional data layers.<br/><input type='button' value='Continue' id='contButton' onclick='preBasketCheckPromptAction(\"continue\"," + String(i) + ");'>  <input type='button' value='Cancel' id='cancelButton' onclick='preBasketCheckPromptAction(\"cancel\"," + String(i) + ");' >"
			//	showDialog('',dialogContent,'prompt');
			//}
			//This product can be combined (prompt to do so)
			if(promptToCombine){
				var dialogContent = "Combine all elements of order item '" + String(productCnt) + "' into a single PDF?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='combinePromptAction(\"yes\"," + String(i) + ");'>  <input type='button' value='No' id='noButton' onclick='combinePromptAction(\"no\"," + String(i) + ");' >"
				showDialog('',dialogContent,'prompt');
			}
			
			//**********Everything OK and we have products - can add to the basket 													
			if((okToAddToBasket) && (productCnt > 0)){
				addToBasket();
			}
		}		
	}else{
		var dialogContent = "Please ensure you are registered and logged in before preceeding with the order.<br/><br/><input type='button' value='Register' id='regButton' onclick='openLoginPreBasket(\"register\");');'>  <input type='button' value='Login' id='loginButton' onclick='openLoginPreBasket(\"login\");' >";
		showDialog('',dialogContent,'prompt');
	}		
}
//************************Show login or register if user not logged in pre going to basket
function openLoginPreBasket(theType){
	if(theType == "login"){
		showLogin();
	}else if(theType == "register"){
		showHideRegister("show");
	}
	hideDialog();
}
//************************Action after prompting to add supplier layers to a product (ie create a combined product)  				//NOT CALLED
function preBasketCheckPromptAction(theActon,startIndex){		
	hideDialog();
	if(theActon == "cancel"){					//Show data suppliers - don't proceed any further							
		showHeightAerialSuppliers('mastermap');
	}else if(theActon == "continue"){			//Continue checking slected products pre adding to basket
		okToAddToBasket = true;
		preBasketCheck(startIndex+1)
	}
}
//************************Action after prompting to add combine MasterMap prints into one file
function combinePromptAction(theActon,startIndex){		
	hideDialog();
	if(theActon == "yes"){					//Show data suppliers - don't proceed any further							
		document.getElementById("combinationinfo" + String(startIndex+1)).value = "yes";
	}
	okToAddToBasket = true;
	preBasketCheck(startIndex+1);	
}

//************************Adds all selected products to temp store of selected product and open shopping basket page.
function addToBasket(){
	//Check if any of the products intersect a MasterMap licensed area
	for (var i=0; i < document.frmSelected.selectedproducts.length; i++){
		document.getElementById("mmlicenceused" + String(i+1)).value = "";			//Clear stored licence for each product
		if((document.getElementById("data" + String(i+1)).value != "") && (document.getElementById("extent" + String(i+1)).value != "")){
			if(document.getElementById("data" + String(i+1)).value.substring(0,4) == "OSMM"){
				//Get the product geometry
				var theExtentID = document.getElementById("extent" + String(i+1)).value;
				var theExtentFeatureToTest = getFeatureExtentByID(theExtentID);					
				//See which licensed area it intersects with
				for(p=0; p < licensedLayer.features.length;p++){
					var centreIntersection = licensedLayer.features[p].geometry.intersects(theExtentFeatureToTest.geometry);
					if(centreIntersection){	 
						//Store in the licence with the order info in a hidden field
						document.getElementById("mmlicenceused" + String(i+1)).value = licensedLayer.features[p].attributes.name;
						break;
					}
				}
			}
		}
	}
	

	var canCombine = false;	
	/*Check if products can be combined (TO MODIFY)
	combineInfo = new Array();
	combineItems = new Array();							
	var combineProducts = false;
	combCnt = -1;
	if(productCnt >1){
		for (var i=0; i < document.frmSelected.selectedproducts.length; i++){
			var testData = document.getElementById("data" + String(i+1)).value;
			var testExtent = document.getElementById("extent" + String(i+1)).value;
			var testLayers = document.getElementById("productLayers" + String(i+1)).value;	
			if(testData != ""){
				if((testData == "OSMM") || (testData == "NULL_AERIAL") || (testData == "NULL_HEIGHT")){			//These products can be combined
					if((testData == "OSMM") && (testLayers != "")){			//The MasterMap product already has layers defined - no need to prompt to combine
						//Do nothing
					}else{
						//User has a product that can be combinded
						combCnt++;
						combineInfo[combCnt] = document.getElementById("datadesc" + String(i+1)).value;
						combineItems[combCnt] = String(i+1);
						var thisHasCombination = false;
						for (var i2=(i+1); i2 < document.frmSelected.selectedproducts.length; i2++){
							var testData2 = document.getElementById("data" + String(i2+1)).value;
							var testExtent2 = document.getElementById("extent" + String(i2+1)).value;
							var testLayers2 = document.getElementById("productLayers" + String(i2+1)).value;
							if(testData2 != ""){			
								if(((testData2 == "OSMM") || (testData2 == "NULL_AERIAL") || (testData2 == "NULL_HEIGHT")) && (testExtent == testExtent2)){		//Have the same extents									
									if(testData2 != testData){			//They are a different product
										if((testData2 == "OSMM") && (testLayers2 != "")){			//The MasterMap product already has layers defined - no need to prompt to combine
											//Do nothing
										}else{
											canCombine = true;				//Flag that there are products that can be combined
											thisHasCombination = true;
											combineInfo[combCnt] += "," + document.getElementById("datadesc" + String(i2+1)).value;
											combineItems[combCnt] += "," +String(i2+1);
										}
									}	
								}
							}
						}
						if(thisHasCombination == false){
							combCnt--;
						}
					}
				}
			}
		}
	}*/
	

	if(annoLayer.features.length > 0){								//There are anno features
		//Reset all associated orderitem numbers stored with the annotation
		for(p=0; p < annoLayer.features.length;p++){
			var theAnnoFeature = annoLayer.features[p];
			if(theAnnoFeature.attributes.id != null){		//Ensure it is valid annotation (and not a selection handle or error point)
				 theAnnoFeature.attributes.orderitems = "";
				 annoLayer.redraw();
			}	
		}		
		//For each selected product check what anno intersect with the defined extent 			
		for (var i=0; i < Number(document.varform.nofProducts.value); i++){
			var selectedData = document.getElementById("data" + (i+1)).value;
			if((selectedData.toLowerCase().indexOf("gs") == 0) || (document.getElementById("orderprice" + String(i+1)).value == "offline")){ 
				//Ignore if anno not allowed on this product or if not an offline order
				//(ADD OTHER PRODUCTS??!!)	
			}else{
				//Get geometry of the product extent
				var passedExtentID = document.getElementById("extent" + (i+1)).value;
				var theDataExtentFeature = getFeatureExtentByID(passedExtentID);		
				//Check if this intersects any annotation
				for(p=0; p < annoLayer.features.length;p++){
					var theAnnoFeature = annoLayer.features[p];
					if(theAnnoFeature.attributes.id != null){		//Ensure it is valid annotation (and not a selection handle or error point)
						var annoIntersection = theDataExtentFeature.geometry.intersects(theAnnoFeature.geometry);
						if(annoIntersection){						//Apply the selected product index to the anno if intersects 
							if(theAnnoFeature.attributes.orderitems == ""){ 
								theAnnoFeature.attributes.orderitems = String(i+1);
							}else{
								theAnnoFeature.attributes.orderitems = theAnnoFeature.attributes.orderitems + "," + String(i+1);
							}
							annoLayer.redraw();
						}
					}	
				}
				
			}	
		}
		//Check if there are any anno elements not associated with product
		for(p=0; p < annoLayer.features.length;p++){
			var theAnnoFeature = annoLayer.features[p];
			if(theAnnoFeature.attributes.id != null){		//Ensure it is valid annotation (and not a selection handle or error point)
				if(theAnnoFeature.attributes.orderitems == ""){ 
					showDialog('Warning','Please note that there are drawn annotations that are not associated with a data area.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
					break;
				}
			}	
		}				
	}
	//Store on hidden form that is passed to basket
	//Store total number of selected product, the region and basket action ("ADD" if an id is not stored)
	document.frmSelected.toAddToBasket.value = document.varform.nofProducts.value;
	document.frmSelected.regionToPass.value = document.varform.region.value;
	if(document.frmSelected.basketAction.value == ""){
		document.frmSelected.basketAction.value = "ADD";
	}
	//Ensure the extent and if paper size is transferred to the hidden for for submitting
	for (var i=0; i < 5; i++){                                           
		var passedExtentID = document.getElementById("extent" + (i+1)).value;
		var theDataExtentFeature = getFeatureExtentByID(passedExtentID);
		theDataExtentFeature
		if(theDataExtentFeature != null){				
			//If a multi extent product we need to store the large extent in the database - so check if this extent is the small part of a multi extent product
			if(extentLayer2.features.length > 0){	
				for(e=0;e<extentLayer2.features.length;e++){
					if(extentLayer2.features[e].attributes.id == passedExtentID){			//Found a match - write this extent instead
						theDataExtentFeature = extentLayer2.features[e];	
						break;
					}
				}
			}
			document.getElementById("extentcoords" + (i+1)).value = String(theDataExtentFeature.geometry);
			if(theDataExtentFeature.attributes.papersize != null){
				document.getElementById("papersize" + (i+1)).value = theDataExtentFeature.attributes.papersize;
			}else{
				document.getElementById("papersize" + (i+1)).value = "";
			}
		}			
	}			
	/*If can be combined and user wants to (store id of products for each item that are combined)
	document.getElementById("combinationinfo1").value = "";			//Clear exiting info
	document.getElementById("combinationinfo2").value = "";
	document.getElementById("combinationinfo3").value = "";
	document.getElementById("combinationinfo4").value = "";
	document.getElementById("combinationinfo5").value = "";*/
	if(canCombine){				//NOT CALLED
		combineTheProducts("prompt");	
	}else{
		//****************OPEN BASKET PAGE (Get all the currently drawn shapes and add to temp database (tempshapes2) before opening)
		getAllDrawnShapes();  
	}			
}
//************************Action for combining product - prompt to ask, and proceed with the user's choice
function combineTheProducts(combineAction){
	if(combineAction == "prompt"){					//Prompt if products are to be combined
		var combineInfoString = "";
		for (var i2=0; i2 <= combCnt; i2++){
			if(i2 == 0){
				 combineInfoString = combineItems[i2];
			}else{
				combineInfoString =  combineInfoString + " and " + combineItems[i2];
			}	
		}
		var dialogContent = "Products items " + combineInfoString + " can be combined into one product PDF.<br/>Do you want to combine products?<br/><input type='button' value='Yes' id='yesButton' onclick='combineTheProducts(\"combine\");'>  <input type='button' value='No' id='noButton' onclick='combineTheProducts(\"cancel\");' >"
		showDialog('',dialogContent,'prompt');
	}else if(combineAction == "combine"){
		hideDialog();
		for (var i=0; i < document.frmSelected.selectedproducts.length; i++){
			for (var i2=0; i2 < combineItems.length; i2++){
				if((combineItems[i2].indexOf(String(i+1)) != -1) && (combineItems[i2].indexOf(",") != -1)){
					document.getElementById("combinationinfo" + String(i+1)).value = combineItems[i2];
					break;
				}
			}
		}		
		//OPEN BASKET PAGE (Get all the currently drawn shapes and add to temp database (tempshapes2) before opening)
		getAllDrawnShapes();  
	}else if(combineAction == "cancel"){
		hideDialog();
		//OPEN BASKET PAGE (Get all the currently drawn shapes and add to temp database (tempshapes2) before opening)
		getAllDrawnShapes();  
	}
}

//-------------------------------------------------------------------------FIXED PRODUCTS

//************************
function showFixedProducts(){		
	var theViewExtent = map.getExtent().toBBOX();
	var theViewExtentArray = theViewExtent.split(",");	
	var newViewWidth = (theViewExtentArray[2] - theViewExtentArray[0]);
	var newViewHeight = (theViewExtentArray[3] - theViewExtentArray[1]);					
	if ((newViewWidth > fixedThresholdSize) && (newViewHeight > fixedThresholdSize)){
		showDialog('Warning','Please zoom in to view extent of your selected product on the map.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{
		var qstring = "extent=" + theViewExtent + "&classcode=bm&buffer=" + fixedBufferDistance;		
		//Add the Fixed layer
		var fixedScriptPath = "http://shop.centremapslive.co.uk/ver2/getFixed.php?"; 			//Location of script to retrieve the fixed points	
		var fixedScript = fixedScriptPath + qstring;
		fixedLayer = new OpenLayers.Layer.GML("TESTFIXED", fixedScript, { format: OpenLayers.Format.Text});
		map.addLayer(fixedLayer);
			
		var visibleLayers = new Array();
		var visLayCnt = -1;
		for(c=0; c < fixedCheckBoxes.length; c++){
			if(fixedLayerArray[c] != null){
				visLayCnt += 1;				
				visibleLayers[visLayCnt] = fixedLayerArray[c];
			}			
		}	
		visLayCnt += 1;
		visibleLayers[visLayCnt] = markerLayer;										//Ensure the maker layer is still selectable
		visLayCnt += 1;
		visibleLayers[visLayCnt] = fixedLayer;										//Ensure the fixed product layer is still selectable		
		//Add a select feature control for the visible Fixed point layers
		selFeatureControl = new OpenLayers.Control.SelectFeature(visibleLayers); 
		map.addControl(selFeatureControl);
		selFeatureControl.activate();
		//Define selection events on the fixed layer	
		fixedLayer.events.on({
		'featureselected': onFixedBuyFeatureSelect,
		'featureunselected': onFixedBuyFeatureUnselect
		});					
	}
}
//************************
function onFixedBuyFeatureSelect(evt) {
    feature = evt.feature; 	
	var passedDescription = feature.attributes.description;
	var featureDescArray = passedDescription.split("~");    //0=description, 1=feature ID	
    popup = new OpenLayers.Popup.FramedCloud("featurePopup",
                             feature.geometry.getBounds().getCenterLonLat(),
                             new OpenLayers.Size(100,100),
                             "<h3>"+feature.attributes.title + "</h3>" +
                             featureDescArray[0] + "<br/><a href='javascript:selectFixed(\"" + featureDescArray[1] + "\",\"select\");'>Select this item</a>" + "<br/><a href='javascript:selectFixed(\"" + featureDescArray[1] + "\",\"unselect\");'>Unselect this item</a>",
                             null, true, onPopupClose);
    popup.autosize = true;
	popup.panMapIfOutOfView = false;
	feature.popup = popup;		
    popup.feature = feature;
    map.addPopup(popup);
	callCufon();		
}
//************************
function onFixedBuyFeatureUnselect(evt) {
    feature = evt.feature;
    if (feature.popup) {
        popup.feature = null;
        map.removePopup(feature.popup);
        feature.popup.destroy();
        feature.popup = null;
    }
}
//************************
function selectFixed(fixedID,theAction){
	if(theAction == "select"){
		var currentValues = document.getElementById("fixselected" + selectedIndex).value;
		if(currentValues == ""){	
			document.getElementById("fixselected" + selectedIndex).value = fixedID;
		}else{
			//Check if already added
			var addThisFixed = true;
			var currentValuesArray = currentValues.split(",");
			for(c=0; c < currentValuesArray.length;c++){				
				if(currentValuesArray[c] == fixedID){
					addThisFixed = false;
					break; 
				}
			}
			if(addThisFixed){
				document.getElementById("fixselected" + selectedIndex).value = currentValues + "," + fixedID;
			}
		}
	}else if(theAction == "unselect"){
		var currentValues = document.getElementById("fixselected" + selectedIndex).value;
		if(currentValues != ""){	
			//Check if already added
			var newFixedIDList = "";
			var currentValuesArray = currentValues.split(",");
			for(c=0; c < currentValuesArray.length;c++){				
				if(currentValuesArray[c] != fixedID){
					if(newFixedIDList == ""){
						newFixedIDList = currentValuesArray[c];
					}else{
						newFixedIDList = newFixedIDList + "," + currentValuesArray[c];
					}
				}
			}		
			document.getElementById("fixselected" + selectedIndex).value = newFixedIDList;
		}
	}	
	//Adjust the price
	adjustFixedPrice();	
}
//************************
function adjustFixedPrice(){
	var selectedFixedsString = document.getElementById("fixselected" + selectedIndex).value
	if(selectedFixedsString != ""){
		var selectedFixedsArray = selectedFixedsString.split(",");	
		var qstring = "prodcode=" + document.varform.data.value + "&total=" + selectedFixedsArray.length;		
		var getFixedPriceReq = new ajaxObject('getFixedPrice.php', handleGetFixedPriceResponse);
		getFixedPriceReq.update(qstring,'POST');
	}
}
//************************
function handleGetFixedPriceResponse(responseText, responseStatus){
	if(responseStatus == 200){				
		if(responseText != ""){																//Check data returned (See "getProduct.php" for format)			
			var thePrice = formatPrice(Math.round(Number(responseText)*100)/100);
			document.getElementById("orderprice"+selectedIndex).value = thePrice;				
			document.getElementById("showdataprice"+selectedIndex).innerHTML = "<p>" + thePrice + "</p>"; 
		}else{
			showDialog('Error','There has been an error retrieving the price for this data.<br/>Please try again or contact CentreMaps.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');	
			document.getElementById("orderprice"+selectedIndex).value = "0";
			document.getElementById("showdataprice"+selectedIndex).innerHTML = "<p>&pound; **.**<br/><a href='javascript:adjustFixedPrice();' style='font-size:11px;'>Get Price</a></p>"; 		
		}
		updateTotalPrice();					//Update the total price to reflect the changes
	}
}

//************************
function selectMultiFixedPoints(theSelectedFeatureGeometry){
	if(fixedLayer != null){
		if(fixedLayer.features.length > 0){				//If no features assumed to be Rural (686)
			var theViewCentreGeom = new OpenLayers.Geometry.Point(map.getCenter().lon, map.getCenter().lat);				//Get the view centre as a geometry
			var intersectionIDlist = [];
			for(p=0; p < fixedLayer.features.length;p++){
				var fixedIntersection = theSelectedFeatureGeometry.intersects(fixedLayer.features[p].geometry);
				if(fixedIntersection){														//***Centre intersects an urban or moorland extent 
					var passedDescription = fixedLayer.features[p].attributes.description;
					var featureDescArray = passedDescription.split("~");    //0=description, 1=feature ID
					intersectionIDlist.push(featureDescArray[1]);
				}
			}
		}
		var newFixedIDList = "";		
		var currentValues = document.getElementById("fixselected" + selectedIndex).value;
		if(currentValues != ""){	
			var currentValuesArray = currentValues.split(",");
			for(c=0; c < intersectionIDlist.length;c++){
				var fixedIsFound = false
				for(c1=0; c1 < currentValuesArray.length;c1++){				
					if(currentValuesArray[c1] == intersectionIDlist[c]){
						fixedIsFound = true;
						break;
					}
				}
				if(fixedIsFound == false){
					newFixedIDList = newFixedIDList + "," + intersectionIDlist[c];
				}
			}		
			document.getElementById("fixselected" + selectedIndex).value = currentValues + newFixedIDList;
		}else{
			document.getElementById("fixselected" + selectedIndex).value = intersectionIDlist.join(",");
		}		
		//Adjust the price
		adjustFixedPrice();
	}
	drawCapturePolyControl.deactivate();				//Deactivate the poly capture tool			
}

//-------------------------------------------------End of file.
