/*--------------------------------------------------------------
useranno.js
Javascript for CentremapsLive map interface
User annotation drawing scripts and associated
Lovell Johns Ltd
Jan 2010
----------------------------------------------------------------*/

//-------------------------------------------------------------------------GLOBALS
var shapeToAdd = 0; 

//-------------------------------------------------------------------------DRAWING TOOLS AND STORING ANNO SCRIPTS

//******************Toogle the opacity of the map extent layers (Used when drawing editing anno elements)
function adjustMapExtentOpacity(actionType){
	//OLD - Change opacity
	/*if(actionType == "fade"){
		extentLayer.setOpacity(0.5);
		extentLayer2.setOpacity(0.5);
		paperLayer.setOpacity(0.5);	
	}else if(actionType == "full"){
		extentLayer.setOpacity(1);
		extentLayer2.setOpacity(1);
		paperLayer.setOpacity(1);
	}*/
	//NEW - Remove the fill
	for(ecnt=0;ecnt < 5;ecnt++){
		var theExtentColour = extentColours[ecnt];
		var passedExtentID = "Extent " + String(ecnt+1);
		var theCurrentExtentFeature = getFeatureExtentByID(passedExtentID);	
		if(theCurrentExtentFeature != null){		
			defExtentStyle.fillColor = theExtentColour;
			if(actionType == "fade"){
				theCurrentExtentFeature.style.fillColor = "none";		  
			}else if(actionType == "full"){	
				theCurrentExtentFeature.style.fillColor = theExtentColour;	
			}	
		}
	}
	extentLayer.redraw();		
}
//******************Enable the selected tools on the tool bar
function annoDrawingEnable(toolType){	
	adjustMapExtentOpacity("fade");    									//Knock back extent layers when using drawing tools
	canHideIt = true; 													//Can now hide toolbox on mouse over map (if not already set)	
	var theMapLayer = document.getElementById("map");					//Get the map layer (Used to update the map cursor)	
	theMapLayer.style.cursor='default';  	
	deactivateDrawingControls(); 										//Deactivate any existing controls
	if(selFeatureControl != null){
		selFeatureControl.deactivate();									//Ensure select feature control active
	}
	if (toolType=='drawline'){																
		if(document.drawline.src.indexOf('images/drawline_on.png') != -1){		//If drawing tool already selected turn off and reset
			document.varform.selectedTool.value = "";							//Store the selected tool							
			eval("document.drawline.src = 'images/drawline.png'");
			drawAnnoLineControl.deactivate();
			adjustMapExtentOpacity("full");	
		}else{														//Tool needs turning on
			toggleDrawingTools(toolType);
			drawAnnoLineControl.activate();
		}	
	}else if (toolType=='drawarrow'){
		if(document.drawarrow.src.indexOf('images/drawarrow_on.png') != -1){		//If drawing tool already selected turn off and reset
			document.varform.selectedTool.value = "";							//Store the selected tool							
			eval("document.drawarrow.src = 'images/drawarrow.png'");
			drawAnnoLineControl.deactivate();
			adjustMapExtentOpacity("full");	
		}else{														//Tool needs turning on
			toggleDrawingTools(toolType);
			drawAnnoLineControl.activate();
		}	
	}else if (toolType=='drawpoly'){
		if(document.drawpoly.src.indexOf('images/drawpoly_on.png') != -1){		//If drawing tool already selected turn off and reset
			document.varform.selectedTool.value = "";							//Store the selected tool							
			eval("document.drawpoly.src = 'images/drawpoly.png'");
			drawAnnoPolyControl.deactivate();
			adjustMapExtentOpacity("full");	
		}else{														//Tool needs turning on
			toggleDrawingTools(toolType);
			drawAnnoPolyControl.activate();
		}	
	}else if (toolType=='drawcircle'){
		if(document.drawcircle.src.indexOf('images/drawcircle_on.png') != -1){		//If drawing tool already selected turn off and reset
			document.varform.selectedTool.value = "";							//Store the selected tool							
			eval("document.drawcircle.src = 'images/drawcircle.png'");
			drawAnnoCircleControl.deactivate();
			drawAnnoLabelControl.deactivate();
			adjustMapExtentOpacity("full");	
		}else{														//Tool needs turning on
			toggleDrawingTools(toolType);
			drawAnnoLabelControl.activate();
		}		
	}else if (toolType=='drawrect'){
		if(document.drawrect.src.indexOf('images/drawrect_on.png') != -1){		//If drawing tool already selected turn off and reset
			document.varform.selectedTool.value = "";							//Store the selected tool							
			eval("document.drawrect.src = 'images/drawrect.png'");
			drawAnnoRectControl.deactivate();
			drawAnnoLabelControl.deactivate();
			adjustMapExtentOpacity("full");	
		}else{														//Tool needs turning on
			toggleDrawingTools(toolType);	
			drawAnnoLabelControl.activate();
		}
	}else if (toolType=='drawlabel'){
		if(document.drawlabel.src.indexOf('images/drawlabel_on.png') != -1){		//If drawing tool already selected turn off and reset
			document.varform.selectedTool.value = "";							//Store the selected tool							
			eval("document.drawlabel.src = 'images/drawlabel.png'");
			drawAnnoLabelControl.deactivate();
			adjustMapExtentOpacity("full");	
		}else{														//Tool needs turning on
			toggleDrawingTools(toolType);
			drawAnnoLabelControl.activate();
		}	
	}else if ((toolType=='selarea') || (toolType=='selarea2')){
		//Check if we can use these tools
		if(mmLayer.getVisibility()){			//If MasterMap showing
			//toggleDrawingTools(toolType);
			if(toolType == 'selarea'){
				if(document.selarea.src.indexOf('images/selarea_on.png') != -1){		//If drawing tool already selected turn off and reset
					document.varform.selectedTool.value = "";							//Store the selected tool							
					eval("document.selarea.src = 'images/selarea.png'");
					drawCapturePointControl.deactivate();
					adjustMapExtentOpacity("full");	
				}else{														//Tool needs turning on
					toggleDrawingTools(toolType);
					drawCapturePointControl.activate();				//Activate the point capture tool
				}			
			}else{
				if(document.selarea2.src.indexOf('images/selarea2_on.png') != -1){		//If drawing tool already selected turn off and reset
					document.varform.selectedTool.value = "";							//Store the selected tool							
					eval("document.selarea2.src = 'images/selarea2.png'");
					drawCapturePolyControl.deactivate();
					adjustMapExtentOpacity("full");	
				}else{														//Tool needs turning on
					toggleDrawingTools(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=='selusershape'){					//Select and reshape		
		if(document.selusershape.src.indexOf('images/selusershape_on.png') != -1){		//If drawing tool already selected turn off and reset
			document.varform.selectedTool.value = "";							//Store the selected tool							
			eval("document.selusershape.src = 'images/selusershape.png'");
			modifyAnnoControl.deactivate();
			adjustMapExtentOpacity("full");	
		}else{														//Tool needs turning on
			if(selFeatureControl != null){
				selFeatureControl.deactivate();										//Ensure select feature control active
			}	
			toggleDrawingTools(toolType);	
			modifyAnnoControl.mode = OpenLayers.Control.ModifyFeature.DRAG;
			modifyAnnoControl.mode |= OpenLayers.Control.ModifyFeature.RESHAPE;
			modifyAnnoControl.activate();
		}	
	}else if (toolType=='resizeusershape'){					//Select and resize
		if(document.resizeusershape.src.indexOf('images/resizeusershape_on.png') != -1){		//If drawing tool already selected turn off and reset
			document.varform.selectedTool.value = "";							//Store the selected tool							
			eval("document.resizeusershape.src = 'images/resizeusershape.png'");
			modifyAnnoControl.deactivate();
			adjustMapExtentOpacity("full");	
		}else{														//Tool needs turning on
			if(selFeatureControl != null){
				selFeatureControl.deactivate();										//Ensure select feature control active
			}	
			toggleDrawingTools(toolType);	
			modifyAnnoControl.mode = OpenLayers.Control.ModifyFeature.RESIZE;
			modifyAnnoControl.mode |= OpenLayers.Control.ModifyFeature.RESHAPE;
			modifyAnnoControl.activate();
		}	
	}		 
}
//***************Toggles the state of the drawing tools
function toggleDrawingTools(toolToShow){
	var drawingTools = new Array("drawline","drawarrow","drawpoly","drawcircle","drawlabel","selarea","selusershape","drawrect","selarea2","resizeusershape");	
	//Turn on or off the clicked on tool
	for(d=0;d<drawingTools.length;d++){
		if(toolToShow == drawingTools[d]){																		
			eval("document." + drawingTools[d] + ".src = 'images/" + drawingTools[d] + "_on.png'");
			eval("document.varform.selectedTool.value = '" + drawingTools[d] + "'");							//Store the selected tool							
		}else{
			eval("document." + drawingTools[d] + ".src = 'images/" + drawingTools[d] + ".png'");
		}			
	}			
}
//****************Deactivate any existing controls
function deactivateDrawingControls(){
	modifyControl.deactivate();
	modifyAnnoControl.deactivate();
	drawPolyControl.deactivate();
	drawPointControl.deactivate();
	drawAnnoPolyControl.deactivate();
	drawAnnoLineControl.deactivate();
	drawAnnoRectControl.deactivate();
	drawAnnoCircleControl.deactivate();
	drawAnnoLabelControl.deactivate();
}
//****************Store info (in hidden) about an added anno element and applies an ID to it
function storeUserAnno(annoType,passedLabel){
	//Get the current feature (last one added)
	var nofeatures = annoLayer.features.length
	var thecurrentFeature = annoLayer.features[nofeatures-1];
	//Apply and store the ID and count of features of the differing type
	if(annoType == "poly"){
		if(document.varform.noUserPolys.value == ""){
			var noUserPolys = 0;
		}else{	
			var noUserPolys = Number(eval("document.varform.noUserPolys.value"));
		}					
		var newID = "userpoly" + String(noUserPolys + 1);
		document.varform.noUserPolys.value = String(noUserPolys+1);
	}else if((annoType == "line") || (annoType == "arrow")){			
		if(document.varform.noUserLines.value == ""){
			var noUserLines = 0;
		}else{	
			var noUserLines = Number(eval("document.varform.noUserLines.value"));
		}					
		var newID = "userline" + String(noUserLines + 1);
		document.varform.noUserLines.value = String(noUserLines+1);		
	}else if(annoType == "rect"){
		if(document.varform.noUserRects.value == ""){
			var noUserRects = 0;
		}else{	
			var noUserRects = Number(document.varform.noUserRects.value);
		}					
		var newID = "userrect" + String(noUserRects + 1);
		document.varform.noUserRects.value = String(noUserRects+1);
	}else if(annoType == "circle"){			
		if(document.varform.noUserCircles.value == ""){
			var noUserCircles = 0;
		}else{	
			var noUserCircles = Number(document.varform.noUserCircles.value);
		}					
		var newID = "usercirc" + String(noUserCircles + 1);
		document.varform.noUserCircles.value = String(noUserCircles+1);
	}else if(annoType == "label"){
		if(document.varform.noUserLabels.value == ""){
			var noUserLabels = 0;
		}else{	
			var noUserLabels = Number(document.varform.noUserLabels.value);
		}					
		var newID = "userlabs" + String(noUserLabels + 1);
		document.varform.noUserLabels.value = String(noUserLabels+1);
	}	
	//Apply the ID
	thecurrentFeature.attributes.id = newID;		
	//Apply a default style 
	defAnnoStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
	defAnnoStyle.graphicOpacity = 1;	
	defAnnoStyle.fillOpacity = 0.3;	
	defAnnoStyle.fillColor = "#FF0000";
	defAnnoStyle.strokeWidth = 2;	
	defAnnoStyle.strokeDashstyle = "none";
	defAnnoStyle.strokeColor = "#FF0000";
	defAnnoStyle.pointerEvents = "visiblePainted";
	if(annoType == "label"){
		if(passedLabel == ""){
			passedLabel = "My Text Label";
		}
		defAnnoStyle.label = passedLabel;
	}else{
		defAnnoStyle.label = ""; 
	}
	if(is_ie){
		defAnnoStyle.cursor = "hand";	
	}else{
		defAnnoStyle.cursor = "pointer";
	}	
	defAnnoStyle.fontColor = "#2A0000";
	defAnnoStyle.fontSize = "18px";
	defAnnoStyle.fontFamily = "Arial";	
	defAnnoStyle.labelSelect = true;  		
	//defAnnoStyle.externalGraphic = 'http://shop.centremapslive.co.uk/ljtest/images/test.gif';
	//defAnnoStyle.graphicHeight = 18;
	//defAnnoStyle.graphicWidth = 200; //117; //13 * 18 100;   chars * 0.5 point size
	//defAnnoStyle.labelXOffset = 5;
	//defAnnoStyle.labelYOffset = 5;	
	defAnnoStyle.labelAlign = "lb";   
	if(is_ie7down == false){	
		defAnnoStyle.labelPadding = "3px";
		defAnnoStyle.labelBackgroundColor = "#ffffff";
		defAnnoStyle.labelBorderColor= "#2A0000";
		defAnnoStyle.labelBorderSize= "1px"; 
	}
	defAnnoStyle.graphicName = "cross"; 
	defAnnoStyle.pointRadius = 0; 	
	thecurrentFeature.style = defAnnoStyle;
	if(annoType == "arrow"){		//If an arrow draw the arrow head
		drawArrowHead("end",thecurrentFeature,newID,"FF0000");
	}
	annoLayer.redraw();	
}

//-------------------------------------------------------------------------SHOW ANNO SPEC
//******************Show styling attributes of the user anno in the attributes area when feature selected
function onFeatureSelect(){
	adjustMapExtentOpacity("fade");									//Knock back map extents
	var theSelectedFeature = getTheSelectedAnnoShape();				//Get the selected feature	
	if(theSelectedFeature != null){					
		//Define the type of attribute area to show (based on id of selected feature)
		var theSelectedFeatureID = theSelectedFeature.attributes.id;
		if(theSelectedFeatureID.indexOf("userline") == 0){
			showAnnoProperties("editline");
		}else if(theSelectedFeatureID.indexOf("userpoly") == 0){ 
			showAnnoProperties("editpoly");
		}else if(theSelectedFeatureID.indexOf("userrect") == 0){
			showAnnoProperties("editrect");
		}else if(theSelectedFeatureID.indexOf("usercirc") == 0){
			showAnnoProperties("editcircle");
		}else if(theSelectedFeatureID.indexOf("userlabs") == 0){
			showAnnoProperties("edittext");
		}			
	}
}
//******************Hide styling attributes of the user anno in the attributes area when feature unselected
function onFeatureUnselect(){
	showAnnoProperties("spacing"); 
	adjustMapExtentOpacity("full");
}
//****************Get the relevant anno properties content
function showAnnoProperties(turnOn){
	if(turnOn != "spacing"){
		var subTurnOn = turnOn;																
		if((turnOn == "editcircle") || (turnOn == "editrect")){				//If a circle or rect this needs to be sub area to turn on within the poly options		
			var turnOn = "editpoly";
		}
		var qstring = "turnon=" + turnOn + "&subturnon=" + subTurnOn;		
		var getAnnoProperties = new ajaxObject('annoProperties.php', getAnnoPropertiesResponse);
		getAnnoProperties.update(qstring,'POST');
	}else{															//Just clear the properties area.
		document.getElementById("annoProperties").innerHTML = "";
		document.getElementById("annoProperties").style.display = "none";
	}	
}
//****************Response from getting anno properties content
function getAnnoPropertiesResponse(responseText, responseStatus){
	if(responseStatus == 200){
		//Show anno properties info area and make visible
		document.getElementById("annoProperties").innerHTML = responseText;
		document.getElementById("annoProperties").style.display = "block";
		callCufon();													//Run cufon styling
		//Get the selected feature's style and show it
		var theSelectedFeature = getTheSelectedAnnoShape();	
		if(theSelectedFeature != null){	
			//Get selected feature's id and geometry
			var theSelFeatureGeometry = theSelectedFeature.geometry;
			var theSelectedFeatureID = theSelectedFeature.attributes.id;
			var theSelectedFeatureStyle = theSelectedFeature.style;		
			//Store the current style of the selected feature
			//Outline
			var arrowStyle = getArrowStyle(theSelectedFeatureID);				//Get arrowheads (if any)	
			if(arrowStyle == "both"){
				var theOutline = "both";
				var theOutlineColour = theSelectedFeatureStyle.strokeColor;
			}else if(arrowStyle == "start"){
				var theOutline = "start";
				var theOutlineColour = theSelectedFeatureStyle.strokeColor;
			}else if(arrowStyle == "end"){
				var theOutline = "end";
				var theOutlineColour = theSelectedFeatureStyle.strokeColor;
			}else if(theSelectedFeatureStyle.strokeWidth == 0){						//No outline
				var theOutline = "none";
				var theOutlineColour = "none";				
			}else if(theSelectedFeatureStyle.strokeDashstyle == "none"){			//Solid outline
				var theOutline = "solid";
				var theOutlineColour = theSelectedFeatureStyle.strokeColor;
			}else{																//Dash outline
				var theOutline = "dash";
				var theOutlineColour = theSelectedFeatureStyle.strokeColor;
			}	
			//Fill
			if(theSelectedFeatureStyle.fillOpacity == 0){						//None
				var theFill = "none";
				var theColour = "none";
			}else if(theSelectedFeatureStyle.fillOpacity != 0){					//Transparent
				var theFill = "trans";
				var theColour = theSelectedFeatureStyle.fillColor;
			}	
			//Label
			var labelString = theSelectedFeatureStyle.label;
			var theLabColour = theSelectedFeatureStyle.fontColor;		
			//Show attribute area based on the user anno type
			if(theSelectedFeatureID.indexOf("userline") == 0){
				showLineSpec(theOutlineColour,theOutline,theSelFeatureGeometry,theSelectedFeatureID);
			}else if((theSelectedFeatureID.indexOf("userpoly") == 0) || (theSelectedFeatureID.indexOf("userrect") == 0) || (theSelectedFeatureID.indexOf("usercirc") == 0)){ 
				showPolySpec(theColour,theOutline,theOutlineColour,theFill,theSelFeatureGeometry,theSelectedFeatureID);
			}else if(theSelectedFeatureID.indexOf("userlabs") == 0){
				showTextSpec(labelString,theLabColour);
				//Show note about label backgrounds for IE7 and lower
				if(is_ie7down){
					document.getElementById("ieLabMessage").innerHTML = "Please note the label background cannot be previewed on the interface using this browser. On the final output your labels will be drawn with a white background.";
				}
			}	
		}	
	}
}
//***********************Display spec of polygon features in the attributes area
function showPolySpec(theColour,theOutline,theOutlineColour,theFill,theSelFeatureGeometry,theSelectedFeatureID){ 
	//Set the fill colour
	if(theColour != "none"){	
		var layer = document.getElementById("pol_currentcolour");
		layer.style.backgroundColor = theColour; 											
	}	
	//Set the outline colour
	if(theOutlineColour	!= "none"){		 
		var layer = document.getElementById("out_currentcolour");
		layer.style.backgroundColor = theOutlineColour; 														
	}	
	//Set the outline style	
	for(c=0;c<3;c++){
		var selectedStyle = eval('document.annoform.theOutlineStyle.options[' + c + '].value');
		if(selectedStyle == theOutline){
			eval('document.annoform.theOutlineStyle.options[' + c + '].selected = true');
		}	
	}
	//Set the fill style
	for(c=0;c<2;c++){
		var selectedStyle = eval('document.annoform.theFillStyle.options[' + c + '].value');
		if(selectedStyle == theFill){
			eval('document.annoform.theFillStyle.options[' + c + '].selected = true');
		}	
	}
	//Calculate area of shape and display to user
	var areaString = getAnnoShapeArea(theSelFeatureGeometry);
	if(areaString != ""){
		document.annoform.polyArea.value = areaString;	
	}
	//If rectangle or circle update the rectangle size and radius
	if(theSelectedFeatureID.indexOf("userrect") == 0){
		var shapeBounds = theSelFeatureGeometry.getBounds().toBBOX();
		var shapeBoundsArray = shapeBounds.split(",");
		var rectHeight = Number(shapeBoundsArray[3]) - Number(shapeBoundsArray[1]);
		var rectWidth = Number(shapeBoundsArray[2]) - Number(shapeBoundsArray[0]);
		document.annoform.rectx.value = rectWidth;
		document.annoform.recty.value = rectHeight;
	}else if(theSelectedFeatureID.indexOf("usercirc") == 0){				
		var shapeBounds = theSelFeatureGeometry.getBounds().toBBOX();
		var shapeBoundsArray = shapeBounds.split(",");
		var theRadius = (Number(shapeBoundsArray[2]) - Number(shapeBoundsArray[0])) / 2;
		document.annoform.userrad.value = theRadius;
	}	
	//Clear buffer values
	document.annoform.userbuf.value = "";
	document.getElementById("bufferMessage").innerHTML = "<p class='error'>No Current Selected Buffers</p>";
}
//************************Display spec of polygon features in the attributes area
function showLineSpec(theColour,theOutline,theSelFeatureGeometry,theSelectedFeatureID){
	//Colour
	var layer = document.getElementById("lin_currentcolour");
	layer.style.backgroundColor = theColour; 											
	for(c=0;c<5;c++){
		var selectedStyle = eval('document.annoform.theLineStyle.options[' + c + '].value');
		if(selectedStyle == theOutline){
			eval('document.annoform.theLineStyle.options[' + c + '].selected = true');
		}	
	}		
	//Calculate length of the line and display to user
	var lengthString = getLineLength(theSelFeatureGeometry);	
	if(lengthString != ""){
		document.annoform.lineLen.value = lengthString;	
	}
}
//***********************Display spec of label feature in the editing pane
function showTextSpec(labelString,theColour){
	document.annoform.usertextlab.value = labelString; 				//Label
	//Colour
	var layer = document.getElementById("lab_currentcolour");
	layer.style.backgroundColor = theColour; 													
}
//***********************Get the area of the passed user anno shap
function getLineLength(theSelFeatureGeometry){
	//Define the area in the selected unit
	var lineLen = theSelFeatureGeometry.getLength();
	var selectedUnit = document.annoform.lineLenUnit.options[document.annoform.lineLenUnit.selectedIndex].value;
	if(selectedUnit == "km"){
		var lengthToPass = String(Math.round((lineLen / 1000)*100)/100) + " km";	
	}else{
		var lengthToPass = String(Math.round(lineLen * 100)/100) + " m";
	}
	return lengthToPass;	
}
//***********************Get the area of the passed user anno shape
function getAnnoShapeArea(theSelFeatureGeometry){
	//Define the area in the selected unit
	var theArea = theSelFeatureGeometry.getArea();
	var selectedUnit = document.annoform.polyAreaUnit.options[document.annoform.polyAreaUnit.selectedIndex].value;
	if(selectedUnit == "km"){
		var extentAreaKm = theArea / 1000000;
		var areaToPass = String(Math.round(extentAreaKm * 100)/100) + " sqkm";
	}else if(selectedUnit == "ha"){
		var areaToPass = String(Math.round((theArea / 10000)* 100)/100) + " ha";
	}else if(selectedUnit == "a"){
		var areaToPass = String(Math.round(((theArea / 10000) * 2.47105381)* 100)/100) + " ac";	
	}else{
		var areaToPass = String(Math.round(theArea * 100)/100) + " sqm";
	}
	return areaToPass;	
}
//************************Highlights the colour in the colour picker when mouseovered
function hiliteColour(theNo,thePreFix){
	theCol = thePreFix + "_colour" + theNo;
	for (var n=0;n<12;n++){	
		var theObj = document.getElementById((thePreFix + "_colour" + String(n+1)));		
		if((thePreFix + "_colour" + String(n+1)) == theCol){
			theObj.style.borderWidth = "2px";
			theObj.style.borderStyle = "solid";
			theObj.style.borderColor = "#000000";			
		}else{
			theObj.style.borderStyle = "none";			
		}										
	}
}

//-------------------------------------------------------------------------GENERAL ANNO EDITING
//******************Delete the selected annotation feature
function deleteFeatures(theMethod,deleteIt){	
	if(theMethod == "all"){
		if(deleteIt == false){														//Prompt user
			//var answer = confirm ("Do you want to delete all features?");			//Prompt user
			var dialogContent = "Do you want to delete all features?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='deleteFeatures(\"all\",true);'>  <input type='button' value='No' id='noButton' onclick=' hideDialog();' >"
			showDialog('',dialogContent,'prompt');
		}else if(deleteIt){
			hideDialog();			
			annoLayer.destroyFeatures();			//Delete all features from the layer
			updateAnnoIDs("","all");				//Clear any stored anno info
		}
	}else if(theMethod == "selected"){
		if(deleteIt == false){														//Prompt user
			var dialogContent = "Do you want to delete the selected feature?<br/><br/><input type='button' value='Yes' id='yesButton' onclick='deleteFeatures(\"selected\",true);'>  <input type='button' value='No' id='noButton' onclick='hideDialog();' >"
			showDialog('',dialogContent,'prompt');
		}else if(deleteIt){		
			hideDialog();
			//Get the selected feature
			var theSelectedFeature = getTheSelectedAnnoShape();	
			if(theSelectedFeature != null){
				var theSelFeatureGeometry = theSelectedFeature.geometry;	
				var theSelFeatureID = theSelectedFeature.attributes.id;
				modifyAnnoControl.deactivate();
				modifyAnnoControl.activate();
				//Delete the feature 
				var nofeatures = annoLayer.features.length
				for(p=0; p < nofeatures;p++){
					var theFeatureGeometry = annoLayer.features[p].geometry;
					if(theFeatureGeometry == theSelFeatureGeometry){
						annoLayer.removeFeatures(annoLayer.features[p])
						updateAnnoIDs(theSelFeatureID,"selected");				//Clear any stored anno info	
						break;
					}
				}
			}	
		}
	}
}
//***********************Updates the area value when the user changes the display unit.
function updateAreaValue(){	
	var theSelectedFeature = getTheSelectedAnnoShape();			//Get the selected feature
	if(theSelectedFeature != null){
		var theSelFeatureGeometry = theSelectedFeature.geometry;
		var areaString = getAnnoShapeArea(theSelFeatureGeometry);
		if(areaString != ""){
			document.annoform.polyArea.value = areaString;	
		}
	}
}
//***********************Updates the line length value when the user changes the display unit.
function updateLengthValue(){
	var theSelectedFeature = getTheSelectedAnnoShape();					//Get the selected feature
	if(theSelectedFeature != null){	
		var theSelFeatureGeometry = theSelectedFeature.geometry;
		var lengthString = getLineLength(theSelFeatureGeometry);
		if(lengthString != ""){
			document.annoform.lineLen.value = lengthString;	
		}
	}
}
//***********************Get the current selected user anno shape
function getTheSelectedAnnoShape(){
	var theSelectedFeature = null;
	var noSelected = annoLayer.selectedFeatures.length;
	for(p=0; p < noSelected;p++){
		theSelectedFeature = annoLayer.selectedFeatures[p];	
	}
	return theSelectedFeature;
}
//****************Update the ids of anno features when a feature is deleted
function updateAnnoIDs(annoType,deleteType){
	if(deleteType == "all"){									//Reset the number of stored annotations for all types
		document.varform.noUserPolys.value = "";
		document.varform.noUserLines.value = "";
		document.varform.noUserRects.value = "";
		document.varform.noUserLabels.value = "";
		document.varform.noUserCircles.value = "";	
	}else if(deleteType == "selected"){							//Reset the number of stored annotations for passed types
		//Apply and store the ID and count of features of the differing type
		if(annoType.indexOf("userpoly") == 0){
			if(document.varform.noUserPolys.value == ""){
				var noUserPolys = 0;
			}else{	
				var noUserPolys = Number(eval("document.varform.noUserPolys.value"));
			}					
			var newID = "userpoly" + String(noUserPolys - 1);
			document.varform.noUserPolys.value = String(noUserPolys-1);
		}else if(annoType.indexOf("userline") == 0){			
			if(document.varform.noUserLines.value == ""){
				var noUserLines = 0;
			}else{	
				var noUserLines = Number(eval("document.varform.noUserLines.value"));
			}					
			var newID = "userline" + String(noUserLines - 1);
			document.varform.noUserLines.value = String(noUserLines-1);	
		}else if(annoType.indexOf("userrect") == 0){
			if(document.varform.noUserRects.value == ""){
				var noUserRects = 0;
			}else{	
				var noUserRects = Number(document.varform.noUserRects.value);
			}					
			var newID = "userrect" + String(noUserRects - 1);
			document.varform.noUserRects.value = String(noUserRects-1);
		}else if(annoType.indexOf("usercirc") == 0){			
			if(document.varform.noUserCircles.value == ""){
				var noUserCircles = 0;
			}else{	
				var noUserCircles = Number(document.varform.noUserCircles.value);
			}					
			var newID = "usercirc" + String(noUserCircles - 1);
			document.varform.noUserCircles.value = String(noUserCircles-1);
		}else if(annoType.indexOf("userlabs") == 0){
			if(document.varform.noUserLabels.value == ""){
				var noUserLabels = 0;
			}else{	
				var noUserLabels = Number(document.varform.noUserLabels.value);
			}					
			var newID = "userlabs" + String(noUserLabels - 1);
			document.varform.noUserLabels.value = String(noUserLabels-1);
		}				
		//Reassign the ids
		var nofeatures = annoLayer.features.length
		for(c=0; c <= nofeatures; c++){
			var theAnnoFeature = annoLayer.features[c];
			var theCurrentID = theAnnoFeature.attributes.id;
			var thePrefix = theCurrentID.substring(0, 8);
			theCurrentID = Number(theCurrentID.substring(8, theCurrentID.length));			
			if(theCurrentID > nofeatures){		
				theAnnoFeature.attributes.id = thePrefix + String(theCurrentID - 1);
			}		
		}
		//Redraw to apply updates
		annoLayer.redraw();	
	}
}
//************************Changes the colour of the selected user anno shape (fill for polys, stroke for lines)
function changeColour(newColour,thePreFix){
	//Change in the editing window
	var layer = document.getElementById(thePreFix + '_currentcolour');											
	layer.style.backgroundColor = newColour;	
	//Get the selected feature
	var theSelectedFeature = getTheSelectedAnnoShape();
	if((thePreFix == "lin")){												//Change the stroke (line and arrow)
		theSelectedFeature.style.strokeColor = newColour;
		//Check if the arrow head colour needs updating
		var updateArrowHeads = false;
		var theSelectedFeatureID = theSelectedFeature.attributes.id;
		var nofeatures = annoLayer.features.length
		for(p=0; p < annoLayer.features.length;p++){
			var theIDtoTest = annoLayer.features[p].attributes.id;
			if((theIDtoTest == (theSelectedFeatureID+"a")) || (theIDtoTest == (theSelectedFeatureID+"b"))){
				updateArrowHeads = true;		
			}
		}	
		if(updateArrowHeads){
			var passedNewColour = newColour.substring(1,newColour.length);
			updateArrowStyle(theSelectedFeatureID,passedNewColour);
		}	
		annoLayer.redraw();	
	}else if(thePreFix == "out"){											//Change the stroke (poly features)		
		theSelectedFeature.style.strokeColor = newColour;
		annoLayer.redraw();
	}else if(thePreFix == "lab"){											//Change the label colour					
		theSelectedFeature.style.fontColor = newColour;
		if(is_ie7down == false){											//Can't show border for <=IE7	
			theSelectedFeature.style.labelBorderColor = newColour;
		}
		annoLayer.redraw();			
	}else{												     				//Change the fill (poly features or text colour)
		theSelectedFeature.style.fillColor = newColour;
		annoLayer.redraw();		
	}
	annoLayer.redraw();
}
//************************Changes the fill style of the selected  user anno shape
function changeFillStyle(selObj){	
	var selectedStyle = selObj.options[selObj.selectedIndex].value;  		//Get the selected style (none, trans, hatch)	
	var theSelectedFeature = getTheSelectedAnnoShape();						//Get the selected feature	
	if(selectedStyle == "none"){											
		theSelectedFeature.style.fillOpacity = 0;				
		annoLayer.redraw();			
	}else if(selectedStyle == "trans"){
		theSelectedFeature.style.fillOpacity = 0.3;
		annoLayer.redraw();		
	}else if(selectedStyle == "hatch"){				//Not called		
		//Cannot define hatch fill in Openlayers
	}			
}
//************************Changes the line style of the selected  user anno shape
function changeLineStyle(selObj){	
	//Get the selected style (dash, solid, none)
	var selectedStyle = selObj.options[selObj.selectedIndex].value;
	//Get the selected feature
	var theSelectedFeature = getTheSelectedAnnoShape();
	var theSelectedFeatureID = theSelectedFeature.attributes.id;		
	//Remove the existing arrow heads		
	removeArrowHeads(theSelectedFeatureID);				
	if(selectedStyle == "dash"){					
		theSelectedFeature.style.strokeDashstyle = "dash";
		theSelectedFeature.style.strokeWidth = 2;
		annoLayer.redraw();	
	}else if(selectedStyle == "solid"){
		theSelectedFeature.style.strokeDashstyle = "none";
		theSelectedFeature.style.strokeWidth = 2;
		annoLayer.redraw();
	}else if(selectedStyle == "none"){
		theSelectedFeature.style.strokeDashstyle = "none";
		theSelectedFeature.style.strokeWidth = 0
		annoLayer.redraw();	
	}else if((selectedStyle == "end") || (selectedStyle == "start") || (selectedStyle == "both")){
		theSelectedFeature.style.strokeDashstyle = "none";
		var passedStrokeColour = theSelectedFeature.style.strokeColor.substring(1,theSelectedFeature.style.strokeColor.length);		
		drawArrowHead(selectedStyle,theSelectedFeature,theSelectedFeatureID,passedStrokeColour);		//Draw arrow heads	
	}			
}
//***********************Updates selected circle user shape with the new radius value 
function updateUserCircle(){
	//Get user entered radius
	var newRadius = Number(eval("document.annoform.userrad.value"));					
	if((newRadius != 0) && (isNaN(newRadius) == false)){
		//Get the selected feature
		var theSelectedFeature = getTheSelectedAnnoShape();
		if(theSelectedFeature != null){	
			//Define the scale fator and scale
			var theSelFeatureGeometry = theSelectedFeature.geometry;
			var theCentrePoint = theSelFeatureGeometry.getCentroid();	
			var theOldRadius = (theSelFeatureGeometry.getBounds().getWidth())/2;
			var theScaleFactor = newRadius/theOldRadius;
			theSelectedFeature.geometry.resize(theScaleFactor,theCentrePoint,1);
			annoLayer.redraw();
		}		
	}
}
//***********************Updates selected rectangle user shape with the new width/height values 
function updateUserRect(){
	//Get user entered width-height
	var newWidth = Number(eval("document.annoform.rectx.value"));				
	var newHeight = Number(eval("document.annoform.recty.value"));				
	if((newWidth != 0) && (newHeight != 0) && (isNaN(newHeight) == false) && (isNaN(newWidth) == false)){
		//Get the selected feature
		var theSelectedFeature = getTheSelectedAnnoShape();
		if(theSelectedFeature != null){	
			var theSelFeatureGeometry = theSelectedFeature.geometry;
			//Define the move distances on x and y axis
			var oldWidth = theSelFeatureGeometry.getBounds().getWidth();
			var oldHeight = theSelFeatureGeometry.getBounds().getHeight();
			var dx = newWidth-oldWidth;
			var dy = newHeight-oldHeight;	
			var moveX = dx/2;
			var moveY = dy/2;
			
			//Define max-min coordinates of the shape
			var theVertices = theSelFeatureGeometry.getVertices();
			for(v=0;v < theVertices.length;v++){ 
				if(v==0){
					var minX = theVertices[v].x;
					var minY = theVertices[v].y;
					var maxX = theVertices[v].x;
					var maxY = theVertices[v].y;	
				}else{
					if(theVertices[v].x < minX){minX = theVertices[v].x}
					if(theVertices[v].y < minY){minY = theVertices[v].y}
					if(theVertices[v].x > maxX){maxX = theVertices[v].x}
					if(theVertices[v].y > maxY){maxY = theVertices[v].y}
				}	
			}
			//Move the vertices
			for(v=0;v < theVertices.length;v++){ 
				if((theVertices[v].x == minX) && (theVertices[v].y == minY)){;		//BL
					var toMoveX = moveX * -1;
					var toMoveY = moveY * -1;
					theVertices[v].move(toMoveX,toMoveY);
				}
				if((theVertices[v].x == minX) && (theVertices[v].y == maxY)){;		//TL
					var toMoveX = moveX * -1;
					var toMoveY = moveY;
					theVertices[v].move(toMoveX,toMoveY);
				}
				if((theVertices[v].x == maxX) && (theVertices[v].y == minY)){;		//BR
					var toMoveX = moveX;
					var toMoveY = moveY * -1;
					theVertices[v].move(toMoveX,toMoveY);
				}
				if((theVertices[v].x == maxX) && (theVertices[v].y == maxY)){;		//TR
					var toMoveX = moveX;
					var toMoveY = moveY;
					theVertices[v].move(toMoveX,toMoveY);
				}
			}
			annoLayer.redraw();
		}		
	}	
}
//***********************Draw the annotation circle based on centre and default width
function drawCircleByCentre(thePassedPoint){
	var theCX = thePassedPoint.x;
	var theCY = thePassedPoint.y;
	var theRad = map.getExtent().getWidth() / 20;
	//Define the coordinate string
	var pointList = []; 
	var theX; 
	var theY;
	for (i=0;i<72;i++){
		//theX = (Math.round(((Math.cos((i*5)*(Math.PI/180)))*theRad)))  + theCX;
		//theY = (Math.round(((Math.sin((i*5)*(Math.PI/180)))*theRad)))  + theCY;
		theX = (((Math.cos((i*5)*(Math.PI/180)))*theRad))  + theCX;
		theY = (((Math.sin((i*5)*(Math.PI/180)))*theRad))  + theCY;
		var newPoint = new OpenLayers.Geometry.Point(theX,theY);
		pointList.push(newPoint)
	}			
	theX = (((Math.cos((i*5)*(Math.PI/180)))*theRad)) + theCX;
	theY = (((Math.sin((i*5)*(Math.PI/180)))*theRad)) + theCY;
	var newPoint = new OpenLayers.Geometry.Point(theX,theY);
	pointList.push(newPoint)						
	var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
	theNewFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);	
	annoLayer.addFeatures(theNewFeature);		
}
//***********************Draw the annotation rectangle based on centre and default width
function drawRectByCentre(thePassedPoint){
	var theCX = thePassedPoint.x;
	var theCY = thePassedPoint.y;
	var theRad = map.getExtent().getWidth() / 20;
	//Define the coordinate string
	var pointList = []; 
	var newPoint = new OpenLayers.Geometry.Point((theCX - theRad),(theCY - theRad));
	pointList.push(newPoint)
	var newPoint = new OpenLayers.Geometry.Point((theCX - theRad),(theCY + theRad));
	pointList.push(newPoint)			
	var newPoint = new OpenLayers.Geometry.Point((theCX + theRad),(theCY + theRad));
	pointList.push(newPoint)
	var newPoint = new OpenLayers.Geometry.Point((theCX + theRad),(theCY - theRad));
	pointList.push(newPoint)
	var newPoint = new OpenLayers.Geometry.Point((theCX - theRad),(theCY - theRad));
	pointList.push(newPoint)					
	var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
	theNewFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);	
	annoLayer.addFeatures(theNewFeature);		
}

//-------------------------------------------------------------------------ARROWS
//***********************Updates the arrow head
function updateArrowStyle(theSelectedFeatureID,passedNewColour){
	for(p=0; p < annoLayer.features.length;p++){
		var theIDtoTest = annoLayer.features[p].attributes.id;
		if((theIDtoTest == (theSelectedFeatureID+"a")) || (theIDtoTest == (theSelectedFeatureID+"b"))){
			annoLayer.features[p].style.externalGraphic = "images/arrows/" + passedNewColour + ".png";		
		}
	}
}
//***********************Define where the arrow heads are on the line
function getArrowStyle(theSelectedFeatureID){
	var arrowStyle = ""														
	for(p1=0; p1 < annoLayer.features.length;p1++){
		var theIDtoTest = annoLayer.features[p1].attributes.id;
		if(theIDtoTest == (theSelectedFeatureID+"b")){
			arrowStyle += "start";
		}
		if(theIDtoTest == (theSelectedFeatureID+"a")){
			arrowStyle += "end";		
		}
	}
	if((arrowStyle == "startend") || (arrowStyle == "endstart")){
		arrowStyle = "both";
	}
	return arrowStyle;
}
//***********************Draws the arrow head (input - arrow sytle(end,start,both),feature,feature id,colour)
function drawArrowHead(selectedStyle,theSelectedFeature,theSelectedFeatureID,passedStrokeColour){   
	//Define the coordinates near the start and end of line with which to generate arrow heads
	var theSelFeatureVertexArray = theSelectedFeature.geometry.getVertices();	
	var firstPoint = theSelFeatureVertexArray[0].clone();	
	if(theSelFeatureVertexArray.length > 2){
		var secondPoint = theSelFeatureVertexArray[1].clone();	
		var penultimatePoint = theSelFeatureVertexArray[theSelFeatureVertexArray.length-2].clone();
	}else{
		var secondPoint = null;	
		var penultimatePoint = null;
	}
	var lastPoint = theSelFeatureVertexArray[theSelFeatureVertexArray.length-1].clone();	
	//--Loop for each head to add
	var arrowHeads = [];
	if(selectedStyle == "both"){
		var toLoop = 2;
	}else{
		var toLoop = 1;
	}
	for(c=0;c<toLoop;c++){
		var angleAdjust = 0;
		if(selectedStyle == "end"){
			if(penultimatePoint == null){
				var dx = firstPoint.x - lastPoint.x;
				var dy = firstPoint.y - lastPoint.y;
			}else{
				var dx = penultimatePoint.x - lastPoint.x;
				var dy = penultimatePoint.y - lastPoint.y;
			}
			if(dx < 0){						//Define adjust angle value
				angleAdjust = 180;	
			}		
			var angleAsRad = Math.atan(dy/dx);
			var headAngle = (angleAsRad * (180/Math.PI));   
			headAngle = headAngle * -1;							//Swap angle to +ve or -ve
			arrowHeads.push(new OpenLayers.Feature.Vector(lastPoint));			
		}else if(selectedStyle == "start"){
			if(secondPoint == null){
				var dx = lastPoint.x - firstPoint.x;
				var dy = lastPoint.y - firstPoint.y;
			}else{
				var dx = secondPoint.x - firstPoint.x;
				var dy = secondPoint.y - firstPoint.y;
			}	
			if(dx < 0){						//Define adjust angle value
				angleAdjust = 180;	
			}
			var angleAsRad = Math.atan(dy/dx);
			var headAngle = (angleAsRad * (180/Math.PI));   	
			headAngle = headAngle * -1;							//Swap angle to +ve or -ve	
		    arrowHeads.push(new OpenLayers.Feature.Vector(firstPoint));	
		}else if(selectedStyle == "both"){
			if(c==0){
				if(penultimatePoint == null){
					var dx = firstPoint.x - lastPoint.x;
					var dy = firstPoint.y - lastPoint.y;		
				}else{
					var dx = penultimatePoint.x - lastPoint.x;
					var dy = penultimatePoint.y - lastPoint.y;
				}
				if(dx < 0){						//Define adjust angle value
					angleAdjust = 180;	
				}
				var angleAsRad = Math.atan(dy/dx);
				var headAngle = angleAsRad * (180/Math.PI);			
				headAngle = headAngle * -1;							//Swap angle to +ve or -ve
				arrowHeads.push(new OpenLayers.Feature.Vector(lastPoint));
			}else{
				if(secondPoint == null){
					var dx = lastPoint.x - firstPoint.x;
					var dy = lastPoint.y - firstPoint.y;
				}else{
					var dx = secondPoint.x - firstPoint.x;
					var dy = secondPoint.y - firstPoint.y;
				}
				if(dx < 0){						//Define adjust angle value
					angleAdjust = 180;	
				}
				var angleAsRad = Math.atan(dy/dx);
				var headAngle = angleAsRad * (180/Math.PI);
				headAngle = headAngle * -1;							//Swap angle to +ve or -ve
				arrowHeads.push(new OpenLayers.Feature.Vector(firstPoint));
			}
		}
		//Add to the layer
		annoLayer.addFeatures(arrowHeads[c]);				
		//Set ID
		if(selectedStyle == "end"){
			var idLetter = "a";
		}else if(selectedStyle == "start"){
			var idLetter = "b";	
		}else{
			if(c==0){
				var idLetter = "b";
			}else{
				var idLetter = "a";
			}
		}
		arrowHeads[c].attributes.id = theSelectedFeatureID + idLetter;					
		//Apply a default style (using current strike colour)	
		if(passedStrokeColour.indexOf("#") == 0){				//Ensure only r-g-b defined
			passedStrokeColour = passedStrokeColour.substring(1,passedStrokeColour.length);
		}	
		defAnnoStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
		defAnnoStyle.externalGraphic = "images/arrows/" + passedStrokeColour + ".png";
		defAnnoStyle.graphicHeight = 20;
		defAnnoStyle.rotation = 90 + headAngle + angleAdjust;	
		arrowHeads[c].style = defAnnoStyle;	
		annoLayer.redraw();	
	}
}
//***********************Delete any displaying arrow heads for the selected feature
function removeArrowHeads(theSelectedFeatureID){
	if(theSelectedFeatureID != ""){
		var nofeatures = annoLayer.features.length
		var featuresToRemove = [];
		for(p=0; p < nofeatures;p++){
			var theIDtoTest = annoLayer.features[p].attributes.id;
			if((theIDtoTest == (theSelectedFeatureID+"a")) || (theIDtoTest == (theSelectedFeatureID+"b"))){
				featuresToRemove.push(annoLayer.features[p]);		
			}
		}	
		for(p=0; p < featuresToRemove.length;p++){
			annoLayer.removeFeatures(featuresToRemove[p]);
		}
	}	
}

//-------------------------------------------------------------------------LABELS
//************************Changes the text of the selected label object
function changeTextLabel(){
	var newLabel = eval("document.annoform.usertextlab.value");				//Get user entered text
	if(newLabel != ""){
		var theSelectedFeature = getTheSelectedAnnoShape();					
		theSelectedFeature.style.label = newLabel;
		annoLayer.redraw();
	}
}
//************************Increases/Decrease the size of the selected label object
function resizeText(theAction){
	var theSelectedFeature = getTheSelectedAnnoShape();					
	var currentSize = theSelectedFeature.style.fontSize;
	if(theAction == "up"){
		currentSize = Number(currentSize.substring(0, (currentSize.length -2))) + 1;
	}else if(theAction == "down"){
		currentSize = Number(currentSize.substring(0, (currentSize.length -2))) - 1;
	}	
	var newFontSize = String(currentSize) + "px";
	theSelectedFeature.style.fontSize = newFontSize;
	annoLayer.redraw();	
}
//***********************Adds shape area or line length as a label
function addAsLabel(){	
	//Get the selected feature	
	var theSelectedFeature = getTheSelectedAnnoShape();					
	var selectedID = theSelectedFeature.attributes.id;
	if(selectedID != ""){				
		//Get the shapeType
		if((selectedID.indexOf("userrect") != -1) || (selectedID.indexOf("usercirc") != -1) || (selectedID.indexOf("userpoly") != -1)){
			var theLabelString = document.annoform.polyArea.value;			
			var theSelFeatureGeometry = theSelectedFeature.geometry;	
			var theCX = theSelFeatureGeometry.getCentroid().x;
			var theCY = theSelFeatureGeometry.getCentroid().y;
			var theTextPoint = theSelFeatureGeometry.getCentroid();
		}else if(selectedID.indexOf("userline") != -1){
			var theLabelString = document.annoform.lineLen.value;				
			var theSelFeatureVertexArray = theSelectedFeature.geometry.getVertices();
			var theTextPoint = theSelFeatureVertexArray[0].clone();
		}
		if(theLabelString != ""){
			var pointFeature = new OpenLayers.Feature.Vector(theTextPoint,null);
			annoLayer.addFeatures(pointFeature);
			storeUserAnno("label",theLabelString);
		}
	}
}

//-------------------------------------------------------------------------SHAPE BUFFERING
//***********************Add or remove the  buffers for the shape (Store on hidden)
function addRemBuffers(theAction){
	//Get the shape ID and buffer values
	var buffValsOK = true;
	var theSelectedFeature = getTheSelectedAnnoShape();					
	var theID = theSelectedFeature.attributes.id;
	if(theAction == "add"){														//If adding get buffer values
		var theBufferValues = document.annoform.userbuf.value;
		//Remove spaces and anything not a number or comma
		var tempValues = "";
		for(c=0;c<theBufferValues.length;c++){
			var achar = theBufferValues.substring(c,(c+1))
			var acsCode = achar.charCodeAt(0);
			if(acsCode == 44){
				tempValues += achar;
			}else if((acsCode >= 48) && (acsCode <= 57)){			
				tempValues += achar;			
			}
		}
		theBufferValues = tempValues;
		document.annoform.userbuf.value = theBufferValues;
		buffValsOK = checkBuffValues(theBufferValues);
		document.getElementById("bufferMessage").innerHTML = "<p><strong>Current Selected Buffers at: " + document.annoform.userbuf.value + " metres</strong></p>";				
	}else{																		//If clearing reset buffer values
	 	document.annoform.userbuf.value = "";
		document.getElementById("bufferMessage").innerHTML = "<p class='error'>No Current Selected Buffers</p>";	
	}
	if((theAction == "add") && (buffValsOK == false)){
		showDialog('Warning','Buffer values have not been entered correctly.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{
		//Get any current stored info
		var theCurrentValues = eval("document.varform.currentBuffers.value");		//id,b1,b2..._id,b1,b2 ......
		if(theCurrentValues != ""){
			var buffString = "";
			var buffArray = theCurrentValues.split("_");							//Store each features values in an array
			//Write existing
			for(c=0;c<buffArray.length;c++){
				var bufferValsArray = buffArray[c].split(",");
				if(bufferValsArray[0] != theID){									//Ignore any previous buffers specified for this shape
					buffString += buffArray[c] + "_";	
				}		
			}
			if(theAction == "add"){
				buffString += theID + "," + theBufferValues;						//Add values for the current shape		
			}else{
				buffString = buffString.substring(0,(buffString.length-1));			//Remove trailing underscore		
			}		
		}else{
			if(theAction == "add"){
				var buffString = theID + "," + theBufferValues;						//Add values for the current shape		
			}else{
				var buffString = "";
			}		
		}
		eval("document.varform.currentBuffers.value='" + buffString + "'");				//Store on hidden.
	}	
}
//**********************Check buffer values entered correctly
function checkBuffValues(theBufferValues){
	var buffValsOK = true;
	var buffArray = theBufferValues.split(",");
	for(c=0;c<buffArray.length;c++){
		if(isNaN(buffArray[c]) == true){
			buffValsOK = false;
			break;
		}
	}
	return buffValsOK;
}
//**********************Get the buffer values for the shape to write to page when a shape is selected
function getBuffers(theID){
	//Search current stored buffers for match with current ID
	var theBufferValues	= "";
	var theCurrentValues = eval("document.varform.currentBuffers.value");		//id,b1,b2..._id,b1,b2 ......	
	if(theCurrentValues != ""){
		var buffArray = theCurrentValues.split("_");
		for(bf=0;bf<buffArray.length;bf++){
			var bufferValsArray = buffArray[bf].split(",");
			if(bufferValsArray[0] == theID){
				for(bf1=1;bf1<bufferValsArray.length;bf1++){
					if(bf1==1){
						theBufferValues += bufferValsArray[bf1];
					}else{
						theBufferValues += "," + bufferValsArray[bf1];
					}	
				}
				break;	
			}		
		}
	}	
	return theBufferValues;			
}

//-------------------------------------------------------------------------STORE USER SHAPES
//***********************Get all the currently drawn shapes
function getAllDrawnShapes(){
	var linCnt = 0;
	var labCnt = 0;
	var polCnt = 0;
	var lineArray = new Array();
	var labelArray = new Array();
	var polyArray = new Array();	
	var nofeatures = annoLayer.features.length	
	for(p=0; p < nofeatures;p++){
		var theFeatureGeometry = annoLayer.features[p].geometry;
		var theFeatureID = annoLayer.features[p].attributes.id;	
		if(theFeatureID != null){
			if((theFeatureID.substring((theFeatureID.length-1),theFeatureID.length) == "a") || (theFeatureID.substring((theFeatureID.length-1),theFeatureID.length) == "a")){
				//Ignore arrow heads
			}else if(theFeatureID.indexOf("userline") == 0){
				if(annoLayer.features[p].attributes.orderitems != ""){				//Store only if associated with a selected product			
					linCnt = linCnt + 1;
					lineArray[linCnt] = new Array(5);						 
					lineArray[linCnt][0] = annoLayer.features[p].style.strokeColor;			//Colour										
					//Get line style 1=solid,2=dash,3=none,4=end,5=start,6=both
					var theArowStyle = getArrowStyle(theFeatureID);							//Arrow style
					var theDash = annoLayer.features[p].style.strokeDashstyle;						
					if(theArowStyle == "both"){						//both
						var outLineStyleNo = 6;
					}else if(theArowStyle == "start"){				//start
						var outLineStyleNo = 5;
					}else if(theArowStyle == "end"){				//end	
						var outLineStyleNo = 4;
					}else if(theDash == "none"){					//solid
						var outLineStyleNo = 1;
					}else{											//dash
						var outLineStyleNo = 2;
					}	
					lineArray[linCnt][1] = outLineStyleNo;
					var geomAsString = String(theFeatureGeometry)			
					lineArray[linCnt][2] = geomAsString.substring(11,(geomAsString.length-1));		//Geometry
					lineArray[linCnt][3] = annoLayer.features[p].style.strokeWidth;					//Stroke width
					lineArray[linCnt][4] = annoLayer.features[p].attributes.orderitems;				//Order items this is associated with
				}
			}else if((theFeatureID.indexOf("userrect") == 0) || (theFeatureID.indexOf("userpoly") == 0) || (theFeatureID.indexOf("usercirc") == 0)){
				if(annoLayer.features[p].attributes.orderitems != ""){				//Store only if associated with a selected product			
					polCnt = polCnt + 1;
					polyArray[polCnt] = new Array(9);		
					var geomAsString = String(theFeatureGeometry)
					polyArray[polCnt][0] = geomAsString.substring(9,(geomAsString.length-2));			//Geometry		
					if(theFeatureID.indexOf("userrect") == 0){
						var shapeType = "rect";
					}else if(theFeatureID.indexOf("userpoly") == 0){
						var shapeType = "poly";		
					}else if(theFeatureID.indexOf("usercirc") == 0){
						var shapeType = "circle";
					}
					var theStroke = annoLayer.features[p].style.strokeColor;
					var theDash = annoLayer.features[p].style.strokeDashstyle;
					var theOpacity = annoLayer.features[p].style.fillOpacity;
					var theFill = annoLayer.features[p].style.fillColor;
					var theStrokeWidth = annoLayer.features[p].style.strokeWidth;					
					if(theStrokeWidth  == 0){
						var outLineStyleNo = "3";
					}else if(theDash == "none"){
						var outLineStyleNo = "1";
					}else{
						var outLineStyleNo = "2";
					}
					polyArray[polCnt][2] = outLineStyleNo;				//Outline Style
					if(theOpacity == "0"){								//Fill Style
						polyArray[polCnt][3] = "0"; //"none"
					}else{
						polyArray[polCnt][3] = "2"; //"trans"
					}	
					polyArray[polCnt][1] = theFill;						//Fill Colour		
					polyArray[polCnt][4] = theStroke					//Outline Colour
					polyArray[polCnt][5] = getBuffers(theFeatureID);	//Buffer Values	
					polyArray[polCnt][6] = theStrokeWidth;				//Outline width
					polyArray[polCnt][7] = shapeType;					//Polygon type
					polyArray[polCnt][8] = annoLayer.features[p].attributes.orderitems;			//Order items this is associated with
				}
			}else if(theFeatureID.indexOf("userlabs") == 0){
				if(annoLayer.features[p].attributes.orderitems != ""){				//Store only if associated with a selected product				
					labCnt = labCnt + 1;
					labelArray[labCnt] = new Array(7);				
					labelArray[labCnt][0] = annoLayer.features[p].style.fontColor; 				//Colour
					labelArray[labCnt][1] = String(theFeatureGeometry.x) + " " + String(theFeatureGeometry.y); 	//Geometry
					labelArray[labCnt][2] = annoLayer.features[p].style.label;  				//Label
					labelArray[labCnt][3] = "solid";											//Background (always solid)							
					labelArray[labCnt][4] = 0;													//Rotation (always zero - not supported)
					var theFontSize = annoLayer.features[p].style.fontSize;
					labelArray[labCnt][5] = theFontSize.substring(0, (theFontSize.length-2));	//Font size
					labelArray[labCnt][6] = annoLayer.features[p].attributes.orderitems;			//Order items this is associated with
				}
			}
		}
	}
	//Store each feature type in turn
	//Add the stored info to temp database to store user shapes
	shapeToAdd =  polCnt + linCnt + labCnt;
	if(shapeToAdd >0){	
		var thePolysToPass = "";
		var theLabsToPass = "";
		var theLinesToPass = "";		
		if(polCnt>0){
			for(c=1;c<=polCnt;c++){
				if(polyArray[c][1].toLowerCase() != "none"){
					polyArray[c][1] = polyArray[c][1].substring(1,polyArray[c][1].length);			//Remove # from colour bstring (causes problems in querystring for some reason)
				}
				if(polyArray[c][4].toLowerCase() != "none"){					
					polyArray[c][4] = polyArray[c][4].substring(1,polyArray[c][4].length);
				}
				if(c==1){
					thePolysToPass =  polyArray[c][1] + "_" + polyArray[c][2] + "_" + polyArray[c][0] + "_" + polyArray[c][5] + "_" + polyArray[c][3] + "_" + polyArray[c][4] + "_" + polyArray[c][6] + "_" + polyArray[c][7] + "_" + polyArray[c][8];	
				}else{
					thePolysToPass += "|" + polyArray[c][1] + "_" + polyArray[c][2] + "_" + polyArray[c][0] + "_" + polyArray[c][5] + "_" + polyArray[c][3] + "_" + polyArray[c][4] + "_" + polyArray[c][6] + "_" + polyArray[c][7] + "_" + polyArray[c][8];
				}
			}		
		}	
		if(linCnt>0){
			for(c=1;c<=linCnt;c++){
				if(lineArray[c][0].toLowerCase() != "none"){			
					lineArray[c][0] = lineArray[c][0].substring(1,lineArray[c][0].length);			//Remove # from colour bstring (causes problems in querystring for some reason)
				}					
				if(c==1){
					theLinesToPass = lineArray[c][0] + "_" + lineArray[c][1] + "_" + lineArray[c][2] + "_"  + lineArray[c][3] + "_"  + lineArray[c][4];
				}else{
					theLinesToPass += "|" + lineArray[c][0] + "_" + lineArray[c][1] + "_" + lineArray[c][2] + "_" + lineArray[c][3] + "_"  + lineArray[c][4];
				}
			}		
		}
		if(labCnt>0){
			for(c=1;c<=labCnt;c++){
				labelArray[c][0] = labelArray[c][0].substring(1,labelArray[c][0].length);			//Remove # from colour bstring (causes problems in querystring for some reason)
				if(c==1){
					theLabsToPass = labelArray[c][0] + "_" + labelArray[c][1] + "_" + labelArray[c][2] + "_" + labelArray[c][3] + "_" + labelArray[c][4] + "_" + labelArray[c][5] + "_" + labelArray[c][6];
				}else{
					theLabsToPass += "|" + labelArray[c][0] + "_" + labelArray[c][1] + "_" + labelArray[c][2] + "_" + labelArray[c][3] + "_" + labelArray[c][4] + "_" + labelArray[c][5] + "_" + labelArray[c][6];
				}	
			}		
		}		
		//Add the shapes to the database
		var qstring = "polys=" + thePolysToPass + "&lines=" + theLinesToPass + "&labs=" + theLabsToPass;
		var storeUserShapeReq = new ajaxObject('storeUserShape.php', handleShapeAddResponse);
		storeUserShapeReq.update(qstring,'POST');		
	}else{
		//*****OPEN SHOPPING BASKET******
		if(document.frmSelected.basketAction.value == ""){
			document.frmSelected.basketAction.value = "ADD";
		}				
		document.frmSelected.action = "basket.php";
		document.frmSelected.submit();
	}		
}
//****************Handles the response from adding shape to database
function handleShapeAddResponse(responseText, responseStatus){
	if(responseStatus == 200){	
		var theResponse = responseText.split("|");
		if(theResponse[0] == "error"){
			showDialog('Error','An error has occured in storing your order. Please try again.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');			
		}else{
			var shapesAdded = Number(theResponse[1]);
			shapeIDString = theResponse[0];	
			//*****OPEN SHOPPING BASKET******
			if(document.frmSelected.basketAction.value == ""){
				document.frmSelected.basketAction.value = "ADD";
			}				
			document.frmSelected.currentSavedShapes.value = shapeIDString;				
			document.frmSelected.action = "basket.php";
			document.frmSelected.submit();	
		}
	}
}

//-------------------------------------------------------------------------RETRIEVING USER ANNO SCRIPTS
//****************Retrieves user shapes for the selected product (Called on intialization)
function getUserShapes(passedIDs,passedType){	
	if(passedIDs != ""){	
		var idArray = passedIDs.split("_");	
		if((idArray[0]!="") || (idArray[1]!="") || (idArray[2]!="")){			//Check if any ids passed
			var qstring = "lid=" + idArray[0] + "&pid=" + idArray[1]  + "&tid=" + idArray[2] + "&thetype=" + passedType;
			var getUserShapeReq = new ajaxObject('getUserShapes.php', handleUserShapeResponse);
			getUserShapeReq.update(qstring,'POST');	
		}
	}
}
//****************Handles the response from getting user shapes
function handleUserShapeResponse(responseText, responseStatus){
	if(responseStatus == 200){
		if(responseText != ""){													
			//Write the passed lines, polys and text to the map view
			lineSep = responseText.indexOf("lines=");
			polySep = responseText.indexOf("polys=");
			textSep = responseText.indexOf("texts=");			
			if(lineSep != -1){												//Get the passed lines
				if(polySep != -1){
					var linesString = responseText.substring(0,polySep);		//Read up to poly seperator
				}else if(textSep != -1){
					var linesString = responseText.substring(0,textSep);		//Read up to text seperator
				}else{
					var linesString = responseText;								//Only lines passed					
				}	
				writeUserShapes(linesString,"lines");
			}		
			if(polySep != -1){
			 	if(textSep != -1){
					var polysString = responseText.substring(polySep,textSep)	
				}else{
					var polysString = responseText.substring(polySep,responseText.length);					
				}	
				writeUserShapes(polysString,"polys");
			}
			if(textSep != -1){
				var textsString = responseText.substring(textSep,responseText.length);
				writeUserShapes(textsString,"texts");
			}							
		}	
		//Write the map extent
		/*OLDif(document.varform.extentinput.value == "paper"){
			var mapScale = document.varform.scale.value;	
			drawPaperDataExtent(0,0,mapScale,storedPassedExtent,true);	
		}else{
			drawDataExtent(storedPassedExtent,"poly");
		}*/
		selectedIndex = 1;
		if((document.varform.data.value.toLowerCase().indexOf("gs1") == 0) || (document.varform.ismultiextent.value == "yes")){ 		//Multi-extent (Map packs)
			//Get the centoid of the passed extent with which to define the multi-map extents	
			if(storedPassedExtent.indexOf("),(") != -1){
				storedPassedExtent = storedPassedExtent.substring(0,storedPassedExtent.indexOf("),("));
			}
			var tempExtentArray = storedPassedExtent.split(",");
			for(c=0;c < tempExtentArray.length;c++){
				var XYArray = tempExtentArray[c].split(" ");
				if(c==0){
					var extentblx = Number(XYArray[0]);	
					var extentbly = Number(XYArray[1]);
					var extenttrx = Number(XYArray[0]);	
					var extenttry = Number(XYArray[1]);
				}else{
					if(Number(XYArray[0]) < extentblx){extentblx = Number(XYArray[0])}
					if(Number(XYArray[0]) > extenttrx){extenttrx = Number(XYArray[0])}
					if(Number(XYArray[1]) < extentbly){extentbly = Number(XYArray[1])}
					if(Number(XYArray[1]) > extenttry){extenttry = Number(XYArray[1])}
				}
			}
			var theCentreX = extentblx + ((extenttrx - extentblx)/2);
			var theCentreY = extentbly + ((extenttry - extentbly)/2);
			var theCaptureShape = String(theCentreX) + " " + String(theCentreY);
			document.getElementById("theScales" + selectedIndex).value = storedSelectedScale;
			document.getElementById("scale" + selectedIndex).value = storedSelectedScale;	
			defineFixedMapExtents(theCaptureShape,"reshow");
		}else if(document.varform.data.value.toLowerCase().indexOf("gs2") != 0){ 			//Standard polygon extent
			if(document.varform.extentinput.value == "paper"){
				//Set the passed scale and show in the list of scales as selected
				document.getElementById("theScales" + selectedIndex).value = storedSelectedScale;
				document.getElementById("scale" + selectedIndex).value = storedSelectedScale;
				mapScale = storedSelectedScale;
				//Draw the extent	
				drawPaperDataExtent(0,0,mapScale,storedPassedExtent,true);
			}else{
				drawDataExtent(storedPassedExtent,"poly");
			}
		}else{																//Groundsure point extent
			drawDataExtent(storedPassedExtent,"point");
		}
	}
}

//-------------------------------------------------------------------------REDRAWING SHAPE SCRIPTS
//****************Draw user shapes to the view called when viewing a previous order with included shapes
function writeUserShapes(passedString,theType){   
	passedString = passedString.substring(6,passedString.length);
	passedString = trim(passedString);
	var theShapes = new Array();
	theShapes = passedString.split("|");
	for(var c=0;c<theShapes.length;c++){			
		//----Draw user polygons
		if(theType == "polys"){
			var theAttributes = new Array();
			theAttributes = theShapes[c].split("_");		
		 	//Create the coordinate string
			var pointList = [];
			var newCoorString = "";
			var theCoordinates = new Array();
			theCoordinates = theAttributes[0].split(",");
			for(c1=0;c1<theCoordinates.length;c1++){
				if(((c1+1)%2) != 0){					
					newCoorString += theCoordinates[c1] + " ";
				}else if((c1+1) == theCoordinates.length){
					newCoorString += String(Number(theCoordinates[c1]));		
				}else{										
					newCoorString += String(Number(theCoordinates[c1])) + ",";		
				}
			}				
			var theCoordArray = newCoorString.split(",");		
			for (c1=0; c1< theCoordArray.length ;c1++){
				var theXY = theCoordArray[c1].split(" ");
				var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
				pointList.push(newPoint);
			}					
			var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
			var theCurrentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);
			annoLayer.addFeatures(theCurrentFeature);		
			//Define the unique id of the shape and store the number of features of this type	
			if(theAttributes[7].indexOf("poly") != -1){
				if(eval("document.varform.noUserPolys.value") == ""){
					var noUserPolys = 0;
				}else{	
					var noUserPolys = Number(eval("document.varform.noUserPolys.value"));
				}					
				var newID = "userpoly" + String(noUserPolys + 1);
				document.varform.noUserPolys.value = String(noUserPolys+1);
			}else if(theAttributes[7].indexOf("rect") != -1){
				if(eval("document.varform.noUserRects.value") == ""){
					var noUserRects = 0;
				}else{	
					var noUserRects = Number(eval("document.varform.noUserRects.value"));
				}					
				var newID = "userrect" + String(noUserRects + 1);
				document.varform.noUserRects.value = String(noUserRects+1);	
			}else if(theAttributes[7].indexOf("circle") != -1){
				if(eval("document.varform.noUserCircles.value") == ""){
					var noUserCircles = 0;
				}else{	
					var noUserCircles = Number(eval("document.varform.noUserCircles.value"));
				}					
				var newID = "usercirc" + String(noUserCircles + 1);
				document.varform.noUserCircles.value = String(noUserCircles+1);		
			}			
			theCurrentFeature.attributes.id = newID;						//Apply the ID
			//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";
			if(is_ie){
				defAnnoStyle.cursor = "hand";	
			}else{
				defAnnoStyle.cursor = "pointer";
			}
			theCurrentFeature.style = defAnnoStyle;					
			//Define outline style and colour		
			if(theAttributes[3] == "1"){										//Solid line
				theCurrentFeature.style.strokeDashstyle = "none";
				theCurrentFeature.style.strokeWidth = 2;
				theCurrentFeature.style.strokeColor = theAttributes[4];
			}else if(theAttributes[3] == "2"){									//Dash line				
				theCurrentFeature.style.strokeDashstyle = "dash";
				theCurrentFeature.style.strokeWidth = 2;
				theCurrentFeature.style.strokeColor = theAttributes[4];
			}else if(theAttributes[3] == "3"){									//No line								
				theCurrentFeature.style.strokeDashstyle = "none";
				theCurrentFeature.style.strokeWidth = 0
			}		
			//Define fill style and colour
			if(theAttributes[1] == "0"){										//No Fill											
				theCurrentFeature.style.fillOpacity = 0;					
			}else if(theAttributes[1] == "1"){									//Hatch fill 
				theCurrentFeature.style.fillOpacity = 0.3;
				theCurrentFeature.style.fillColor = theAttributes[2];
				showDialog('Warning','Pattern fills are not supported in this version of the software yet. Transparent fill will be used instead.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			}else if(theAttributes[1] == "2"){									//Transparent fill
				theCurrentFeature.style.fillOpacity = 0.3;
				theCurrentFeature.style.fillColor = theAttributes[2];
			}		
			annoLayer.redraw();					
			//Store buffers
			if(theAttributes[5] != ""){
				if(document.varform.currentBuffers.value == ""){				
					document.varform.currentBuffers.value = newID + "," + theAttributes[5];
				}else{
					document.varform.currentBuffers.value = document.varform.currentBuffers.value + "_" + newID + "," +theAttributes[5];
				}
			}				
		}
		//----Draw user lines
		if(theType == "lines"){
			var theAttributes = new Array();
			theAttributes = theShapes[c].split("_");			
			//Create the coordinate string
			var pointList = [];
			var newCoorString = "";
			var theCoordinates = new Array();
			theCoordinates = theAttributes[0].split(",");
			for(c1=0;c1<theCoordinates.length;c1++){
				if(((c1+1)%2) != 0){					
					newCoorString += theCoordinates[c1] + " ";
				}else if((c1+1) == theCoordinates.length){
					newCoorString += String(Number(theCoordinates[c1]));		
				}else{										
					newCoorString += String(Number(theCoordinates[c1])) + ",";		
				}
			}
			var theCoordArray = newCoorString.split(",");		
			for (c1=0; c1< theCoordArray.length ;c1++){
				var theXY = theCoordArray[c1].split(" ");
				var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
				pointList.push(newPoint);
			}					
			var theCurrentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(pointList),null);
			annoLayer.addFeatures(theCurrentFeature);
			//Define the unique id of the shape and store the number of features of this type
			if(eval("document.varform.noUserLines.value") == ""){
				var noUserLines = 0;
			}else{	
				var noUserLines = Number(eval("document.varform.noUserLines.value"));
			}					
			var newID = "userline" + String(noUserLines + 1);
			document.varform.noUserLines.value = String(noUserLines+1);
			theCurrentFeature.attributes.id = newID;									//Apply the ID				
			//Apply a default style 
			if(theAttributes[1] == "1"){												//Solid line
				var theDashStyle = "none";			
			}else if(theAttributes[1] == "2"){											//Dash line
				var theDashStyle = "dash";
			}
			defAnnoStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
			defAnnoStyle.fillOpacity = 0.3;
			defAnnoStyle.graphicOpacity = 1;
			defAnnoStyle.fillColor = "#FF0000";
			defAnnoStyle.strokeWidth = 2;	
			defAnnoStyle.strokeDashstyle = theDashStyle;
			defAnnoStyle.strokeColor = theAttributes[2];  
			defAnnoStyle.pointerEvents = "visiblePainted";
			if(is_ie){
				defAnnoStyle.cursor = "hand";	
			}else{
				defAnnoStyle.cursor = "pointer";
			}
			theCurrentFeature.style = defAnnoStyle;
			annoLayer.redraw();
			//Define arrow head (if necessary)
			var selectedStyle = "";			
			if(theAttributes[1] == "4"){
				var selectedStyle = "end";
			}else if(theAttributes[1] == "5"){
				var selectedStyle = "start";
			}else if(theAttributes[1] == "6"){
				var selectedStyle = "both";
			}	
			if(selectedStyle != ""){  
				drawArrowHead(selectedStyle,theCurrentFeature,newID,theAttributes[2]);    //Draw arrow heads
			}	
		}
		//----Draw user labels	
		if(theType == "texts"){
			var theAttributes = new Array();
			var theCoordinates = new Array();
			theAttributes = theShapes[c].split("_");
			theCoordinates = theAttributes[0].split(",");
			var newPoint = new OpenLayers.Geometry.Point(theCoordinates[0],theCoordinates[1]);					
			var theCurrentFeature = new OpenLayers.Feature.Vector(newPoint,null);
			annoLayer.addFeatures(theCurrentFeature);
			//Define the unique id of the shape and store the number of features of this type
			if(document.varform.noUserLabels.value == ""){
				var noUserLabels = 0;
			}else{	
				var noUserLabels = Number(document.varform.noUserLabels.value);
			}					
			var newID = "userlabs" + String(noUserLabels + 1);
			document.varform.noUserLabels.value = String(noUserLabels+1);		
			theCurrentFeature.attributes.id = newID;							//Apply the ID			
			//Apply a default style 
			if(theAttributes[5] == ""){
				var theFontSize = "18";  
				showDialog('Warning','The original text size could not be read. Default size will be used instead.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			}else{
				var theFontSize = theAttributes[5];			
			}	
			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";
			if(is_ie){
				defAnnoStyle.cursor = "hand";	
			}else{
				defAnnoStyle.cursor = "pointer";
			}
			defAnnoStyle.label = theAttributes[1]; 
			defAnnoStyle.fontColor = theAttributes[2];
			defAnnoStyle.fontSize = theFontSize+"px";          
			defAnnoStyle.fontFamily = "Arial";		
			defAnnoStyle.labelSelect = true;  		
			defAnnoStyle.labelAlign = "lb";   
			if(is_ie7down == false){	
				defAnnoStyle.labelPadding = "3px";
				defAnnoStyle.labelBackgroundColor = "#ffffff";
				defAnnoStyle.labelBorderColor= theAttributes[2];
				defAnnoStyle.labelBorderSize= "1px"; 
			}
			defAnnoStyle.graphicName = "cross"; 
			defAnnoStyle.pointRadius = 0; 
			
			
			/*defAnnoStyle.labelXOffset = "3px";   //NOT WORKING!!
			defAnnoStyle.labelYOffset = "3px";	
			defAnnoStyle.labelPadding = "5px";
			defAnnoStyle.labelBackgroundColor = "#ffffff";
			defAnnoStyle.labelBorderColor = theAttributes[2];
			defAnnoStyle.labelBorderSize = "1px"; 
			defAnnoStyle.graphicName = "cross";
			defAnnoStyle.pointRadius = 10;*/
			
			theCurrentFeature.style = defAnnoStyle;
			annoLayer.redraw();					
		}				
	}	
}

//-------------------------------------------------------------------------RETREIVING MASTERMAP SHAPE SCRIPTS
//****************Handles the response from getting MasterMap shapes
function handleMMShapesResponse(responseText, responseStatus){
	if(responseStatus == 200){		
		if((responseText.indexOf("false") == -1) && (responseText != "")){
			var tempArray = responseText.split("_");
			if(tempArray[1] != ""){
				drawReturnedShapes(tempArray[0],tempArray[1]);						//Pass to function to draw the shapes
			}else{
				showDialog('Warning','No features found.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');			
			}
			//Turn off the tools and clear progress animation
			if(tempArray[0] == "extent"){
				document.getElementById("mmshapeprogess2").style.display = "none";
				document.getElementById("selarea1").src = "images/selarea1.png";		
				document.getElementById("selarea3").src = "images/selarea3.png";
			}else{
				document.getElementById("mmshapeprogess").style.display = "none";
			}					
		}else{
			showDialog('Error','There has been a problem in retrieving features from within your OS MasterMap preview areas. Ensure you are logged in and have captured a shape within a preview area.<br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
		}		
	}
}
//****************Draw the map extent from the passed coordinate string  
function drawReturnedShapes(theType,theMMPolys){
	var mmPolyArray = new Array();	
	mmPolyArray = theMMPolys.split('|');							
	if((theType == "extent") && (mmPolyArray.length > 1)){   
		showDialog('Warning','Ensure only one shape is returned.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
	}else{
		//Draw each shape in turn	
		for(s=0;s<mmPolyArray.length;s++){
			var pointList = [];			
			var theCoordArray = mmPolyArray[s].split(",");		
			for (c=0; c< theCoordArray.length ;c++){
				if((c % 2) == 0){
					theX = theCoordArray[c];
				}else{
					theY = theCoordArray[c];
					var newPoint = new OpenLayers.Geometry.Point(theX,theY);
					pointList.push(newPoint);
				}
			}					
			var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
			polygonExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);
			if(theType == "anno"){						
				annoLayer.addFeatures(polygonExtentFeature);		
				storeUserAnno("poly","");							//Define the unique id for the shape and  number of shapes
			}else{
				extentLayer.addFeatures(polygonExtentFeature);		
			}						
		}
		if(theType == "anno"){	
			annoDrawingEnable('selusershape');	
		}
		drawCapturePointControl.deactivate();				//Deactivate the point capture tool		
		drawCapturePolyControl.deactivate();				//Deactivate the poly capture tool			
	}
}

//---------------------------End of script
