/*--------------------------------------------------------------
dataextents.js
Javascript for CentremapsLive map interface
Data extent drawing scripts and associated
Lovell Johns Ltd
Jan 2010
----------------------------------------------------------------*/

//-------------------------------------------------------------------------GLOBALS
var theGSOption = "";											//Current GS type "full" needs full info showing, "simple" needs address and postcode showing
var productExtentOpts = new Array(5);
var paperExtentLabel = ""										//Extent Info	
var areaToPrint = "";
var centreXY = "";
var dataExtentExtent = "";

//-------------------------------------------------------------------------DEFINING DATA EXTENT SCRIPTS
//************************Get the sheet size (standard sizes)
function getSheetSize(mapCentreX,mapCentreY,theIndex,passedMapScale){
	canHideIt = true; 								//Can now hide toolbox on mouse over map (if not already set)
	deactivateDrawingControls();					//Deactivate any existing controls
	if(theIndex.indexOf("a") != -1){				//Called when updating scale - use the passed paper size
		var paperSize = theIndex;	
	}else{
		var paperSizeObj = document.getElementById("sheetSize" + theIndex);
		var paperString = paperSizeObj.options[paperSizeObj.selectedIndex].value;
		var paperValues = paperString.split(",");
		var paperSize = paperValues[0];
		var paperDesc = paperValues[1];
	}

	//Get the selectedd sheet size
	if(paperSize.toLowerCase().indexOf("a5p") != -1){			//98x113mm
		xSizeMetres = 0.098; 
		ySizeMetres = 0.113; 
	}else if(paperSize.toLowerCase().indexOf("a5l") != -1){		//113x98mm
		xSizeMetres = 0.113; 
		ySizeMetres = 0.098; 
	}else if(paperSize.toLowerCase().indexOf("a4p") != -1){		//160x200mm
		xSizeMetres = 0.160; 
		ySizeMetres = 0.200;  
	}else if(paperSize.toLowerCase().indexOf("a4l") != -1){		//200x160mm
		xSizeMetres = 0.200;  
		ySizeMetres = 0.160;   
	}else if(paperSize.toLowerCase().indexOf("a3p") != -1){		//247x323mm
		xSizeMetres = 0.247; 
		ySizeMetres = 0.323;  
	}else if(paperSize.toLowerCase().indexOf("a3l") != -1){		//323x247mm
		xSizeMetres = 0.323; 
		ySizeMetres = 0.247;   
	}else if(paperSize.toLowerCase().indexOf("a2p") != -1){		//370x497mm
		xSizeMetres = 0.370;   
		ySizeMetres = 0.497;  
	}else if(paperSize.toLowerCase().indexOf("a2l") != -1){		//497x370mm
		xSizeMetres = 0.497;  
		ySizeMetres = 0.370;   
	}else if(paperSize.toLowerCase().indexOf("a1p") != -1){		//544x743mm
		xSizeMetres = 0.544;   
		ySizeMetres = 0.743;  
	}else if(paperSize.toLowerCase().indexOf("a1l") != -1){		//743x544mm
		xSizeMetres = 0.743;  
		ySizeMetres = 0.544;   
	}else if(paperSize.toLowerCase().indexOf("2a0p") != -1){	//1138x1583mm
		xSizeMetres = 1.138;  
		ySizeMetres = 1.583;  
	}else if(paperSize.toLowerCase().indexOf("2a0l") != -1){	//1583x1138mm
		xSizeMetres = 1.583;  
		ySizeMetres = 1.138;   
	}else if(paperSize.toLowerCase().indexOf("a0p") != -1){		//790x1091mm
		xSizeMetres = 0.790;  
		ySizeMetres = 1.091; 	
	}else if(paperSize.toLowerCase().indexOf("a0l") != -1){		//1091x790mm		
		xSizeMetres = 1.091;   
		ySizeMetres = 0.790;   
	}else if(paperSize.toLowerCase().indexOf("a4v") != -1){		//160x160mm
		xSizeMetres = 0.160;  
		ySizeMetres = 0.160; 
	}	
	if((paperSize != "#") || (passedMapScale != "")){
		document.varform.papersize.value = paperSize;
		document.varform.extentType.value = "scaled";			//Store in hidden
		document.varform.extentinput.value = "paper";							
		if(passedMapScale == ""){
			var mapScale = Number(document.getElementById("paperscales").value);
			//Update the selcted product list with the set scale
			var selectedProdIndex = getSelectedProductIndex();
			document.getElementById("theScales" + selectedProdIndex).value = mapScale;
			document.getElementById("scale" + selectedProdIndex).value = mapScale;	
		}else{	
			var mapScale = Number(passedMapScale);
		}	
		if(mapScale == -99){ 
			showDialog('Warning','The data product choosen has no scale.<br/>Please define extent by specifying a real world size or drawing the required extent.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			document.sheetSizeform.sheetSize.selectedIndex = 0;
		}else if (mapScale == 0){	
			showDialog('Warning','Please ensure the data product choosen before defining the extent.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			document.sheetSizeform.sheetSize.selectedIndex = 0;
		}else if((isNaN(mapScale) == false) && (mapScale != 0) && (xSizeMetres != 0) && (ySizeMetres != 0)){		
			//Set the size of extent in metres at the specified scale.
			mapSizeX = xSizeMetres * mapScale;
			mapSizeY = ySizeMetres * mapScale;				
			//Define coordinates of the extent
			if((mapCentreX == "") || (mapCentreY == "")){		//Map centre not passed called from dropdown list extent centred over map centre			
				var extentCoords = "";
			}else{
				var extentblx = Number(mapCentreX) - (mapSizeX/2);	
				var extentbly = Number(mapCentreY) - (mapSizeY/2);
				var extenttrx = Number(mapCentreX) + (mapSizeX/2);	
				var extenttry = Number(mapCentreY) + (mapSizeY/2);
				var extentCoords = String(extentblx) + " " + String(extentbly) + "," + String(extentblx) + " " + String(extenttry) + "," + String(extenttrx) + " " + String(extenttry) + "," + String(extenttrx) + " " + String(extentbly) + "," + String(extentblx) + " " + String(extentbly);
			}				
			//Draw the map extent		
			drawPaperDataExtent(xSizeMetres,ySizeMetres,mapScale,extentCoords,true);			
		}
	}	
}
//************************Update the sheet size from drop down choices
function updateSheetSize(theIndex){
	updatingExtent = theIndex;
	applyToSelected = false;			//Ensure when updating the extent it is not applied to the selected product (As this extent may not be tied to a product)
	resizeFeatureID = "Extent " + theIndex;
	if(resizeFeatureID != ""){
		/*Get the scale this sheet size is defined at
		for (var i=0; i < 5; i++){	
			if(document.getElementById("extent" + String(i+1)).value == resizeFeatureID){
				theMapScale = document.getElementById("theScales" + String(i+1)).value;	
				break;	
			}
		}*/
		var theCurrentFeature = getFeatureExtentByID(resizeFeatureID);
		theMapScale = theCurrentFeature.attributes.datascale;
		
		if(theCurrentFeature != null){
			if(theCurrentFeature.attributes.papersize != null){						//If a paper extent resize
				//Get current centrepoint of the extent
				var centreX = String(Math.round(theCurrentFeature.geometry.getCentroid().x)); 
				var centreY = String(Math.round(theCurrentFeature.geometry.getCentroid().y));
				//Get rid of the current extent
				clearExtentPreResize(resizeFeatureID);
				//Redraw the new extent
				getSheetSize(centreX,centreY,theIndex,theMapScale);
			}
		}
	}
}
//************************Get the sheet size (User defined sizes)
function getUserDefinedSize(){
	canHideIt = true; 								//Can now hide toolbox on mouse over map (if not already set)
	deactivateDrawingControls();					//Deactivate any existing controls	
	//Get user entered x-y.
	var userX = Number(document.mappingSizeform.userxmm.value);			
	var userY = Number(document.mappingSizeform.userymm.value);		
	//Transform from entered units to millimetres if necessary	
	if(document.mappingSizeform.printedunit.value == "cm"){	
		userX = userX * 10;
		userY = userY * 10;
	}else if(document.mappingSizeform.printedunit.value == "in"){
		userX = userX * 25.4;
		userY = userY * 25.4;
	}				
	if((userX == 0) || (userY == 0)){
		showDialog('Warning','Please enter a valid map size.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else if((isNaN(userX)) || (isNaN(userY))){
		showDialog('Warning','Please enter a valid map size.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{		
		xSizeMetres = userX / 1000; 
		ySizeMetres = userY / 1000; 
		var mapScale = Number(document.getElementById("userscales").value);	
		document.varform.extentType.value = "scaled";
		document.varform.extentinput.value = "user";
		document.varform.papersize.value = "";			
		if(mapScale == -99){ 
			showDialog('Warning','The data product choosen has no scale.<br/>Please define extent by specifying a real world size or drawing the required extent.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			document.sheetSizeform.sheetSize.selectedIndex = 0;
		}else if (mapScale == 0){	
			showDialog('Warning','Please ensure the data product choosen before defining the extent.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			document.sheetSizeform.sheetSize.selectedIndex = 0;
		}else if((isNaN(mapScale) == false) && (mapScale != 0) && (xSizeMetres != 0) && (ySizeMetres != 0)){		
			//Set the size of extent in metres at the specified scale.
			mapSizeX = xSizeMetres * mapScale;
			mapSizeY = ySizeMetres * mapScale;				
			//Define coordinates of the extent			
			var mapCentreX = map.getCenter().lon;	
			var mapCentreY = map.getCenter().lat;			
			var extentblx = mapCentreX - (mapSizeX/2);	
			var extentbly = mapCentreY - (mapSizeY/2);
			var extenttrx = mapCentreX + (mapSizeX/2);	
			var extenttry = mapCentreY + (mapSizeY/2);
			var extentCoords = String(extentblx) + " " + String(extentbly) + "," + String(extentblx) + " " + String(extenttry) + "," + String(extenttrx) + " " + String(extenttry) + "," + String(extenttrx) + " " + String(extentbly) + "," + String(extentblx) + " " + String(extentbly);
			//Draw the map extent
			drawDataExtent(extentCoords,"poly");						
		}
	}	
}
//************************Get the ground size (User defined sizes)
function getGroundSize(){
	canHideIt = true; 								//Can now hide toolbox on mouse over map (if not already set)
	deactivateDrawingControls();					//Deactivate any existing controls
	//Get user entered x-y.
	var userX = Number(document.groundSizeform.userxm.value);			
	var userY = Number(document.groundSizeform.userym.value);						
	//Transform from entered units to metres if necessary	
	if(document.groundSizeform.sizeunit.value == "km"){	
		userX = userX * 1000;
		userY = userY * 1000;
	}else if(document.groundSizeform.sizeunit.value == "mi"){
		userX = userX * 1609;
		userY = userY * 1609;
	}			
	if((userX == 0) || (userY == 0)){
		showDialog('Warning','Please enter a valid ground size.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else if((isNaN(userX)) || (isNaN(userY))){
		showDialog('Warning','Please enter a valid ground size.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{			
		xSizeMetres = userX; 
		ySizeMetres = userY; 
		document.varform.extentType.value = "ground";
		document.varform.extentinput.value = "ground";
		document.varform.papersize.value = "";		
		//Define coordinates of the extent			
		var mapCentreX = map.getCenter().lon;	
		var mapCentreY = map.getCenter().lat;			
		var extentblx = mapCentreX - (xSizeMetres/2);	
		var extentbly = mapCentreY - (ySizeMetres/2);
		var extenttrx = mapCentreX + (xSizeMetres/2);	
		var extenttry = mapCentreY + (ySizeMetres/2);
		var extentCoords = String(extentblx) + " " + String(extentbly) + "," + String(extentblx) + " " + String(extenttry) + "," + String(extenttrx) + " " + String(extenttry) + "," + String(extenttrx) + " " + String(extentbly) + "," + String(extentblx) + " " + String(extentbly);
		//Draw the map extent
		drawDataExtent(extentCoords,"poly");
	}
}
//************************Get the user extent size (User defined extent)
function getUserExtent(){
	canHideIt = true; 								//Can now hide toolbox on mouse over map (if not already set)
	deactivateDrawingControls();					//Deactivate any existing controls	
	//Get user entered x-y.
	var userBLX = Number(document.extentSizeform.userblx.value);			
	var userBLY = Number(document.extentSizeform.userbly.value);
	var userTRX = Number(document.extentSizeform.usertrx.value);			
	var userTRY = Number(document.extentSizeform.usertry.value);		
	if((isNaN(userBLX)) || (isNaN(userBLY)) || (isNaN(userTRX)) || (isNaN(userTRY))){
		showDialog('Warning','Please enter valid coordinates to specify extent.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{	
		if(((userTRX - userBLX) == 0) ||((userTRY - userBLY) == 0)){
			showDialog('Warning','Please enter valid coordinates to specify extent.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}else{		
			document.varform.extentType.value = "extent";
			document.varform.extentinput.value = "extent";
			document.varform.papersize.value = "";
			//Define coordinates of the extent			
			xSizeMetres = (userTRX - userBLX); 
			ySizeMetres = (userTRY - userBLY); 
			var userExtentCentreX = userBLX + ((userTRX - userBLX)/2);
			var userExtentCentreY = userBLY + ((userTRY - userBLY)/2);						
			var extentblx = userExtentCentreX - (xSizeMetres/2);	
			var extentbly = userExtentCentreY - (ySizeMetres/2);
			var extenttrx = userExtentCentreX + (xSizeMetres/2);	
			var extenttry = userExtentCentreY + (ySizeMetres/2);
			var extentCoords = String(extentblx) + " " + String(extentbly) + "," + String(extentblx) + " " + String(extenttry) + "," + String(extenttrx) + " " + String(extenttry) + "," + String(extenttrx) + " " + String(extentbly) + "," + String(extentblx) + " " + String(extentbly);
			//Draw the map extent
			drawDataExtent(extentCoords,"poly");
		}
	}
}
//************************Get the Radius extent
function getRadius(){
	canHideIt = true; 								//Can now hide toolbox on mouse over map (if not already set)
	deactivateDrawingControls();					//Deactivate any existing controls
	//Get the input
	var theRad = Number(document.radiusSizeform.userradius.value);
	var theCX = map.getCenter().lon;	
	var theCY = map.getCenter().lat;		
	//Transform from entered units to metres if necessary	
	if(document.radiusSizeform.radiusunit.value == "km"){	
		theRad = theRad * 1000;
	}else if(document.radiusSizeform.radiusunit.value == "mi"){
		theRad = theRad * 1609;
	}
	if(theRad > 0){
		var userOk = true;
	}else{
		var userOk = false;
		showDialog('Warning','Please select a radius value.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}	
	if(userOk){	
		//Define the coordinate string
		var coordList = "";   
		var strXtemp; 
		var strYtemp;
		for (i=0;i<72;i++){
			strXtemp = String((Math.round(((Math.cos((i*5)*(Math.PI/180)))*theRad)))  + theCX);
			strYtemp = String((Math.round(((Math.sin((i*5)*(Math.PI/180)))*theRad)))  + theCY);
			coordList += strXtemp + " " + strYtemp + ",";
		}			
		strXtemp = String((Math.round(((Math.cos(0))*theRad))) + theCX);
		strYtemp = String((Math.round(((Math.sin(0))*theRad))) + theCY);
		coordList += strXtemp + " " + strYtemp;						
		//Store info on hidden and reload the page	
		document.varform.extentType.value = "ground";
		document.varform.papersize.value = "";
		document.varform.extentinput.value = "radius";				//Draw by specifying centre and radius	
		//Draw the map extent
		drawDataExtent(coordList,"poly");		
	}
}
//************************Get the coordinate extent
function getCoordinateExtent(){
	canHideIt = true; 								//Can now hide toolbox on mouse over map (if not already set)
	deactivateDrawingControls();					//Deactivate any existing controls
	var theCoordinateString = document.coordExtentform.usercoords.value;
	theCoordinateString = theCoordinateString.replace(/ /g,"");
	document.coordExtentform.usercoords.value = theCoordinateString;		
	var userCoordsOK = false;
	if(theCoordinateString != ""){
		//Check the string is OK
		userCoordsOK = true;
		var userCoordArray = new Array();
		userCoordArray =  theCoordinateString.split(",");
		var nofCoords = userCoordArray.length;
		if(((nofCoords % 2) != 0) || (nofCoords < 6)){
			showDialog('Warning','Coordinate string not defined correctly. Incorrect number of coordinates.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			userCoordsOK = false;
		}else{
			//Check the coordinate string is closed
			if((userCoordArray[0] != userCoordArray[nofCoords-2]) && (userCoordArray[1] != userCoordArray[nofCoords-1])){
				userCoordArray[nofCoords] = userCoordArray[0];
				userCoordArray[nofCoords+1] = userCoordArray[1];	
			}
		}
		if(userCoordsOK){
			//Define new centre point	
			var extentCoords = "";
			for(var n=0;n<userCoordArray.length;n++){			
				if(((n+1)%2) != 0){
					var theX = Number(userCoordArray[n]);
					extentCoords += String(theX) + " ";
				}else{
					var theY = Number(userCoordArray[n]);
					if(n == (userCoordArray.length-1)){
						extentCoords += String(theY);
					}else{
						extentCoords += String(theY) + ",";	
					}
				}				
				if(n==0){
					geomMinX = theX;
					geomMaxX = theX;
				}else if(n==1){
					geomMinY = theY;	
					geomMaxY = theY;
				}else{
					if(theX < geomMinX){
						geomMinX = theX;
					}		
					if(theX > geomMaxX){
						geomMaxX = theX;
					}		
					if(theY < geomMinY){
						geomMinY = theY;
					}		
					if(theY > geomMaxY){
						geomMaxY = theY;
					}
				}						
			}			
			//Get the new centre x-y coordinate and the bounding box x-y
			var theX = String(geomMinX + ((geomMaxX - geomMinX) /2));
			var theY = String((geomMinY + ((geomMaxY - geomMinY) /2)));
			var theExtentX = geomMaxX - geomMinX;
			var theExtentY = geomMaxY - geomMinY;					
			//Store info on hidden and reload the page
			document.varform.extentinput.value = "draw";
			document.varform.extentType.value = "ground";
			document.varform.papersize.value = "";
			//Draw the map extent
			drawDataExtent(extentCoords,"poly");
		}		
	}else{
		showDialog('Warning','Coordinate string not defined correctly.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}
}

//-------------------------------------------------------------------------GENERAL EXTENT SCRIPTS

//****************Response from getting drawing tools
function getToolsResponse(responseText, responseStatus){
	if(responseStatus == 200){
		document.getElementById("toolsDefineContent").innerHTML = responseText;		//Show  extent drawing tools  content
		getExtentInfo();															//Update the extent info content	
	}
}
//***********************Retreive and show the data extent info
function getExtentInfo(){
	//Get all extent features added over the map
	for(e=0;e < extentLayer.features.length;e++){
		var theCurrentFeature = extentLayer.features[e];  	
		if(theCurrentFeature != null){
			var theExtentID = theCurrentFeature.attributes.id
			if(theExtentID != null){
				//Make layer visible that show extent info
				document.getElementById(theExtentID+"container").style.display = "block";		
				//Define what editing tools can be shown  based on the geometry
				if(String(theCurrentFeature.geometry).indexOf("POINT") == 0){								//Is point only allow move
					document.getElementById(theExtentID+"reshape").style.display = "none";
					document.getElementById(theExtentID+"resize").style.display = "none";
					document.getElementById(theExtentID+"change").style.display = "none";
				}else{
					var isMulti = false;
					var isPaper = false;
					var isFixed = false;
					for(p=0;p < extentLayer2.features.length;p++){												
						if(extentLayer2.features[p].attributes.id == theExtentID){
							isMulti = true;
							break;
						}			
					}
					for(p=0;p < extentLayer.features.length;p++){												
						if(extentLayer.features[p].attributes.id == theExtentID){
							if(extentLayer.features[p].attributes.papersize != null){
								isPaper = true;								
							}
							break;
						}			
					}
					if(isMulti == false){
						for(p=0;p < extentLayer.features.length;p++){												
							if(extentLayer.features[p].attributes.id == theExtentID){
								if(extentLayer.features[p].attributes.isfixed != null){
									isFixed = true;								
								}
								break;
							}			
						}
					}
					if((isMulti) || (isPaper) || (isFixed)){						//***Is a fixed, multi or paper extent
						document.getElementById(theExtentID+"reshape").style.display = "none";
						document.getElementById(theExtentID+"resize").style.display = "none";
						document.getElementById(theExtentID+"move").style.display = "block";
					}else{															//***Standard extent
						document.getElementById(theExtentID+"reshape").style.display = "block";
						document.getElementById(theExtentID+"resize").style.display = "block";
						document.getElementById(theExtentID+"move").style.display = "none";
					}
					if(isPaper){
						document.getElementById(theExtentID+"change").style.display = "block";
					}else{
						document.getElementById(theExtentID+"change").style.display = "none";
					}				
				}
			}
		}
	}
}
//****************Show the relevant extent drawing area (defineprintarea,definegroundarea,defineradiusarea,defineshapearea,definecoordsarea,definecurrentarea) ie the initial choices
function showExtentTools(turnOn){
	var theOptions = new Array("defineprintarea","definegroundarea","defineradiusarea","definecoordsarea","historicContainer","ospackContainer","gssiteContainer","gsareaContainer");
	var theOptions1 = new Array("paper","ground","radius","extent","historic","ospack","gssite","gsarea");				
	canHideIt = false; 															//Can now hide toolbox on mouse over map (if not already set)
	adjustMapExtentOpacity("full");												//Ensure map extents are not knocked back.		
	//Hide intial choices and show the specific choices
	document.getElementById("initialAreaChoices").style.display = "none";
	document.getElementById("specificAreaChoices").style.display = "block";		
	if(getSelectedProductIndex() == -1){	
		//Show the select product message and ensure all extent drawing options are hidden
		document.getElementById("noprodmessage").style.display = "block";
		for (var n=0;n<(theOptions.length);n++){
			var theObj = document.getElementById(theOptions[n]);	
			showExtentOption("");				
			theObj.style.display = "none";										
		}	
	}else{	
		document.getElementById("noprodmessage").style.display = "none";
		//Make available the specific options								
		for (var n=0;n<(theOptions.length);n++){
			var theObj = document.getElementById(theOptions[n]);	
			if(turnOn == theOptions[n]){
				theObj.style.display = "block";
				showExtentOption(theOptions1[n]);				//Ensure the specific option area is shown			
			}else{
				theObj.style.display = "none";										
			}
		}	
	}
}
//****************Shows the initial data area choices
function hideExtentTools(){
	//Show intial choices and hide the specific choices
	document.getElementById("initialAreaChoices").style.display = "block";
	document.getElementById("specificAreaChoices").style.display = "none";
	//Ensure the 'existing extents' option is shown
	if(getNumExtents() > 0){
		document.getElementById("currentExtentsOpt").style.display = "block";
	}else{
		document.getElementById("currentExtentsOpt").style.display = "none";
	}
}
//****************Show the relevat extent drawing option (paper size, shape extract etc..)
function showExtentOption(turnOn){									
	var theOptions = new Array("paper","ground","mapping","radius","extent","gssite","gsarea","historic","ospack");			//Map Extent drawing option elements		
	for (var n=0;n<(theOptions.length);n++){
		var theObj = document.getElementById(theOptions[n]);	
		if(turnOn == theOptions[n]){						
			theObj.style.display = "block";	
			//Ensure check box is checked
			for (var i=0; i < document.extOptionsform.extenttype.length; i++){	
				if(document.extOptionsform.extenttype[i].value == theOptions[n]){	
					document.extOptionsform.extenttype[i].checked = true;	
					break;	
				}
			}			
		}else{
			theObj.style.display = "none";										
		}
	}
}
//****************Get the number of map extents defined
function getNumExtents(){
	if(extentLayer.features.length == 0){
		nofExtents = 0;
	}else{
		var nofExtents = 0;
		for(e=0;e<extentLayer.features.length;e++){						//Get the highest ID (will be number of features)
			var theFeatureID = extentLayer.features[e].attributes.id;
			if(theFeatureID != null){
				var testID = theFeatureID.substring(6,theFeatureID.length);	
			}
			if(Number(testID) > nofExtents){
				nofExtents = Number(testID);
			}
		}
	}			
	return nofExtents;				
}
//***********************Get the current selected user data extent
function getTheSelectedExtent(){
	var theSelectedFeature = null;
	for(p=0; p < extentLayer.selectedFeatures.length;p++){
		theSelectedFeature = extentLayer.selectedFeatures[p];	
	}
	return theSelectedFeature;
}
//***********************Get the current data extent geometry by passed id
function getExtentGeomByID(thePassedExtentID){
	var extentGeom = null;
	for(p=0; p < extentLayer.features.length;p++){
		if(thePassedExtentID == extentLayer.features[p].attributes.id){
			extentGeom = extentLayer.features[p].geometry;
			break;
		}
	}
	return extentGeom;
}
//***********************Retreive and show the data extent info (area and centre x-y)
function showExtentInfo(theCurrentExtentID){
	updateExtentInfo(theCurrentExtentID);
	Tip(paperExtentLabel + "Area: " + areaToPrint + "<br/>Centre (x,y): " + centreXY + "<br/>Extent (width,height): " + dataExtentExtent);
}
function updateExtentInfo(theCurrentExtentID){
	//Get the feature
	var theCurrentFeature = getFeatureExtentByID(theCurrentExtentID);	
	if(theCurrentFeature != null){
		var selObj = document.getElementById(theCurrentExtentID+"info");
		if(selObj != null){	
			if(String(theCurrentFeature.geometry).indexOf("POINT") == 0){
				var extentType = "point";
				areaToPrint = "N/A";
				dataExtentExtent = "N/A";
			}else{
				var extentType = "poly";
				var extentArea = theCurrentFeature.geometry.getArea();   //getGeodesicArea();  //;   
				
				//var testProj =  new OpenLayers.Projection("EPSG:27700")
				  
				//var extentArea = theCurrentFeature.geometry.getGeodesicArea(testProj);  //;  
				//alert(extentArea)
								
				var extentAreaKM = extentArea / 1000000;
				if(extentArea < 1){
					areaToPrint = String(Math.round((extentArea / 10000)* 1000)/1000) + " ha"; 
				}else if(extentArea < 1000){
					areaToPrint = String(Math.round(extentArea* 1000)/1000) + " m<sup><font size='-2'>2</font></sup>";	
					
				}else{				
					areaToPrint = String(Math.round(extentAreaKM*1000)/1000) + " km<sup><font size='-2'>2</font></sup>";
				}				
				//dataExtentExtent = theCurrentFeature.geometry.getBounds().toBBOX();
				dataExtentExtent = theCurrentFeature.geometry.getBounds().getWidth() + "," + theCurrentFeature.geometry.getBounds().getHeight();			
			}
			centreXY = String(Math.round(theCurrentFeature.geometry.getCentroid().x)) + "," + String(Math.round(theCurrentFeature.geometry.getCentroid().y)) + " m.";
			//Check if extent is a paper size (read attribute from the extent)
			if(theCurrentFeature.attributes.papersize != null){
				paperExtentLabel = "Sheet Size: " + theCurrentFeature.attributes.papersize + "<br/>";
			}else{
				paperExtentLabel = "";
			}
		}
	}
}
//****************Hide the extent info area
function hideExtentInfo(theCurrentExtentID){
	var selObj = document.getElementById(theCurrentExtentID+"info");
	if(selObj != null){	
		selObj.style.display = "none";
	}
}
//****************Get the extent element by the passed ID
function getFeatureExtentByID(passedExtentID){
	var theCurrentFeature = null;
	for(e=0;e<extentLayer.features.length;e++){
		if(extentLayer.features[e].attributes.id == passedExtentID){
			theCurrentFeature = extentLayer.features[e];
			break;
		}
	}
	return theCurrentFeature;
}
//****************Apply the current extent to the selected product
function applyExtent(passedExtentID,selectedProductIndex){
	//No selected product has been passed - check if there is one
	if(selectedProductIndex == -1){	
		selectedProductIndex = getSelectedProductIndex();
	}
	//Get the selcted product
	if(selectedProductIndex != -1){
		if(passedExtentID == "Extent 0"){					//Clearing extent
			document.getElementById("extent" + selectedProductIndex).value = "";
			document.getElementById("selectedextent" + selectedProductIndex).style.backgroundColor = "#FFFFFF";
			document.getElementById("prodmessage" + selectedProductIndex).innerHTML = "";		//Clear any product messages
			updatePrice(selectedProductIndex);	
		}else{
			//Get this extent type
			var theCurrentFeature = getFeatureExtentByID(passedExtentID);
			if(String(theCurrentFeature.geometry).indexOf("POINT") == 0){
				var theExtentType = "point";
			}else{
				var theExtentType = "poly";	
			}
			//Get currently selected data product and if multi extent - used to check if the extent can be applied to the selected product
			var selectedData = document.varform.data.value.toLowerCase();
			var isMultiExtent = document.varform.ismultiextent.value.toLowerCase();
			var isOK = checkProductExtentAgree(selectedData,isMultiExtent,theExtentType,passedExtentID);	
			//Check if a paper extent 
			var isPaperExtent = false;
			if(theCurrentFeature.attributes.papersize != null){
				if(theCurrentFeature.attributes.papersize != ""){
					isPaperExtent = true;
				}
			}
			if(isOK){
				if(isPaperExtent){		//is paper - check if we can allow it to be applied to another product
					isOK = false;
					var updateThePrintScale = false;
					var scaleOfThisProduct = Number(document.getElementById("scale" + selectedProductIndex).value);			//Get the scale of the product trying to add this extent to
					if(scaleOfThisProduct == Number(theCurrentFeature.attributes.datascale)){		//Sacle agree allow applying
						isOK = true;
					}else{				//Check if the print scale can be adjusted to agree with the extent applying
						document.getElementById("theScales" + selectedProductIndex)
						var scaleFound = false;
						var noCurrentOptions = eval("document.frmSelected.theScales" + selectedIndex + ".options.length");
						for(var m=0; m < noCurrentOptions; m++){
							if(Number(eval("document.frmSelected.theScales" + selectedIndex + ".options[m].value")) == Number(theCurrentFeature.attributes.datascale)){
								scaleFound = true;
								break;
							}	
						}
						if(scaleFound){
							updateThePrintScale = true;
							isOK = true;
						}
					}
				}
				if(isOK){
					//Change the print scale to the scale of the applied scale
					if(updateThePrintScale){
						document.getElementById("scale" + selectedProductIndex).value = theCurrentFeature.attributes.datascale;	
						document.getElementById("theScales" + selectedProductIndex).value = theCurrentFeature.attributes.datascale;
					}
					document.getElementById("extent" + selectedProductIndex).value = passedExtentID;
					//Update the extent background colour
					var extentNo = passedExtentID.substring((passedExtentID.length-1),passedExtentID.length);
					document.getElementById("selectedextent" + selectedProductIndex).style.backgroundColor = extentColours[extentNo-1];
					//Retrieve supplier info if necessary
					if((document.varform.suppliers.value != "no") && (document.varform.suppliers.value != "")){
						document.getElementById("productLayers" + selectedProductIndex).value = "";			//Reset fields
						document.getElementById("layersPrice" + selectedProductIndex).value = "0";
						if(document.varform.data.value.substring(0,4) == "OSMM"){			//MAY NOT BE JUST OSMM???!!
							document.getElementById("productsAvailable").innerHTML = "<div id='supplierinfoAerial_layer'></div><div id='supplierinfoHeight_layer'></div>";
						}else{		
							getSupplierInfo(true);		//Ensure area for results are shown	
						}
						document.getElementById("showdataprice"+selectedProductIndex).innerHTML = "<p>&pound; **.**<br/><a href='javascript:retrievePrice(\"show\",\"" + selectedProductIndex + "\",\"" + passedExtentID + "\");' style='font-size:11px;'>Get Price</a></p>"; 	//Clear the price				
					}else{
						updatePrice(selectedProductIndex);									//Update the price
					}
				}else{
					//Reset the combo and show warning
					var theBackCol = document.getElementById("selectedextent" + selectedProductIndex).style.backgroundColor;
					var extentCombo = document.getElementById("selectedextent" + selectedProductIndex);
					if(theBackCol == "rgb(237, 4, 137)"){
						extentCombo.options[1].selected = true;				
					}else if(theBackCol == "rgb(0, 0, 0)"){
						extentCombo.options[2].selected = true;	
					}else if(theBackCol == "rgb(255, 0, 0)"){
						extentCombo.options[3].selected = true;
					}else if(theBackCol == "rgb(0, 255, 0)"){
						extentCombo.options[4].selected = true;
					}else if(theBackCol == "rgb(0, 0, 255)"){
						extentCombo.options[5].selected = true;
					}else if(theBackCol == "rgb(255, 255, 255)"){
						extentCombo.options[0].selected = true;
					}
					showDialog('Warning','Please ensure the scale is 1:' + theCurrentFeature.attributes.datascale +' before applying a scaled map extent to this product.<br/>Alternatively define the extent under the "Define Area" tab.<br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				}
			}else{
				//Reset the combo and show warning
				var theBackCol = document.getElementById("selectedextent" + selectedProductIndex).style.backgroundColor;
				var extentCombo = document.getElementById("selectedextent" + selectedProductIndex);
				if(theBackCol == "rgb(237, 4, 137)"){
					extentCombo.options[1].selected = true;				
				}else if(theBackCol == "rgb(0, 0, 0)"){
					extentCombo.options[2].selected = true;	
				}else if(theBackCol == "rgb(255, 0, 0)"){
					extentCombo.options[3].selected = true;
				}else if(theBackCol == "rgb(0, 255, 0)"){
					extentCombo.options[4].selected = true;
				}else if(theBackCol == "rgb(0, 0, 255)"){
					extentCombo.options[5].selected = true;
				}else if(theBackCol == "rgb(255, 255, 255)"){
					extentCombo.options[0].selected = true;
				}
				showDialog('Warning','This extent is incompatible with the selected product.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');			
			}
		}
	}else{
		showDialog('Warning','Please ensure a product is selected.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}
}
//****************Adds the currently drawn extent to the dropdown list (so it can be applied to a product)
function addExtentToList(extentNo){	
	for(r=0; r < 5; r++){
		document.getElementById("selectedextent" + String(r+1)).appendChild(productExtentOpts[r][Number(extentNo)-1]);	
	}		
}
//****************Apply the extent when user chooses extent from dropdown list
function extentListChange(selObj,selectedProductIndex){
	var passedExtentID = selObj.value;
	applyExtent(passedExtentID,selectedProductIndex);
}
//****************Apply the extent when user chooses "Apply" from the current data extent list
function applyNewExtent(passedExtentID){	
	var selectedProductIndex = getSelectedProductIndex();	
	applyExtent(passedExtentID,selectedProductIndex);
}
//****************Store and then remove all the extent options from the drop down list (Cant just hide them cus IE is shit)
function removeAllExtentOptions(){
	//Store all the extent options to choose for each selected product and then remove (These can then be added to the dropdown list when the user add an extent)
	for(r=0; r < 5; r++){ 
		//Store the oprion elements in an array
		productExtentOpts[r] = new Array(5)
		productExtentOpts[r][0] = document.getElementById("prod" + String(r+1) + "_1");
		productExtentOpts[r][1] = document.getElementById("prod" + String(r+1) + "_2");
		productExtentOpts[r][2] = document.getElementById("prod" + String(r+1) + "_3");
		productExtentOpts[r][3] = document.getElementById("prod" + String(r+1) + "_4");
		productExtentOpts[r][4] = document.getElementById("prod" + String(r+1) + "_5");
		//Remove from the parent
		document.getElementById("selectedextent" + String(r+1)).removeChild(document.getElementById("prod" + String(r+1) + "_1"));
		document.getElementById("selectedextent" + String(r+1)).removeChild(document.getElementById("prod" + String(r+1) + "_2"));
		document.getElementById("selectedextent" + String(r+1)).removeChild(document.getElementById("prod" + String(r+1) + "_3"));
		document.getElementById("selectedextent" + String(r+1)).removeChild(document.getElementById("prod" + String(r+1) + "_4"));
		document.getElementById("selectedextent" + String(r+1)).removeChild(document.getElementById("prod" + String(r+1) + "_5"));
	}
}
//****************Apply the draw extent to the selected product (called after extent drawn)
function applyExtentToSelected(selectedProductIndex,extentId,extentNo){	
	if(selectedProductIndex == -1){	
		selectedProductIndex = getSelectedProductIndex();
	}
	if(selectedProductIndex != -1){
		hideDialog();
		document.getElementById("extent" + selectedProductIndex).value = extentId;  //Store extent ID						
		//Show this extent selected for the currently selected product
		document.getElementById("prod" + selectedProductIndex + "_" + extentNo).selected = true;
		document.getElementById("selectedextent" + selectedProductIndex).style.backgroundColor = extentColours[extentNo-1];							
		//Retrieve supplier info if necessary
		if((document.varform.suppliers.value != "no") && (document.varform.suppliers.value != "")){								
			if(document.varform.data.value.substring(0,4) == "OSMM"){			//MAY NOT BE JUST OSMM???!!
				document.getElementById("productsAvailable").innerHTML = "<div id='supplierinfoAerial_layer'></div><div id='supplierinfoHeight_layer'></div>";;
				updatePrice(selectedProductIndex);
			}else{
				//kill any height-aerial lookups
				cancelSupplierReq("aerial");
				cancelSupplierReq("height");
				getSupplierInfo(true);
			}
		}else{
			updatePrice(selectedProductIndex);			
		}
		//Show further GS options			
		if((document.varform.data.value.indexOf("GS") == 0) && (document.varform.data.value.indexOf("GS1") == -1)){
			showGSInfo();
		}
	}
}
//*******************Check if there are any selected products with the passed extent id
function checkIfExtentUsed(thePassedExtentID){
	var extentUsedCnt = 0;
	for (var i=0; i < document.frmSelected.selectedproducts.length; i++){
		if(document.getElementById("extent" + String(i+1)).value == thePassedExtentID){
			extentUsedCnt++;	
		}
	}
	return extentUsedCnt;
}
//****************Call look up to show overlay suppliers for MasterMap
function showHeightAerialSuppliers(theType){
	hideDialog();
	var outputHTMLString = "<div id='supplierinfoAerial_layer'></div><div id='supplierinfoHeight_layer'></div>";				
	document.getElementById("productsAvailable").innerHTML = outputHTMLString;
	zchm.slideIn();
	if(theType == "mastermap"){	
		getOverlaySupplierInfo("aerial",true);
		timerId = setTimeout("getOverlaySupplierInfo('height',true)",5000);	
	}else if(theType == "mastermapaerial"){
		getOverlaySupplierInfo("aerial",true);
	}else if(theType == "mastermapheight"){
		getOverlaySupplierInfo("height",true);
	}
}
//****************Dont show height options - called if user chooses not to show for a MM product. hides dialog and collapses zchm
function dontShowHeightAerialSuppliers(){
	hideDialog();
	zchm.slideOut();
}
//****************Defines if the product agrees with the type of extent (Eg. can't apply site extent to streetview)
function checkProductExtentAgree(selectedData,isMultiExtent,theExtentType,passedExtentID){
	//Define the type of product (ie what extents can it have)
	if(isMultiExtent == "yes"){
		var productType = "multi";     
	}else if(selectedData.toLowerCase().indexOf("gs2") == 0){
		var productType = "point";	
	}else if(selectedData.toLowerCase().indexOf("gs1") == 0){	
		var productType = "fixed";		
	}else{
		var productType = "poly";
	}	
	//Check if the extent is multi extent or fixed size
	if(theExtentType != "point"){
		for(p=0;p < extentLayer2.features.length;p++){												
			if(extentLayer2.features[p].attributes.id == passedExtentID){
				theExtentType = "multi";
				break;
			}			
		}
		if(theExtentType != "multi"){								//Check if a fixed product
			for(p=0;p < extentLayer.features.length;p++){												
				if(extentLayer.features[p].attributes.id == passedExtentID){
					if(extentLayer.features[p].attributes.isfixed != null){
						theExtentType = "fixed";	
					}
					break;
				}			
			}
		}
	}
	//Don't allow fixed or multi extent to be applied or if the types disagree
	if((productType == "fixed") || (theExtentType == "fixed") || (productType == "multi") || (theExtentType == "multi")){
		var isOK = false;
	}else if(productType == theExtentType){
		var isOK = true;
	}else{
		var isOK = false;
	}
	return isOK;
}
//****************Activates for use the selected draw extent tool on the toolbar	
function activateExtentTool(toolType){
	canHideIt = true; 									//Can now hide toolbox on mouse over map (if not already set)	
	deactivateDrawingControls();						//Deactivate any existing controls
	adjustMapExtentOpacity("full");						//Ensure map extents are not knocked back.		
	if(selFeatureControl != null){ 
		selFeatureControl.activate();					//Ensure select feature control active
	}
	var canContinue = true;
	if((toolType=='drawpoly') || (toolType=='drawpoly2') || (toolType=='drawpoint') || (toolType=='selarea1') || (toolType=='selarea3') || (toolType=='historic') || (toolType=='mappack')){
		if(getNumExtents() >= 5){
			showDialog('Warning','A maximum of 5 extents can be drawn.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');	
			canContinue = false;
		}
	}
	if(canContinue){
		//Reset hidden
		document.varform.extentType.value = "";
		document.varform.extentinput.value = "";
		document.varform.papersize.value = "";	
		if(toolType=='drawpoly'){
			drawPolyControl.activate();
		}else if(toolType=='drawpoly2'){
			drawPolyControl.activate();
			document.getElementById(toolType).src = "images/" + toolType + "_on.png";					
		}else if(toolType=='drawpoint'){
			drawPointControl.activate();	
		}else if(toolType=='edit'){
			if(selFeatureControl != null){ 
				selFeatureControl.deactivate();
			}
			modifyControl.mode = OpenLayers.Control.ModifyFeature.RESHAPE;			
			modifyControl.activate();
		}else if(toolType=='resize'){
			if(selFeatureControl != null){ 
				selFeatureControl.deactivate();
			}	
			modifyControl.mode = OpenLayers.Control.ModifyFeature.DRAG;
			modifyControl.mode |= OpenLayers.Control.ModifyFeature.RESIZE;
		    modifyControl.mode |= OpenLayers.Control.ModifyFeature.RESHAPE;
			modifyControl.activate();	 	
		}else if(toolType=='move'){
			if(selFeatureControl != null){ 
				selFeatureControl.deactivate();
			}	
			modifyControl.mode = OpenLayers.Control.ModifyFeature.DRAG;
			modifyControl.activate();
		}else if(toolType=='selarea1'){	
			//Check if we can use these tools
			if(mmLayer.getVisibility()){					//If MasterMap showing
				document.getElementById(toolType).src = "images/" + toolType + "_on.png";
				document.varform.selectedTool.value = toolType;
				drawCapturePointControl.activate();				//Activate the point capture tool
			}else{
				if(document.varform.region.value == "gb"){
					showDialog('Warning','Please zoom in to OS MasterMap preview mapping before sending request to retrieve shape.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				}else{
					showDialog('Warning','Functionality not available for Northern Ireland mapping.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				}
			}
		}else if(toolType=='selarea3'){
			//Check if we can use these tools
			if(mmLayer.getVisibility()){					//If MasterMap showing
				document.getElementById(toolType).src = "images/" + toolType + "_on.png";
				document.varform.selectedTool.value = toolType;	
				drawCapturePolyControl.activate();				//Activate the poly capture tool
			}else{
				if(document.varform.region.value == "gb"){
					showDialog('Warning','Please zoom in to OS MasterMap preview mapping before sending request to retrieve shape.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				}else{
					showDialog('Warning','Functionality not available for Northern Ireland mapping.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				}		
			}
		}else if((toolType=='historic') || (toolType=='mappack')){
			document.varform.selectedTool.value = toolType;
			drawCapturePointControl.activate();				//Activate the point capture tool
		}else if(toolType=='capturepoints'){
			document.varform.selectedTool.value = toolType;
			drawCapturePolyControl.activate();				//Activate the capture tool
		}		 
	}
}
//****************Zoom to the passed data extent
function zoomToDataExtent(thePassedExtent){
	var zoomToIt = false;
	if(document.getElementById("exZoom") == null){			//Maybe null when we call this before the page is fully loaded
		zoomToIt = true;
	}else if(document.getElementById("exZoom").checked){
		zoomToIt = true;
	}
	if(zoomToIt){
		var theGeometryasBounds = thePassedExtent.geometry.getBounds();
		if(theGeometryasBounds != null){
			var theExtentWidth = theGeometryasBounds.getWidth();
			var theExtentHeight = theGeometryasBounds.getHeight();
			var centreLatLon = theGeometryasBounds.getCenterLonLat();
			var theX = centreLatLon.lon;
			var theY = centreLatLon.lat; 
			var blx = (theX - (theExtentWidth/2)) - (theExtentWidth/4);
			var bly = (theY - (theExtentHeight/2)) - (theExtentHeight/4);
			var urx = (theX + (theExtentWidth/2)) + (theExtentWidth/4);
			var ury = (theY + (theExtentHeight/2)) + (theExtentWidth/4);
			boundsForLicenceCheckPreAutoZoom = new OpenLayers.Bounds(blx,bly,urx,ury);
			//If the new view size means we will be viewing MasterMap ensure we check if the the area is licenced
			var testWidth = (urx - blx);
			var testHeight = (ury - bly);
			if((testWidth < 1000) && (testHeight < 1000)){
				if((document.varform.cid.value != "") && (document.varform.mmViewExtents.value == "")){			//Retreive initial licensed areas if not already done so
					//See if we need to zoom in a bit as should not retrieve lincensed areas at small scale
					var currentMapWidth = map.getExtent().getWidth();
					var currentMapHeight = map.getExtent().getHeight();
					if((currentMapWidth > 1000) || (currentMapHeight > 1000)){
				//	var tempBounds = new OpenLayers.Bounds((theX-500),(theY-500),(theX+500),(theY+500));
				//		map.zoomToExtent(tempBounds);
						map.setCenter(boundsForLicenceCheckPreAutoZoom.getCenterLonLat(),11,false,true)
					}
					checkLicenceAfterGetURM = false;
					getLicensedAreas();
				}else{
					if(performLicenceCheckPreAutoZoom(boundsForLicenceCheckPreAutoZoom)){
						map.zoomToExtent(boundsForLicenceCheckPreAutoZoom);
					}
				}
			}else{ 
				map.zoomToExtent(boundsForLicenceCheckPreAutoZoom);
			}
		}
	}
}
//****************Clear the selected data extent.
function clearExtent(theSelFeatureID,deleteIt){
	//Get selected features' geometry
	for(p=0; p < extentLayer.features.length;p++){
		if(extentLayer.features[p].attributes.id == theSelFeatureID){
			var theSelFeatureGeometry = extentLayer.features[p].geometry;
		}	
	}
	//Check if there are selected products attached to this extent
	var selectedProductIndices = getAssociatedExtents(theSelFeatureID);
	if((deleteIt == false) && (selectedProductIndices.length > 0)){				//Routine called to prompt to delete delete
		var dialogContent = "Do you want to delete the selected map extent?<br/>There are " + String(selectedProductIndices.length) + " products attached to this extent.<br/><br/><input type='button' value='Yes' id='yesButton' onclick='clearExtent(\"" + theSelFeatureID + "\",true);'>  <input type='button' value='No' id='noButton' onclick='hideDialog();' >"
		showDialog('',dialogContent,'prompt');
	}else{							  //Routine called to actually delete	
		 hideDialog();				
		//Remove the highest extent from the dropdown lists
		var extenNoToRemove = getNumExtents();		
		document.getElementById("selectedextent1").removeChild(document.getElementById("prod1_" + extenNoToRemove));
		document.getElementById("selectedextent2").removeChild(document.getElementById("prod2_" + extenNoToRemove));
		document.getElementById("selectedextent3").removeChild(document.getElementById("prod3_" + extenNoToRemove));
		document.getElementById("selectedextent4").removeChild(document.getElementById("prod4_" + extenNoToRemove));
		document.getElementById("selectedextent5").removeChild(document.getElementById("prod5_" + extenNoToRemove));		
		//Define if we need to reorder the extent numbers
		var reOrderExtents = false;
		var totalExtentFeatures = 0;
		for(p=0; p < extentLayer.features.length;p++){
			var testID = extentLayer.features[p].attributes.id;
			if(testID != null){
				totalExtentFeatures += 1;	
			}	
		}	
		var deletedFeatureID = Number(theSelFeatureID.substring((theSelFeatureID.length-1),theSelFeatureID.length));
		if((totalExtentFeatures > 1) && (deletedFeatureID != totalExtentFeatures)){
			reOrderExtents = true;
		}
		//Deselect modify control
		modifyControl.deactivate();
		modifyControl.activate();
		//Delete the feature
		for(p=0; p < extentLayer.features.length;p++){
			var theFeatureGeometry = extentLayer.features[p].geometry;	
			if(theFeatureGeometry == theSelFeatureGeometry){
				//Delete any paper extents
				for(p2=0; p2 < paperLayer.features.length;p2++){
					if(paperLayer.features[p2].attributes.id == extentLayer.features[p].attributes.id){
						paperLayer.removeFeatures(paperLayer.features[p2])
						break;
					}
				}
				//Delete any associated multi-extents
				for(p2=0; p2 < extentLayer2.features.length;p2++){
					if(extentLayer2.features[p2].attributes.id == extentLayer.features[p].attributes.id){
						extentLayer2.removeFeatures(extentLayer2.features[p2])
						break;
					}
				}
				extentLayer.removeFeatures(extentLayer.features[p])
				break;
			}
		}	
		if(selectedProductIndices.length != 0){
			for(c=0;c<selectedProductIndices.length;c++){
				document.getElementById("extent" + selectedProductIndices[c]).value = "";		//Clear associated extent
				document.getElementById("prod" +  selectedProductIndices[c] + "_0").selected = true;
				document.getElementById("selectedextent" +  selectedProductIndices[c]).style.backgroundColor = "#FFFFFF";
				updatePrice(selectedProductIndices[c]);											//Recalc price ie clear
			}
		}	
		//Update the extent info area (ie. hide the last one) If info needs to be reassigned this will happen latera 
		var selObj = document.getElementById("Extent " + totalExtentFeatures +"container");
		if(selObj != null){	
			selObj.style.display = "none";	
		}			
		//Re-order extents if necessary
		if(reOrderExtents){
			for(p=0; p < extentLayer.features.length;p++){
				var testID = extentLayer.features[p].attributes.id;
				if(testID != null){
					var testFeatureID = Number(testID.substring((testID.length-1),testID.length));
					//Check if this extent is a paper extent
					if(paperLayer.features.length > 0){
						var isPaperExtent = false;
						for(p1=0;p1 < paperLayer.features.length;p1++){								
							if(paperLayer.features[p1].attributes.id == testID){		//Remove existing
								var theCurrentPaperExtentFeature = paperLayer.features[p1];
								isPaperExtent = true;
								break;
							}
						}			
					}
					//Check if this extent is a multi extent
					if(extentLayer2.features.length > 0){
						var isMultiExtent = false;
						for(p1=0;p1 < extentLayer2.features.length;p1++){								
							if(extentLayer2.features[p1].attributes.id == testID){		//Remove existing
								var theCurrentMultiExtentFeature = extentLayer2.features[p1];
								isMultiExtent = true;
								break;
							}
						}			
					}			
					if(testFeatureID > deletedFeatureID){			//This feature will need ID re-ordering					
						//Reassign the stored extent
						for (var i=0; i < document.frmSelected.selectedproducts.length; i++){
							if(document.getElementById("extent" + String(i+1)).value == ("Extent " + testFeatureID)){
								document.getElementById("extent" + String(i+1)).value = "Extent " + (testFeatureID-1);		
								document.getElementById("prod" + String(i+1) + "_" + String(testFeatureID-1)).selected = true;
								document.getElementById("selectedextent" + String(i+1)).style.backgroundColor = extentColours[(testFeatureID-1)-1];
							}
						}
						var extentNo = testFeatureID - 1;
						var extentId = "Extent " + String(extentNo);
						theCurrentExtentID = extentId;	
						var theCurrentExtentFeature = extentLayer.features[p];
						theCurrentExtentFeature.attributes.id = extentId; 
						//Update extent in paper and multi layer to ensure they agree
						if(isPaperExtent){
							theCurrentPaperExtentFeature.attributes.id = extentId; 
						}
						if(isMultiExtent){
							theCurrentMultiExtentFeature.attributes.id = extentId; 
						}
						//Apply a default style 
						defExtentStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
						//Get extent colour and label
						var theExtentColour = extentColours[extentNo-1];
						defExtentStyle.label= String(extentNo)			
						defExtentStyle.fillColor = theExtentColour;
						defExtentStyle.strokeColor = theExtentColour;			
						defExtentStyle.fillOpacity= 0.15;	
						defExtentStyle.fontSize= "20px";
						defExtentStyle.fontFamily= "Arial";
						defExtentStyle.fontWeight= "bold";
						if(String(extentLayer.features[extentLayer.features.length-1].geometry).indexOf("POINT") == -1){	
							defExtentStyle.labelAlign= "ct";
						}else{
							defExtentStyle.labelAlign= "lb";
						}
						if(is_ie){
							defExtentStyle.cursor = "hand";	
						}else{
							defExtentStyle.cursor = "pointer";
						}			
						defExtentStyle.pointRadius = 10;					
						defExtentStyle.labelXOffset = 20;
						defExtentStyle.labelYOffset = 20;							
						//if(is_ie7down == false){
						//	defExtentStyle.fontColor = "#ffffff";  
						//	defExtentStyle.labelPadding = "5px";
						//	defExtentStyle.labelBackgroundColor = theExtentColour;
						//	defExtentStyle.labelBorderColor= theExtentColour;
						//	defExtentStyle.labelBorderSize= "1px"; 
						//}else{
						defExtentStyle.fontColor = theExtentColour;  
						//}	
						theCurrentExtentFeature.style = defExtentStyle;		  
						extentLayer.redraw();		
						//Update style of multi extent too	
						if(isMultiExtent){
							defExtentStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
							var theExtentColour = extentColours[extentNo-1];		
							defExtentStyle.fillColor = theExtentColour;
							defExtentStyle.strokeColor = theExtentColour;			
							defExtentStyle.fillOpacity= 0.15;
							if(is_ie){
								defExtentStyle.cursor = "hand";	
							}else{
								defExtentStyle.cursor = "pointer";
							}			
							theCurrentMultiExtentFeature.style = defExtentStyle;		  
							extentLayer2.redraw();
						}			
						//Update the extent info area 
						var selObj = document.getElementById(extentId+"container");
						if(selObj != null){	
							selObj.style.display = "block";
							updateExtentInfo(extentId);	
						}	
					}	
				}	
			}
		}
		//If order price not defined update the link (may be storing the wrong extent id due to an extent deletion)
		for (var c=0; c < document.frmSelected.selectedproducts.length; c++){
			if((document.getElementById("orderprice" + String(c+1)).value == "") || (document.getElementById("orderprice" + String(c+1)).value == "0")){
				document.getElementById("showdataprice" + String(c+1)).innerHTML = "<p>&pound; **.**<br/><a href='javascript:retrievePrice(\"show\",\""+ String(c+1) + "\",\"" + document.getElementById("extent" + String(c+1)).value + "\");' style='font-size:11px;'>Get Price</a></p>"; 	//Clear the price				
			}
		}
	}		
}
//************************Update the displayed extent inputs when the user changes the units dropdown
function amendUserCoords(selObj,toUpdate){
	//Get new value
	var newValue = selObj.options[selObj.selectedIndex].value;
	//Get Current value
	if(toUpdate == "radius"){													//Radius extent		
		var currentUnit = document.radiusSizeform.currentradiusunit.value;		
	}else if(toUpdate == "extent"){												//Ground extent
		var currentUnit = document.groundSizeform.currentexteunit.value;
	}else if(toUpdate == "pageextent"){											//Page extent		
		var currentUnit = document.mappingSizeform.currentpageunit.value;
	}
	//Get scale factor	
	if((currentUnit == "km") && (newValue == "mi")){				//km -> mi	
		var unitScaleFact = 0.6;
	}else if((currentUnit == "km") && (newValue == "m")){			//km -> mi	
		var unitScaleFact = 1000;
	}else if((currentUnit == "mi") && (newValue == "km")){			//mi -> km
		var unitScaleFact = 1.604;	
	}else if((currentUnit == "mi") && (newValue == "m")){			//mi -> m	
		var unitScaleFact = 1604;
	}else if((currentUnit == "m") && (newValue == "km")){			//m -> km
		var unitScaleFact = 0.001;
	}else if((currentUnit == "m") && (newValue == "mi")){			//m -> mi
		var unitScaleFact = 0.0006;				
	}else if((currentUnit == "mm") && (newValue == "cm")){			//mm -> cm
		var unitScaleFact = 0.1;		
	}else if((currentUnit == "mm") && (newValue == "in")){			//mm -> in
		var unitScaleFact = 0.0394;		
	}else if((currentUnit == "cm") && (newValue == "mm")){			//cm -> mm
		var unitScaleFact = 10;		
	}else if((currentUnit == "cm") && (newValue == "in")){			//cm -> in
		var unitScaleFact = 0.394;		
	}else if((currentUnit == "in") && (newValue == "mm")){			//in -> mm
		var unitScaleFact = 25.4;		
	}else if((currentUnit == "in") && (newValue == "cm")){			//in -> mm
		var unitScaleFact = 2.54;
	}	
	//Change display to selected units
	if(toUpdate == "radius"){
		document.radiusSizeform.userradius.value = Math.round((Number(document.radiusSizeform.userradius.value) * unitScaleFact) * 100) /100;		
		var currentUnit = document.radiusSizeform.currentradiusunit.value = newValue;			
	}else if(toUpdate == "extent"){
		document.groundSizeform.userxm.value =  Math.round((Number(document.groundSizeform.userxm.value) * unitScaleFact) * 100) /100;
		document.groundSizeform.userym.value =  Math.round((Number(document.groundSizeform.userym.value) * unitScaleFact) * 100) /100;
		var currentUnit = document.groundSizeform.currentexteunit.value = newValue;
	}else if(toUpdate == "pageextent"){
		document.mappingSizeform.userxmm.value =  Math.round((Number(document.mappingSizeform.userxmm.value) * unitScaleFact) * 100) /100;
		document.mappingSizeform.userymm.value =  Math.round((Number(document.mappingSizeform.userymm.value) * unitScaleFact) * 100) /100;
		var currentUnit = document.mappingSizeform.currentpageunit.value = newValue;
	}	
}

//-------------------------------------------------------------------------DRAWING DATA EXTENT SCRIPTS
//****************Draw the map extent from the passed coordinate string (POINT or POLY) 
function drawDataExtent(passedCoordinates,theType){
	if(getNumExtents() >= 5){
		showDialog('Warning','A maximum of 5 extents can be drawn.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');	
	}else{	
		if(theType == "poly"){	
			var pointList = [];			
			var theCoordArray = passedCoordinates.split(",");		
			for (c=0; c< theCoordArray.length ;c++){
				var theXY = theCoordArray[c].split(" ");
				var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
				pointList.push(newPoint);
			}					
			var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
			theExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);
		}else if(theType == "point"){ 			
			var theCoordArray = passedCoordinates.split(",");		
			var theXY = theCoordArray[0].split(" ");
			var theExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(theXY[0],theXY[1]),null);
		}
		extentLayer.addFeatures(theExtentFeature);
	}		
}
//****************Define the fixed map extent based around the capture point
function defineFixedMapExtents(theCaptureShape,theType){			
	//Set the extent sizes (in metres) for OS MasterMap Packs and Historic map products
	var selectedData = document.varform.data.value.toLowerCase();				
	if(selectedData.indexOf("gs1_1") == 0){								//Complete set
		var extentsToShow = new Array("gsExtent1","gsExtent2");
		var extentSizes = new Array(650,2600);
	}else if(selectedData.indexOf("gs1_2") == 0){							//10,000 sets
		var extentsToShow = new Array("gsExtent1","");  		//Does not work with just one array element
		var extentSizes = new Array(2600,0);
	}else if((selectedData.indexOf("gs1_3") == 0)){							//2,500 sets etc
		var extentsToShow = new Array("gsExtent2","");
		var extentSizes = new Array(650,0);
	//PACKS AND EXTENT AVAILABLE TO CHECK			
	}else if(selectedData == "osmmbwpack1"){							//1:500 and 1250 (value) sets 
		var extentsToShow = new Array("osExtent2","osExtent1");
		var extentSizes = new Array(200,200,80,80);
	}else if(selectedData == "osmmbwpack2"){							//1:500 and 2500 (value) sets 
		var extentsToShow = new Array("osExtent3","osExtent1");
		var extentSizes = new Array(400,400,80,80);			
	}else if(selectedData == "osmmbwpack3"){							//1:500 and 1250 (std) sets 
		var extentsToShow = new Array("osExtent2","osExtent1");
		var extentSizes = new Array(200,250,80,100);
	}else if(selectedData == "osmmbwpack4"){							//1:500 and 2500 (std) sets 
		var extentsToShow = new Array("osExtent3","osExtent1");
		var extentSizes = new Array(400,500,80,100);
	}
	//Store info on hidden
	document.varform.extentinput.value = "gsmap";
	document.varform.papersize.value = "";		
	if(selectedData.indexOf("osmmbwpack") == 0){				//Check!!
		document.varform.extentType.value = "scaled";
	}else{
		document.varform.extentType.value = "ground";
	}		
	//Get the centre point for the extents
	var theXY = new Array();
	if(theType == "define"){													//Is the passed click point	
		var theGeometryAsString = String(theCaptureShape.geometry);
		theGeometryAsString = theGeometryAsString.substring(6,(theGeometryAsString.length-1));
		theXY = theGeometryAsString.split(" ");
	}else if(theType == "reshow"){												//Is the passed x-y	
		theXY = theCaptureShape.split(" ");	
	}else if(theType == "redraw"){												//Is the centroid of passed polygon (Used when redrawing the outer extent
		theXY[0] = theCaptureShape.geometry.getCentroid().x;
		theXY[1] = theCaptureShape.geometry.getCentroid().y;
	}
	//Define coordinates for map extents
	var pointList2 = [];
	for(c=0;c<extentsToShow.length;c++){
		if(extentSizes[c] != 0){
			//Define the map extent and add
			if(selectedData.indexOf("osmmbwpack") == 0){
				var theblx = Math.round((Number(theXY[0]) - (extentSizes[c*2] / 2)) * 10) / 10;
				var thebly = Math.round((Number(theXY[1]) + (extentSizes[(c*2)+1] / 2)) * 10) / 10;
				var thetrx = Math.round((Number(theXY[0]) + (extentSizes[c*2] / 2)) * 10) / 10;
				var thetry = Math.round((Number(theXY[1]) - (extentSizes[(c*2)+1] / 2)) * 10) / 10;
			}else{					
				var theblx = Math.round((Number(theXY[0]) - (extentSizes[c] / 2)) * 10) / 10;
				var thebly = Math.round((Number(theXY[1]) + (extentSizes[c] / 2)) * 10) / 10;
				var thetrx = Math.round((Number(theXY[0]) + (extentSizes[c] / 2)) * 10) / 10;
				var thetry = Math.round((Number(theXY[1]) - (extentSizes[c] / 2)) * 10) / 10;	
			}	
			var pointList = [];							
			var newPoint = new OpenLayers.Geometry.Point(theblx,thebly);
			pointList.push(newPoint);
			if(c==0){pointList2.push(newPoint.clone())}
			var newPoint = new OpenLayers.Geometry.Point(theblx,thetry);
			pointList.push(newPoint);
			if(c==0){pointList2.push(newPoint.clone())}
			var newPoint = new OpenLayers.Geometry.Point(thetrx,thetry);
			pointList.push(newPoint);
			if(c==0){pointList2.push(newPoint.clone())}	
			var newPoint = new OpenLayers.Geometry.Point(thetrx,thebly);
			pointList.push(newPoint);
			if(c==0){pointList2.push(newPoint.clone())}
			var newPoint = new OpenLayers.Geometry.Point(theblx,thebly);
			pointList.push(newPoint);
			if(c==0){pointList2.push(newPoint.clone())}					
			var linearRing = new OpenLayers.Geometry.LinearRing(pointList);	
			if(c==0){																	//Add the inner extent
				if(theType != "redraw"){												//If redrawing the inner extent will be already defined
					theExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);
					extentLayer.addFeatures(theExtentFeature);
				}
			}else{																		//Add the outer extent (with hole)
				var linearRing2 = new OpenLayers.Geometry.LinearRing(pointList2);
				theExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing,linearRing2]),null);
				extentLayer2.addFeatures(theExtentFeature);							
			}			
		}			
	}			
	drawCapturePointControl.deactivate();				//Deactivate the point capture tool
}
//****************Draw the paper size map extent from the passed width, height and scale 
function drawPaperDataExtent(xSizeMetres, ySizeMetres, mapScale, extentCoords, drawExtent){
	if(getNumExtents() >= 5){
		showDialog('Warning','A maximum of 5 extents can be drawn.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');		
	}else{
		if(extentCoords == ""){											//No extent passed create from paper dimensions and scale (used when choosing from options on the page)
			//Set the size of extent in metres at the specified scale.
			mapSizeX = xSizeMetres * mapScale;
			mapSizeY = ySizeMetres * mapScale;			
			//Define coordinates of the extent			
			var mapCentreX = map.getCenter().lon;	
			var mapCentreY = map.getCenter().lat;			
			var extentblx = mapCentreX - (mapSizeX/2);	
			var extentbly = mapCentreY - (mapSizeY/2);
			var extenttrx = mapCentreX + (mapSizeX/2);	
			var extenttry = mapCentreY + (mapSizeY/2);
			var extentCoords = String(extentblx) + " " + String(extentbly) + "," + String(extentblx) + " " + String(extenttry) + "," + String(extenttrx) + " " + String(extenttry) + "," + String(extenttrx) + " " + String(extentbly) + "," + String(extentblx) + " " + String(extentbly);			
		}else{															//Extent passed (used when re-creating a paper extent on the interface ie a previous or saved order)
			//Store the extent in blx,bly,trx,try variables in order to add the paper exetnt
			var tempExtentArray = extentCoords.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 pointList = [];
		var pointList2 = [];			
		var theCoordArray = extentCoords.split(",");		
		for (c=0; c< theCoordArray.length ;c++){
			var theXY = theCoordArray[c].split(" ");
			var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
			pointList.push(newPoint);
			pointList2.push(newPoint.clone());
		}					
		var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
		var linearRing1 = new OpenLayers.Geometry.LinearRing(pointList2);
		polygonExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);		
		//Define the extent of the paper size
		var topmarginY = 0.025;						
		var leftmarginX = 0.025;
		var rightmarginX = getPaperSizeMargin("right");
		var botmarginY = getPaperSizeMargin("bottom");	
		leftmarginX = leftmarginX * mapScale;
		rightmarginX = rightmarginX * mapScale;
		topmarginY = topmarginY * mapScale;
		botmarginY = botmarginY * mapScale;
		var paperSizeMinX = extentblx - leftmarginX;
		var paperSizeMinY = extentbly - botmarginY;
		var paperSizeMaxX = extenttrx + rightmarginX;
		var paperSizeMaxY = extenttry + topmarginY;		
		var extentCoords = String(paperSizeMinX) + " " + String(paperSizeMinY) + "," + String(paperSizeMinX) + " " + String(paperSizeMaxY) + "," + String(paperSizeMaxX) + " " + String(paperSizeMaxY) + "," + String(paperSizeMaxX) + " " + String(paperSizeMinY) + "," + String(paperSizeMinX) + " " + String(paperSizeMinY);			
		var pointList = [];			
		var theCoordArray = extentCoords.split(",");		
		for (c=0; c< theCoordArray.length ;c++){
			var theXY = theCoordArray[c].split(" ");
			var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
			pointList.push(newPoint);
		}					
		var linearRing2 = new OpenLayers.Geometry.LinearRing(pointList);
		paperExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing1,linearRing2]),null);		
		//Add extents to the map
		if(drawExtent){													//If called after moving a paper extent - don't need to draw the actual data extent
			extentLayer.addFeatures(polygonExtentFeature);
			polygonExtentFeature.attributes.datascale = mapScale;
		}
		paperLayer.addFeatures(paperExtentFeature);			
	}	
}
//****************Stores new data scale and resizes the selected drawn map extent if necessary
function updateProductScale(selObj){	
	//Get the new map scale and product index
	var mapScale = selObj.options[selObj.selectedIndex].value;
	var selectedProdIndex = getSelectedProductIndex();
	//Get the extent attached to the selected product
	resizeFeatureID= document.getElementById("extent" + selectedProdIndex).value;
	if(resizeFeatureID != ""){
		var theCurrentFeature = getFeatureExtentByID(resizeFeatureID);
		if(theCurrentFeature != null){
			if(theCurrentFeature.attributes.papersize != null){						//If a paper extent resize
				//Define the number of products using this extent
				var extentUsedCnt = checkIfExtentUsed(resizeFeatureID);
				if(extentUsedCnt > 1){			//More than one products with this extent.
					showDialog('Warning','Can\'t change the scale of this products as another product is using this extent at a different scale.<br/>Please define a new extent under the "Define Area" tab.<br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
					document.getElementById("theScales" + selectedProdIndex).value = document.getElementById("scale" + selectedProdIndex).value;	//reset the drop down
				}else{
					//Get current centrepoint of the extent
					var centreX = String(Math.round(theCurrentFeature.geometry.getCentroid().x)); 
					var centreY = String(Math.round(theCurrentFeature.geometry.getCentroid().y));
					var passedMapScale = document.getElementById("theScales" + selectedProdIndex).value;
					//Get rid of the current extent
					clearExtentPreResize(resizeFeatureID);
					//Redraw the new extent
					var theCurrentPaperSize = theCurrentFeature.attributes.papersize.toLowerCase();
					updatingExtent = resizeFeatureID.substring((resizeFeatureID.length-1),resizeFeatureID.length);	
					getSheetSize(centreX,centreY,theCurrentPaperSize,passedMapScale);
					//Changed stored scaled extent if necessary
					document.getElementById("scale" + selectedProdIndex).value = mapScale;
				}
			}else{
				//Store the new map scale for the selected product
				document.getElementById("scale" + selectedProdIndex).value = mapScale;
			}
		}else{
			//Store the new map scale for the selected product
			document.getElementById("scale" + selectedProdIndex).value = mapScale;
		}		
	}else{
		//Store the new map scale for the selected product
		document.getElementById("scale" + selectedProdIndex).value = mapScale;
	}

}
//****************Stores new data scale before drawing map extent
function updateProductScale2(selObj){	
	/*Store the new map scale for the selected product
	var mapScale = selObj.options[selObj.selectedIndex].value;
	var selectedProdIndex = getSelectedProductIndex();
	document.getElementById("theScales" + selectedProdIndex).value = mapScale;
	document.getElementById("scale" + selectedProdIndex).value = mapScale;*/
}

//****************Clear the data extent before resizing an extent (as a new one will be added to replace the old one).
function clearExtentPreResize(theSelFeatureID){
	//Get selected features' geometry
	for(p=0; p < extentLayer.features.length;p++){
		if(extentLayer.features[p].attributes.id == theSelFeatureID){
			var theSelFeatureGeometry = extentLayer.features[p].geometry;
		}	
	}
	//Delete the feature
	for(p=0; p < extentLayer.features.length;p++){
		var theFeatureGeometry = extentLayer.features[p].geometry;	
		if(theFeatureGeometry == theSelFeatureGeometry){
			//Delete any paper extents
			for(p2=0; p2 < paperLayer.features.length;p2++){
				if(paperLayer.features[p2].attributes.id == extentLayer.features[p].attributes.id){
					paperLayer.removeFeatures(paperLayer.features[p2])
					break;
				}
			}
			extentLayer.removeFeatures(extentLayer.features[p])
			break;
		}
	}		
}
//************************Get the bottom and right margins for paper size extent
function getPaperSizeMargin(theMargin){
	leftmarginX = 0.025;
	topmarginY = 0.025;
	if(document.varform.papersize.value.toLowerCase() == "a5p"){
		rightmarginX = (0.148 - 0.098) - leftmarginX;
		botmarginY = (0.210 - 0.113) - topmarginY;		
	}else if(document.varform.papersize.value.toLowerCase() == "a5l"){
		rightmarginX = (0.210 - 0.113) - leftmarginX;
		botmarginY = (0.148 - 0.098) - topmarginY;		
	}else if(document.varform.papersize.value.toLowerCase() == "a4p"){
		rightmarginX = (0.210 - 0.160) - leftmarginX;
		botmarginY = (0.297 - 0.200) - topmarginY;	
	}else if(document.varform.papersize.value.toLowerCase() =="a4l"){
		rightmarginX = (0.297 - 0.200) - leftmarginX;      
		botmarginY = (0.210 - 0.160) - topmarginY;
	}else if(document.varform.papersize.value.toLowerCase() =="a3p"){
		rightmarginX = (0.297 - 0.247) - leftmarginX;
		botmarginY = (0.420 - 0.323) - topmarginY;		
	}else if(document.varform.papersize.value.toLowerCase() =="a3l"){
		rightmarginX = (0.420 - 0.323) - leftmarginX;
		botmarginY = (0.297 - 0.247) - topmarginY;
	}else if(document.varform.papersize.value.toLowerCase() =="a2p"){                                                          
		rightmarginX = (0.420 - 0.370) - leftmarginX;
		botmarginY = (0.594 - 0.497) - topmarginY;	
	}else if(document.varform.papersize.value.toLowerCase() =="a2l"){
		rightmarginX = (0.594 - 0.497) - leftmarginX;
		botmarginY = (0.420 - 0.370) - topmarginY;	
	}else if(document.varform.papersize.value.toLowerCase() =="a1p"){
		rightmarginX = (0.594 - 0.544) - leftmarginX;
		botmarginY = (0.841 - 0.743) - topmarginY;
	}else if(document.varform.papersize.value.toLowerCase() =="a1l"){
		rightmarginX = (0.841 - 0.743) - leftmarginX;
		botmarginY = (0.594 - 0.544) - topmarginY;
	}else if(document.varform.papersize.value.toLowerCase() =="2a0p"){
		rightmarginX = (1.189 - 1.138) - leftmarginX;
		botmarginY = (1.682 - 1.583) - topmarginY;	
	}else if(document.varform.papersize.value.toLowerCase() =="2a0l"){
		rightmarginX = (1.682 - 1.583) - leftmarginX;
		botmarginY = (1.189 - 1.138) - topmarginY;				
	}else if(document.varform.papersize.value.toLowerCase() =="a0p"){
		rightmarginX = (0.841 - 0.790) - leftmarginX;
		botmarginY = (1.189 - 1.091) - topmarginY;
	}else if(document.varform.papersize.value.toLowerCase() =="a0l"){
		rightmarginX = ( 1.189 - 1.091) - leftmarginX;
		botmarginY = (0.841 - 0.790) - topmarginY;
	}else if(document.varform.papersize.value.toLowerCase() =="a4v"){
		rightmarginX = (0.210 - 0.160) - leftmarginX;
		botmarginY = (0.297 - 0.160) - topmarginY;
	}	
	if(theMargin == "right"){
		return rightmarginX;
	}else{
		return botmarginY;
	}		
}
//************************Remove capture shape
function removeCaptureShape(theCaptureShape){
	var theCaptureGeometry = theCaptureShape.geometry;	
	for(p=0; p < captureLayer.features.length;p++){
		var theFeatureGeometry = captureLayer.features[p].geometry;
		if(theFeatureGeometry == theCaptureGeometry){
			captureLayer.removeFeatures(captureLayer.features[p])	
			break;
		}
	}
}

//-------------------------------------------------------------------------PREVIOUS ORDERS SCRIPTS
//****************Show or Hide the user's or companies previos orders
function showHidePrevious(selObj){
	if(document.varform.cid.value != ""){							//Check user is logged in
		if(selObj.checked){
			var qstring = "catid=" + document.getElementById("optPrevCat").value + "&cid=" + document.varform.cid.value;
			var getPreviousReq = new ajaxObject('getPrevious.php', handlePreviousResponse);
			getPreviousReq.update(qstring,'POST');	
		}else{						//Hide previous extents (actually delete the features)
			previousLayer.destroyFeatures();			//Delete all features from the layer		
		}
	}else{
		showDialog('Warning','Please ensure you are logged in before showing previous orders.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');	
		selObj.checked = false;
	}
	//Hide the map layers tab
	hideMapLayers();
}
//****************Handles the response from getting previous extents
function handlePreviousResponse(responseText, responseStatus){
	if(responseStatus == 200){
		if(responseText != ""){
			if(responseText.indexOf('_' != -1)) {
				var tempArray = new Array();
				tempArray = responseText.split('_');
				if(tempArray[0] != ""){													//Draw previous extents										
					var theExtentString  = tempArray[0];
					var theExtentArray = theExtentString.split("|");
					var theOrderNoString = tempArray[1];
					var theOrderNoArray = theOrderNoString.split("|");
					//Draw each extent in turn	
					for(prev=0;prev<theExtentArray.length;prev++){
						//Check if extent to show is a GroundSure point
						var gsPointTest = theOrderNoArray[prev].substring ((theOrderNoArray[prev].length - 2),theOrderNoArray[prev].length); 		//Identifies a GroundSure point object						
						if((gsPointTest == "gs")){									//Create point geometry
							var isGSPoint = true;
							theOrderNoArray[prev] = theOrderNoArray[prev].substring (0,(theOrderNoArray[prev].length - 2))			
							var theCoordArray = theExtentArray[prev].split(",");		
							var theXY = theCoordArray[0].split(" ");
							var previousExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(theXY[0],theXY[1]),null);		
						}else{														//Create polygon geometry
							var isGSPoint = false;
							var pointList = [];			
							var theCoordArray = theExtentArray[prev].split(",");		
							for (c=0; c< theCoordArray.length ;c++){
								var theXY = theCoordArray[c].split(" ");
								var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
								pointList.push(newPoint);
							}
							var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
							var previousExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);
						}
						//Apply the ID
						previousExtentFeature.attributes.id = "prev_"+ theOrderNoArray[prev];		
						//Apply a default style 
						defAnnoStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
						defAnnoStyle.fillOpacity= 0.3;
						defAnnoStyle.graphicOpacity= 1;
						defAnnoStyle.fillColor= "#FF0000";
						defAnnoStyle.strokeWidth= 2;	
						defAnnoStyle.strokeDashstyle= "none";
						defAnnoStyle.strokeColor=  "#FF0000";
						defAnnoStyle.pointerEvents= "visiblePainted";
						defAnnoStyle.label = theOrderNoArray[prev];
						defAnnoStyle.fontColor = "#2A0000";
						defAnnoStyle.fontSize = "10px";
						defAnnoStyle.fontFamily = "Arial";
						if(isGSPoint){
							defAnnoStyle.pointRadius = 10;
							defAnnoStyle.labelAlign = "lb";    
						}else{
							defAnnoStyle.labelAlign = "cc";      	
						}
						defAnnoStyle.labelXOffset = "10px";
						defAnnoStyle.labelYOffset = "10px";			
						if(is_ie7down == false){
							defAnnoStyle.labelPadding = "5px";
							defAnnoStyle.labelBackgroundColor = "#ffffff";
							defAnnoStyle.labelBorderColor= "#2A0000";
							defAnnoStyle.labelBorderSize= "1px";  
						}
						previousExtentFeature.style = defAnnoStyle;
						previousLayer.addFeatures(previousExtentFeature);
					}																			
				}else{
					showDialog('Warning','No previous orders have been found for display.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				}	
			}
		}else{			
			showDialog('Warning','No previous orders have been found for display.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}
	}
}
//****************Toogle the state of the 'Show previous button'
function toggleShowPrevious(selObj){
	if(selObj.src.indexOf("btnShowPastON") != -1){
		selObj.src='images/btnShowPast.jpg';
	}else if(selObj.src.indexOf("btnHidePastON") != -1){
		selObj.src='images/btnHidePast.jpg';
	}else if(selObj.src.indexOf("btnShowPast") != -1){
		selObj.src='images/btnShowPastON.jpg';
	}else if(selObj.src.indexOf("btnHidePast") != -1){
		selObj.src='images/btnHidePastON.jpg';
	}
}
//****************Updates the previous orders showing when user changes the category to display
function refreshPrevious(){
	//If the  previous extent are already showing need to show but with the new selected category
	var selObj = document.getElementById("chkPrevious");
	if(selObj.checked){
		previousLayer.destroyFeatures();			//Delete all features from the layer
		showHidePrevious(selObj);					//Show new selection
	}
}

//-------------------------------------------------------------------------NOT AVAILABLE EXTENTS SCRIPTS
//****************Shows or hides the Not available areas
function getNA(showIt){
	document.getElementById("NA_key").innerHTML = "&nbsp;";    				//Hide key
	if(showIt == "yes"){														//Show 'Not Avaialable' extents
		NALayer.destroyFeatures();												//Delete features from the layer first
		var qstring = "naname=" + document.varform.availibility.value;
		var getNAReq = new ajaxObject('getNA.php', handleNAResponse);
		getNAReq.update(qstring,'POST');
	}else{																		//Hide 'Not Avaialable' extents	
		NALayer.destroyFeatures();												//Delete features from the layer
	}	
}
//****************Handles the response from getting Not Avaialable extents
function handleNAResponse(responseText, responseStatus){
	if(responseStatus == 200){
		if(responseText != ""){
			var tempArray = responseText.split("_");							
			document.getElementById("NA_key").innerHTML = "Grey areas indicate data not available.";			//Show key			
			//Draw the extents				
			if(tempArray[1] != ""){
				var theNAArray = tempArray[1].split('|');			
				for(na=0;na<theNAArray.length;na++){
					var pointList = [];			
					var theCoordArray = theNAArray[na].split(",");		
					for (c=0; c< theCoordArray.length ;c++){
						var theXY = theCoordArray[c].split(" ");
						var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
						pointList.push(newPoint);	
					}					
					var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
					var NAExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);
					NALayer.addFeatures(NAExtentFeature);
				}
			}									
		}
	}
}

//-------------------------------------------------------------------------GROUNDSURE SCRIPTS
//****************Stores entrered info about the Groundsure extent
function storeGSInfo(theType){
	var allDefinedOK = true;
	if(theType == "simple"){
		var gsInfoString = document.gsform.gsAddress1.value + "|" + document.gsform.gsPostCode1.value; 		//Address and Post Code
		var selectedIndex = getSelectedProductIndex();
		document.getElementById("gsinfo" + selectedIndex).value = gsInfoString;		
	}else if(theType == "full"){
		var dialogContent = "";
		var gsInfoString = document.gsform.gsAddress2.value + "|" + document.gsform.gsPostCode2.value; 		//Address and Post Code			
		//Current use
		var isDefined = false;
		for(c=0;c<6;c++){
			if(document.gsform.gs3cuse[c].checked){
				cuse = c;			
				//Store current use			
				if(cuse == 5){
					if(document.gsform.cuse6text.value == ""){
						dialogContent += 'Please ensure that the "Current Use" has been defined.<br/>';
						allDefinedOK = false;
					}
					gsInfoString += "|" + document.gsform.cuse6text.value; 
				}else{
					gsInfoString += "|" + String(cuse);
				}
				isDefined = true;
				break;
			}
		}
		if(isDefined == false){
			gsInfoString += "|-1";		
		}	
		//Proposed use
		var isDefined = false;
		for(c=0;c<6;c++){
			if(document.gsform.gs3puse[c].checked){
				puse = c;
				//Store proposed use			
				if(puse == 5){
					if(document.gsform.puse6text.value == ""){
						dialogContent += 'Please ensure that the "Proposed Use" has been defined.<br/>';
						allDefinedOK = false;
					}
					gsInfoString += "|" + document.gsform.puse6text.value; 
				}else{
					gsInfoString += "|" + puse;
				}
				isDefined = true;
				break;
			}
		}
		if(isDefined == false){
			gsInfoString += "|-1";		
		}	
		//Age of Property
		if(document.gsform.age.value == ""){
			dialogContent += 'Please ensure that the "Age of Property" has been defined.<br/>';
			allDefinedOK = false;
		}
		gsInfoString += "|" + document.gsform.age.value; 
		//Store 'Known Issues'
		gsInfoString += "|" + document.gsform.issues.value; 	
		var selectedIndex = getSelectedProductIndex();
		document.getElementById("gsinfo" + selectedIndex).value = gsInfoString;
	}
	//Close the overlay
	if(allDefinedOK){
		closeGSInfo();
	}else{
		showDialog('Warning',dialogContent + '<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}
}
//****************Stores entrered info about the Groundsure extent (Called when recreating the order) 
function storeGSInfo2(theGSInfoString){
	if(theGSInfoString != ""){
		var gsInfoArray = theGSInfoString.split("_");				//0=Current Use, 1=Proposed Use, 2=Age of Property, 3=Known Issues, 4=Address, 5=Postcode
		if((gsInfoArray[0] == "") && (gsInfoArray[1] == "") && (gsInfoArray[2] == "") && (gsInfoArray[3] == "")){			//Address and Post Code only	
			document.getElementById("gsinfo1").value = gsInfoArray[4] + "|" + gsInfoArray[5];
		}else{
			document.getElementById("gsinfo1").value = gsInfoArray[4] + "|" + gsInfoArray[5] + "|" + gsInfoArray[0] + "|" + gsInfoArray[1] + "|" + gsInfoArray[2] + "|" + gsInfoArray[3];
		}
		showGSInfo();
	}
}
//****************Show Groundsure info for the selected product
function showGSInfo(){
	//Define the type of option to show 
	if(document.varform.data.value.indexOf("GS3_2") == 0){
		theGSOption = "full";
	}else{
		theGSOption = "simple";
	}					
	//Get any stored parameters for the selected product
	var selectedIndex = getSelectedProductIndex();
	var gsInfoString = document.getElementById("gsinfo" + selectedIndex).value;
	if(gsInfoString != ""){
		var gsInfoArray = gsInfoString.split("|");
		var theGSAddress = gsInfoArray[0];
		var theGSPostcode = gsInfoArray[1];		
		if(isNaN(gsInfoArray[2])){
			var gsOpt1 = gsInfoArray[2];
		}else{
			var gsOpt1 = Number(gsInfoArray[2]);
		}
		if(isNaN(gsInfoArray[3])){
			var gsOpt2 = gsInfoArray[3];
		}else{
			var gsOpt2 = Number(gsInfoArray[3]);
		}	
		var gsOpt3 = gsInfoArray[4];
		var gsOpt4 = gsInfoArray[5];		
	}else{	
		var theGSAddress = document.varform.gsaddress.value;
		var theGSPostcode = document.varform.gspostcode.value;
		var gsOpt1 = "";
		var gsOpt2 = "";
		var gsOpt3 = "";
		var gsOpt4 = "";
	}
	var qstring = "theoption=" + theGSOption + "&gsaddress=" + theGSAddress + "&gspostcode=" + theGSPostcode + "&opt1=" + gsOpt1 + "&opt2=" + gsOpt2 + "&opt3=" + gsOpt3 + "&opt4=" + gsOpt4;
	var showGSInfoReq = new ajaxObject('gsinfo.php', showGSInfoResponse);
	showGSInfoReq.update(qstring,'POST');		
}
//*****************************Check all required options selected for GroundSure Type 3 Site reports
function checkSiteReportOptions(selectedIndex){
	var isOK = true;
	//Get the storedd groundsure options		
	var gsInfoString = document.getElementById("gsinfo" + selectedIndex).value;	
	if(gsInfoString == ""){
		showDialog('Warning','Please ensure that "Additional Info." has been defined.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		isOK = false;
	}else{
		var dialogContent = "";
		var gsInfoArray = gsInfoString.split("|");	
		//Current use
		if(gsInfoArray[2] == ""){
			isOK = false;
			dialogContent += 'Please ensure that the "Current Use" has been defined.<br/>';
		}	
		//Proposed use
		if(gsInfoArray[3] == ""){
			isOK = false;
			dialogContent += 'Please ensure that the "Proposed Use" has been defined.<br/>';
		}	
		//Age of Property
		if(gsInfoArray[4] == ""){
			isOK = false;
			dialogContent += 'Please ensure that the "Age of Property" has been fully defined.<br/>';
		}		
		if(isOK == false){
			showDialog('Warning',dialogContent + '<input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');	
		}
	}
	return isOK;	
}
//****************Response from getting further Groundsure info.
function showGSInfoResponse(responseText, responseStatus){
	if(responseStatus == 200){
		if(theGSOption == "full"){
			document.getElementById("gsInfoContent").style.display = "block";
			document.getElementById("gsInfoContentContent").innerHTML = responseText;		//Show furher GS info required (full options)
		}else{
			document.getElementById("gsInfoContent2").style.display = "block";
			document.getElementById("gsInfoContent2Content").innerHTML = responseText;		//Show furher GS info required (postcode and adress options only)	
		}
		callCufon();			
	}
}
//****************Close Groundsure info. layers
function closeGSInfo(){
	document.getElementById("gsInfoContent").style.display = "none";				//For full options
	document.getElementById("gsInfoContentContent").innerHTML = "";
	document.getElementById("gsInfoContent2").style.display = "none";				//For postcode and adress options only
	document.getElementById("gsInfoContent2Content").innerHTML = "";		
}

//----------------------------End of Script
