/*-------------------------------------
planvu2.js
Lovell Johns Ltd.
March 2009
JavaScript file for PlanVu ver.2
---------------------------------------*/

//----------------------------------------------------------GLOBALS
var http;
var theMapFile = "/var/www/html/burnleybc/bbcplanvu.map";	//Mapserver map file
var osBaseLayerNames = "ov_small ov os50k os10k e34_4_label";			//OS raster layers (that are always defines in the map)
var fixedQuickZoomWidth = 3000;								//In metres
var shiftIsDown = false;									//Stores if the shift is pressed down - allows turning collapsing/expanding all legend groups
var usesGroups = true;										//Define if layers are grouped 
var useMSLegImages = false;									//Define if using MapServer created lagend images or pre-created ones
var map;													//Openlayers map
var baseLayer;												//Openlayers mapping layer
var editingLayer;											//Openlayers layer for drawing over the map
var drawPointControl;										//Openlayers drawing controls
var drawLineControl;
var drawPolyControl;
var modifyControl;
var selControl;
var click;
var popup = new Array();									//Openlayers popup - used for adding labels to the map
var thePopupIndex = -1;
var watermarkLayer = null;
var animateToggleLayers = true;								//Defines if expending or collapsing layer groups in the legend have an effect or not
var mapMinX = 377220;										//Full map extent
var mapMinY = 423416;
var mapMaxX = 393220;
var mapMaxY = 439416;
var waterMarkImagePath = "http://www.planvu.co.uk/burnleybc/images/watermark.gif";	//Path to watermark image
var introCookieName = "bbcplanvuintro";
var mapLabelLayers = new Array("regen_urban_areas");		//Stores map layers that have associated labels (these will be called "<layer name>_label")

OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '3';				//Drawn feature styles
OpenLayers.Feature.Vector.style['default']['fillColor'] = 'red';
OpenLayers.Feature.Vector.style['default']['strokeColor'] = 'red';
OpenLayers.Feature.Vector.style['default']['fillOpacity'] = '0.3';
OpenLayers.Feature.Vector.style['default']['graphicOpacity'] = '1';
OpenLayers.Feature.Vector.style['select']['strokeWidth'] = '3';
OpenLayers.Feature.Vector.style['select']['fillColor'] = 'blue';
OpenLayers.Feature.Vector.style['select']['strokeColor'] = 'blue';
OpenLayers.Feature.Vector.style['select']['fillOpacity'] = '0.3';
OpenLayers.Feature.Vector.style['select']['graphicOpacity'] = '1';

//******************Store browser version
var is_nav6up = false;
var is_ie6up = false;
var is_opera5up = false;
checkBrowser();

//----------------------------------------------------------MAP INITIALIZATION
//*********************************Initialization
function init(){
	//Get map layers
	document.mapform.mapaction.value = "initial" 			
	var qstring = "mapaction=" + document.mapform.mapaction.value;
	sndReq(qstring);			
}
//*********************************Initialize the mapping
function mapInit(){


	
	//Set the map
	map = new OpenLayers.Map( $('maplayer'), { controls: [], projection: 'EPSG:27700',
		units:'m',
		maxExtent: new OpenLayers.Bounds(mapMinX,mapMinY,mapMaxX,mapMaxY),
		resolutions: [26.6, 13, 7, 4, 2, 1, 0.5]});
	
	//Set the map options - used for overview map
	var mapOptions = {
		projection: 'EPSG:27700',
		units:'m',
		maxExtent: new OpenLayers.Bounds(mapMinX,mapMinY,mapMaxX,mapMaxY),
		resolutions: [65]
	};
	
	
	
	//Define the base layer
	document.mapform.mapaction.value = "refresh";	
	var theMapLayersString = getMapLayers(); 
	var theMapLayerInfo = theMapLayersString.split("|");
	var layersToShow = osBaseLayerNames + " " +theMapLayerInfo[0];		//Get all the layers to show
	
	baseLayer = new OpenLayers.Layer.MapServer("Mapping",
				"http://www.planvu.co.uk/cgi-bin/mapserv",
				{ map: theMapFile,
				  layers: layersToShow}, { singleTile: true, isBaseLayer: true, transitionEffect: 'resize'});
	
	//Add the editing layer
	editingLayer = new OpenLayers.Layer.Vector("Editable");
	  
	//Add layers to map and set any properties on the map   
	map.addLayers([baseLayer,editingLayer]);
	map.fractionalZoom = true;
	
	//--Set the initial extent of the map and zoom to it
	var bounds = new OpenLayers.Bounds(mapMinX,mapMinY,mapMaxX,mapMaxY);
	if (!map.getCenter()) map.zoomToExtent(bounds);
	
	//Add controls to the map
	map.addControl(new OpenLayers.Control.PanZoomBar({'div':OpenLayers.Util.getElement('zoompaneldiv')}));	
	map.addControl(new OpenLayers.Control.Navigation());				
	map.addControl(new OpenLayers.Control.ScaleLine({'div':OpenLayers.Util.getElement('scalediv')}));  
	//map.addControl(new OpenLayers.Control.LayerSwitcher());
	//map.addControl(new OpenLayers.Control.PanZoom());
	// map.addControl(new OpenLayers.Control.MouseToolbar());
	//map.addControl(new OpenLayers.Control.MousePosition());
	//map.addControl(new OpenLayers.Control.NavToolbar());
	//map.addControl(new OpenLayers.Control.EditingToolbar(vlayer));
	//map.addControl(new OpenLayers.Control.Scale()); 
	
	//Map click control - used for returing policy info	
	OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
		defaultHandlerOptions: {
			'single': true,
			'double': false,
			'pixelTolerance': 0,
			'stopSingle': false,
			'stopDouble': false
		},

		initialize: function(options) {
			this.handlerOptions = OpenLayers.Util.extend(
				{}, this.defaultHandlerOptions
			);
			OpenLayers.Control.prototype.initialize.apply(
				this, arguments
			); 
			this.handler = new OpenLayers.Handler.Click(
				this, {
					'click': this.trigger
				}, this.handlerOptions
			);
		}, 

		trigger: function(e) {
			if(document.mapform.mapaction.value == "mapquery"){			
				//Pass the selected coordinate through to MapServer to return a list of policies
				var lonlat = map.getLonLatFromViewPortPx(e.xy);
				var theX =  lonlat.lon;
				var theY =  lonlat.lat;       
				var theMapLayersString = getMapLayers(); 			//Get list of all the layers that are visible (need to pass this to ensure we only query visible layers)
				var theMapLayerInfo = theMapLayersString.split("|");           		
				document.mapform.mapaction.value = "mapquery";
				var qstring = "mapaction=" + document.mapform.mapaction.value + "&ldfmapx=" + theX + "&ldfmapy=" + theY + "&mapLayers=" + theMapLayerInfo[0];		
				sndReq(qstring);
							
			}else if(document.mapform.mapaction.value == "addlabel"){
				var lonlat = map.getLonLatFromViewPortPx(e.xy);		//Get the clicked point
				var theX =  lonlat.lon;
				var theY =  lonlat.lat;   
						
				//Toggle the HTML watermark layer off and the openlayers layer on
				toggleWatermark("openlayers");
				
				//Define the new label index for the  label to add  (use as global var instead!!)
				document.mapform.labelcount.value = Number(document.mapform.labelcount.value) + 1;
				var labelIndex = Number(document.mapform.labelcount.value);
				var labelID = "label_" + String(labelIndex);
				var labelBackID = "labelback_" + String(labelIndex);
				
				//Create the label as a popup
				popup[labelIndex] = new OpenLayers.Popup("maplabel",
                	new OpenLayers.LonLat(theX,theY),
                	new OpenLayers.Size(2,2),
                	"<div id='" + labelBackID + "' name='" + labelBackID + "' style='background-color:#FFFFFF; padding: 2px; height:18px; width:130px; align:center;' onclick='selectLabel(this);' ondblclick='startLabelMove(this);'><textarea id='" + labelID + "' name='" + labelID + "' style='height:16px; width:128px;' onkeyup='updateLabelText(this);'>Enter Label Here</textarea></div>",
                   	false);
					popup[labelIndex].autoSize=true;		
					map.addPopup(popup[labelIndex]);
					//Show added label as selected
					deselectLabels();	
					var theLabelObj = document.getElementById(labelBackID);
					selectLabel(theLabelObj);
					
			}else if(document.mapform.mapaction.value == "movelabel"){		
				var newPos = map.getLonLatFromViewPortPx(e.xy);		//Get the clicked point
				popup[thePopupIndex].lonlat = newPos;
				document.mapform.mapaction.value = "";
				click.deactivate();		
				
			}else{				//Deselect everything
				deselectLabels()
			}												  							  
		}

	});
	click = new OpenLayers.Control.Click();
    map.addControl(click);
      
	
	//Draw fetaures
	drawPointControl = new OpenLayers.Control.DrawFeature(editingLayer,OpenLayers.Handler.Point);
    drawLineControl = new OpenLayers.Control.DrawFeature(editingLayer, OpenLayers.Handler.Path);
    drawPolyControl = new OpenLayers.Control.DrawFeature(editingLayer,OpenLayers.Handler.Polygon);
	map.addControl(drawPointControl)
	map.addControl(drawLineControl)
	map.addControl(drawPolyControl)
	
	//Modify features
	modifyControl =  new OpenLayers.Control.ModifyFeature(editingLayer)	
	map.addControl(modifyControl);
	
	selControl =  new OpenLayers.Control.SelectFeature(editingLayer);
	map.addControl(selControl);
	
	//Overview control	
    var controlOptions = {
        mapOptions: mapOptions,
		div: $('overviewmapimage')
    }	
	var theOverview = new OpenLayers.Control.OverviewMap(controlOptions);
	var ovSize = new OpenLayers.Size(250,250);
	theOverview.size = ovSize;
    map.addControl(theOverview); 
	
	//Register events 
	//Get scale after each zoom
	map.events.register('zoomend', map, function(evt) { 
		var theMappingScale = Math.round(map.getScale());
		document.mapform.theMapScale.value = theMappingScale;
	}); 
	
	//Reset the policy links and search results that are showing when the user update the map view
	map.events.register('moveend', map, function(evt) { 		
		document.getElementById("policyresultslayer").innerHTML = "<br/><p>Click the <em>Info. Button</em> <img src='images/infotool.bmp' border='0' /> and then click on the map to get policy info. at this point</p><br/>";
        document.getElementById("searchresultslayer").innerHTML = "<p>&nbsp;</p>";
		
		//If the openlayers watermark is showing update it so that it is positioned centrally over the map
		if(watermarkLayer != null){
			toggleWatermark("updateopenlayers");
		}
	});
	
	//Show content of default tabs on left
	if(document.mapform.apptype.value != "reduced"){
		toggleTabs("searching","1");
	}

}

//----------------------------------------------------------MAP NAVIGATION

//******************Run navigation when user chooses quick map link
function quickNav(selObj){
	var theCoordString = selObj.options[selObj.selectedIndex].value;
	if(theCoordString != "#"){
		//Get selected coordinate and zoom scale	
		var theCoordStringArray = theCoordString.split(",");
		var theX = Number(theCoordStringArray[0]);
		var theY = Number(theCoordStringArray[1]);
		var theZoomScale = Number(theCoordStringArray[2]);
		//Zoom to the point
		zoomToScale(theX,theY,theZoomScale);
	}	
}

//******************Zoom to a point (called when zooming to search location)
function zoomToPoint(theX,theY,zoomWidth){
	var blx = Number(theX) - (Number(zoomWidth)/2);
	var bly = Number(theY) - (Number(zoomWidth)/2);
	var urx = Number(theX) + (Number(zoomWidth)/2);
	var ury = Number(theY) + (Number(zoomWidth)/2);
	var bounds = new OpenLayers.Bounds(blx,bly,urx,ury);
	map.zoomToExtent(bounds);
}

//******************Zoom to a point @ scale (called from quick links)
function zoomToScale(theX,theY,zoomScale){
	//Zoom in at a point
	var blx = Number(theX) - (Number(fixedQuickZoomWidth)/2);
	var bly = Number(theY) - (Number(fixedQuickZoomWidth)/2);
	var urx = Number(theX) + (Number(fixedQuickZoomWidth)/2);
	var ury = Number(theY) + (Number(fixedQuickZoomWidth)/2);
	var bounds = new OpenLayers.Bounds(blx,bly,urx,ury);
	map.zoomToExtent(bounds);
	//Adjust the scale
	if(zoomScale != 0){
		map.zoomToScale(zoomScale,false);
	}
}

//******************Zoom map to the specified scale
function updateMapScale(){
	var theScale = Number(document.mapform.theMapScale.value);
	if(theScale != 0){
		map.zoomToScale(theScale,false);
	}
}

//****************Send request to get the extent of the passed policy code
function zoomToPolicy(thePolicyCode){
	var theMapLayersString = getMapLayers(); 			//Get list of all the layers that are visible (need to pass this to ensure we only query visible layers)
	var theMapLayerInfo = theMapLayersString.split("|");           		
	document.mapform.mapaction.value = "policy";
	var qstring = "mapaction=" + document.mapform.mapaction.value + "&policy=" + thePolicyCode + "&mapLayers=" + theMapLayerInfo[0];		
	sndReq(qstring);
}

//****************Send request to get the extent of the passed layer
function zoomToLayer(theLayerID){
	var theMapLayersString = getMapLayers(); 			//Get list of all the layers that are visible (need to pass this to ensure we only query visible layers)
	var theMapLayerInfo = theMapLayersString.split("|");           		
	document.mapform.mapaction.value = "layer";
	var qstring = "mapaction=" + document.mapform.mapaction.value + "&layerid=" + theLayerID + "&mapLayers=" + theMapLayerInfo[0];		
	sndReq(qstring);
}

//----------------------------------------------------------GET POLICY SCRIPTS

//******************Get the policies that intersect with the current view
function getPolicy(){			
	document.mapform.mapaction.value = "queryview";
	var theMapLayersString = getMapLayers(); 			//Get list of all the layers
	var theMapLayerInfo = theMapLayersString.split("|");	
	var theViewExtent = map.getExtent().toBBOX();
	var qstring = "mapaction=" + document.mapform.mapaction.value + "&mapLayers=" + theMapLayerInfo[0] + "&extent=" + theViewExtent;
	sndReq(qstring);	
}

//******************Hides/displays the relavant policy results pages
function showResultPage(toShow,toHide){		
	if (is_nav6up) {										//Navigator6/Firefox
		var theObjToShow = document.getElementById("page_" + toShow);						
		theObjToShow.className = 'policypageon';
		var theObjToHide= document.getElementById("page_" + toHide);						
		theObjToHide.className = 'policypageoff';											
	}else{													//Opera/IE
		var toEval = "page_" + toShow + ".className='policypageon'";
		eval(toEval);		
		var toEval = "page_" + toHide + ".className='policypageoff'";
		eval(toEval);	
	}
}

//----------------------------------------------------------AJAX FUNCTIONALITY

//****************Create request object
function createRequestObject() {
	var ro;		
	if (window.XMLHttpRequest) { 				// Mozilla, Safari,...
		ro = new XMLHttpRequest();
	}else if (window.ActiveXObject) { 			// IE
		try {
			ro = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			ro = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	return ro;	
}

//****************Run mapserver mapscript functions to return map layer list
function sndReq(qstring) {
	http = createRequestObject();
	http.open('get', 'updatemap2.php?' + qstring); 
	http.onreadystatechange = updatemapResponse2;
	http.send(null);
}

//****************Perform action based on returned values
function updatemapResponse2() {
	if(http.readyState == 4){	
		//Get the returned values
		var response = http.responseText;		
		var tempArray = new Array();
		tempArray = response.split("|"); 
		//alert(response)	
		if(tempArray[0] == "initial"){						//**Map initialization - update layer list
			document.getElementById("maplayerslayer").innerHTML = tempArray[1];				
			addLegImages(tempArray[2]);						//Get the individual legend images and add to the layer list to create combine layer/legand list
			mapInit();										//Initialize the map		
		}else if(tempArray[0] == "mapsearch"){				//**Show results of map serach
			document.getElementById("searchresultslayer").innerHTML = tempArray[1] + "<br/>";	
			toggleTabs("searching","1");					
		}else if(tempArray[0] == "zoomtopcode"){			//**Zoom to the returned location
			var tempArray2 = new Array();
			tempArray2 = tempArray[1].split(","); 
			zoomToPoint(tempArray2[0],tempArray2[1],tempArray2[2]);		
		}else if(tempArray[0] == "mapquery"){				//**Show the results map query			
			document.getElementById("policyresultslayer").innerHTML = tempArray[1];
			toggleTabs("policyresultslayer","1");			
		}else if(tempArray[0] == "policy"){					//**Zoom to the passed extent (ie extent of the policy code)
			var policyBoundsArray = tempArray[1].split(" ");			
			var bounds = new OpenLayers.Bounds(policyBoundsArray[0],policyBoundsArray[1],policyBoundsArray[2],policyBoundsArray[3]);
			map.zoomToExtent(bounds);
		}else if(tempArray[0] == "layer"){					//**Zoom to the passed extent (ie extent of the policy layer)
			var policyBoundsArray = tempArray[1].split(" ");			
			var bounds = new OpenLayers.Bounds(policyBoundsArray[0],policyBoundsArray[1],policyBoundsArray[2],policyBoundsArray[3]);
			map.zoomToExtent(bounds);
		}
	}
}

//----------------------------------------------------------LAYER LIST/LEGEND SCRIPTS

//****************Add individual legend images into the layer list
function addLegImages(theHTMLLegString){
	//Get the individual legend images and add to the layer list to create combine layer/legand list
	//HTML legend elements are of the form -
	//<p><img id="[metadata name=LAYER_SOURCE]" src="[leg_icon width=20 height=13]" width=20 height=13>&nbsp; [metadata name=LAYER_ALIAS]</p>
	//alert(theHTMLLegString)
	var tempString = theHTMLLegString;
	var sep1 = 0
	var legcnt = 0;
	while(sep1 != -1){
		legcnt += 1;
		sep1 = tempString.indexOf("id=");
		if(sep1 == -1){					//No more legend items - exit loop
			break;
		}					
		if(legcnt == 500){				//Catch to ensure we don't loop infinately
			break;
		}
		var sep2 = tempString.indexOf("src=");
		var sep3 = tempString.indexOf("width=");
		var theID = tempString.substring((sep1+4),(sep2-2));
		theLegImageName = tempString.substring((sep2+5),(sep3-2));
		
		if(useMSLegImages == false){				//Use pre-created legend images (MapServer images rescale and don't give good indication of policy)
			theLegImageName = "images/legend/" + theID + ".gif";
		}
		
		var theLegImageObj = document.getElementById("leg_" + theID);				//**Update new overview image
		if(theLegImageObj != null){
			theLegImageObj.src = theLegImageName;
		}
		var sep4 = tempString.indexOf("</p>");
		var tempString1 = tempString.substring((sep4+4),tempString.length);
		tempString = tempString1;
	}
}

//******************Get visible map layers
function getMapLayers(){

	if(document.mapform.apptype.value == "reduced"){					//***Using stripped application all layers turned on by default
		return "all|";
	}else{																//***Using full application define the layers that are visible
		var theVisibleLayers = "";
		var visLayCnt = 0;
		var theExpandedGroups = "";
		var expandedGroupsCnt = 0;
		var	theSelectedGroups = "";
		var selectedGroupsCnt = 0;
		c1=0;
		
		if(usesGroups){
			var toLoop = document.mapform.mapGroupLayers.length;
		}else{
			var toLoop = 1;
		}
		
		for(c1=0;c1<toLoop;c1++){
			//Define what groups are expanded (if layers are grouped)
			if(usesGroups){		
				if(is_nav6up){										//Navigator6/Firefox
					var theObj = document.getElementById("group" + String(c1+1));
					if(theObj.className == 'collapsibleon'){
						expandedGroupsCnt += 1;
						if(expandedGroupsCnt == 1){
							theExpandedGroups += String(c1+1);
						}else{
							theExpandedGroups += "," + String(c1+1);
						}	 
					}										
				}else{													//Opera/IE
					var toEval = "group" + String(c1+1) + ".className";		
					if(eval(toEval) == 'collapsibleon'){
						expandedGroupsCnt += 1;
						if(expandedGroupsCnt == 1){
							theExpandedGroups += String(c1+1);
						}else{
							theExpandedGroups += "," + String(c1+1);
						}
					}
				}
			}
					
			if((document.mapform.mapGroupLayers[c1].checked) || (document.mapform.mapGroupLayers[c1].disabled) || (usesGroups == false)){								//Group Layer is turned on - check which sub layers are turned on	
				selectedGroupsCnt += 1;
				if(selectedGroupsCnt == 1){
					theSelectedGroups += String(c1+1);
				}else{
					theSelectedGroups += "," + String(c1+1);
				}
					
				var noSubLayers = eval("document.mapform.mapLayers" + String(c1+1) + ".length");
				if(isNaN(noSubLayers)){
					var noSubLayers = 1;
				}		
				if(noSubLayers == 1){
					if((eval("document.mapform.mapLayers" + String(c1+1) + ".checked")) || (eval("document.mapform.mapLayers" + String(c1+1) + ".disabled"))){
						visLayCnt += 1;
						if(visLayCnt == 1){
							theVisibleLayers = eval("document.mapform.mapLayers" + String(c1+1) + ".value"); 
						}else{
							theVisibleLayers += " " + eval("document.mapform.mapLayers" + String(c1+1) + ".value"); 
						}	
					}
				}else{
					for(c2=0;c2<noSubLayers;c2++){
						if((eval("document.mapform.mapLayers" + String(c1+1) + "[" + c2 + "].checked")) || (eval("document.mapform.mapLayers" + String(c1+1) + "[" + c2 + "].disabled"))){
							visLayCnt += 1;
							if(visLayCnt == 1){
								theVisibleLayers = eval("document.mapform.mapLayers" + String(c1+1) + "[" + c2 + "].value");  //document.mapform.mapLayers[c].value;
							}else{
								theVisibleLayers += " " + eval("document.mapform.mapLayers" + String(c1+1) + "[" + c2 + "].value");  //document.mapform.mapLayers[c].value;
							}		
						}
					}
				}	
			}
		}
		
		//Check if any of the visible layers have associated Label layers and add to string of visible layers
		for(c=0;c < mapLabelLayers.length;c++){							
			if(theVisibleLayers.indexOf(mapLabelLayers[c]) != -1){
				theVisibleLayers += " " + mapLabelLayers[c] + "_label";	
			}
		}

		return theVisibleLayers + "|" + theExpandedGroups + "|" + theSelectedGroups;
	}
}

//******************Toggles the visibility of a layer
function toggleLayer(selObj,layerType,groupIndex){

	//If user has clicked on a group layer - turn on or off the sub layers
	if(layerType == "parent"){
		if(selObj.checked){				//Turn all on		
			var noSubLayers = eval("document.mapform.mapLayers" + groupIndex + ".length");
			for(c=0;c<noSubLayers;c++){
				eval("document.mapform.mapLayers" + groupIndex + "[" + c + "].checked = true");
			}
		}else{							//Turn all off
			var noSubLayers = eval("document.mapform.mapLayers" + groupIndex + ".length");
			for(c=0;c<noSubLayers;c++){
				eval("document.mapform.mapLayers" + groupIndex + "[" + c + "].checked = false");
			}
		}
	}
	
	//If the user has clicked on a layer to make visisble and the parent group is unchecked (not visible) - check the parent
	if(layerType != "parent"){
		if(selObj.checked){
			var groupIndex = Number(selObj.id.substring(9,selObj.id.length)) - 1;
			if(eval ("document.mapform.mapGroupLayers[" + groupIndex + "].checked") == false){					
				eval ("document.mapform.mapGroupLayers[" + groupIndex + "].checked = true");
			}
		}
	}

	//Get the visible map layers
	document.mapform.mapaction.value = "refresh";	
	var theMapLayersString = getMapLayers(); 
	var theMapLayerInfo = theMapLayersString.split("|");
	
	//Update on the map
	var layersToShow = osBaseLayerNames + " " +theMapLayerInfo[0];
	updateLayersOnMap(layersToShow);
}

//******************Toggles the visibility of all layers
function toggleLayers(theAction){

	if(usesGroups){
		var toLoop = document.mapform.mapGroupLayers.length;
	}else{
		var toLoop = 1;
	}
	
	if(theAction == "on"){ 				//Turn all on
		c1=0;
		for(c1=0;c1<toLoop;c1++){
			if(usesGroups){
				document.mapform.mapGroupLayers[c1].checked = true;
			}
			var noSubLayers = eval("document.mapform.mapLayers" + String(c1+1) + ".length");
			if(isNaN(noSubLayers)){
				var noSubLayers = 1;
			}
			if(noSubLayers == 1){
				eval("document.mapform.mapLayers" + String(c1+1) + ".checked = true");
			}else{
				for(c2=0;c2<noSubLayers;c2++){
					eval("document.mapform.mapLayers" + String(c1+1) + "[" + c2 + "].checked = true");			
				}
			}
		}
	}else{								//Turn all off
		c1=0;
		for(c1=0;c1<toLoop;c1++){		
			//if(usesGroups){
				//document.mapform.mapGroupLayers[c1].checked = false;
			//}	
			var noSubLayers = eval("document.mapform.mapLayers" + String(c1+1) + ".length");
			if(isNaN(noSubLayers)){
				var noSubLayers = 1;
			}
			if(noSubLayers == 1){
				//Ignore fixed layers
				if(eval("document.mapform.mapLayers" + String(c1+1) + ".disabled") == false){
					eval("document.mapform.mapLayers" + String(c1+1) + ".checked = false");
				}
			}else{
				for(c2=0;c2<noSubLayers;c2++){
					//Ignore fixed layers
					if(eval("document.mapform.mapLayers" + String(c1+1) + "[" + c2 + "].disabled") == false){
						eval("document.mapform.mapLayers" + String(c1+1) + "[" + c2 + "].checked = false");
					}			
				}
			}
		}
	}
	
	//Get the visible map layers
	document.mapform.mapaction.value = "refresh";	
	var theMapLayersString = getMapLayers(); 
	var theMapLayerInfo = theMapLayersString.split("|");
	
	//Update on the map
	var layersToShow = osBaseLayerNames + " " +theMapLayerInfo[0];
	updateLayersOnMap(layersToShow);
}

//****************Reloads in new base layer into OpenLayers to reflect a policy layer being turned on or off
function updateLayersOnMap(layersToShow) {
	//Get current extent
	var bounds = map.getExtent();  
	//Remove the old layer
	if(baseLayer != null){
		map.removeLayer(baseLayer);
	}	
	//Define the new base layer
	baseLayer = new OpenLayers.Layer.MapServer("Mapping",
				"http://www.planvu.co.uk/cgi-bin/mapserv",
				{ map: theMapFile,
				  layers: layersToShow}, { singleTile: true, isBaseLayer: true, transitionEffect: 'resize'});	  	
	//Add the layer
	map.addLayer(baseLayer);	
	//Need to zoom to to current extent (sometimes Openlayers changes the zoom level when updating the base layer)
	map.zoomToExtent(bounds);
}

//******************Hides/displays the legend group elements
function toggleLegendGroup(theGroup){
	if(shiftIsDown){										//**Expand or collapse all
		//Define if to expand or collapse all
		var clickedIsOn = false;
		if(animateToggleLayers){
			//Using effects
			var theObj = document.getElementById(theGroup);
			if(theObj.style.display != "none"){
				clickedIsOn = true;
			}
		}else{
			//Using simple show
			if (is_nav6up) {										//Navigator6/Firefox
				var theObj = document.getElementById(theGroup);
				if(theObj.className == 'collapsibleon'){		
					clickedIsOn = true;
				}										
			}else{													//Opera/IE
				var toEval = theGroup + ".className";		
				if(eval(toEval) == 'collapsibleon'){				
					clickedIsOn = true;			
				}
			}
		}

		//Loop thru each layer and expand or collapse all
		for(c1=0;c1<document.mapform.mapGroupLayers.length;c1++){
			theGroup = "group" + String(c1+1);	
			var boxbtn = document.getElementById(theGroup + "img");		
			
			if(animateToggleLayers){		
				//Using effects method for showing the individual layers
				var theObj = document.getElementById(theGroup);
				if(clickedIsOn){      						//Collapse all
					theObj.style.display = "none";
					boxbtn.src = "images/expand.gif";
				}else{										//Expand all
					theObj.style.display = "block";
					boxbtn.src = "images/collapse.gif";
				}
			}else{				
				//Using simple show
				if (is_nav6up) {										//Navigator6/Firefox
					var theObj = document.getElementById(theGroup);				
					if(clickedIsOn){      						//Collapse all
						theObj.className = 'collapsibleoff';
						boxbtn.src = "images/expand.gif";
					}else{										//Expand all
						theObj.className = 'collapsibleon';
						boxbtn.src = "images/collapse.gif";
					}						
				}else{													//Opera/IE
					var toEval = theGroup + ".className";
					if(clickedIsOn){      						//Collapse all
						var toEval2 = theGroup + ".className='collapsibleoff'";
						boxbtn.src = "images/expand.gif";
					}else{
						var toEval2 = theGroup + ".className='collapsibleon'";
						boxbtn.src = "images/collapse.gif";
					}
					eval(toEval2);
				}
			}
		}
	}else{													//**Expand or collapse selected
	
		var boxbtn = document.getElementById(theGroup + "img");
		if(animateToggleLayers){
			//Use effects
			if(document.getElementById(theGroup).style.display == "none"){
				Effect.BlindDown(theGroup,{ duration: 0.5 })
				boxbtn.src = "images/collapse.gif";
			}else{
				Effect.BlindUp(theGroup,{ duration: 0.5 })
				boxbtn.src = "images/expand.gif";
			}
		}else{
			//Just show		
			if (is_nav6up) {										//Navigator6/Firefox
				var theObj = document.getElementById(theGroup);
				if(theObj.className == 'collapsibleon'){			//Collapse
					theObj.className = 'collapsibleoff';
					boxbtn.src = "images/expand.gif";
				}else{												//Expand
					theObj.className = 'collapsibleon';
					boxbtn.src = "images/collapse.gif";
				}										
			}else{													//Opera/IE
				var toEval = theGroup + ".className";		
				if(eval(toEval) == 'collapsibleon'){				//Collapse
					var toEval2 = theGroup + ".className='collapsibleoff'";
					boxbtn.src = "images/expand.gif";			
				}else{												//Expand
					var toEval2 = theGroup + ".className='collapsibleon'";
					boxbtn.src = "images/collapse.gif";
				}
				eval(toEval2);
			}
		}
	}
}

//******************Stores if the shift key is pressed down - allows turning collapsing/expanding all legend groups
function keyPressDown(e){
	evt = e || window.event;
	if(evt.shiftKey){
		shiftIsDown = true;
	}
}
function keyReleased(evt){
	shiftIsDown = false;
}

//----------------------------------------------------------SEARCHING SCRIPTS
//******************Runs query to return the postCode or Street search results
function doMapSearch(){
	var searchString = document.mapform.searchinput.value;			//**Get entered search string.
	if(searchString != ""){	
		//Get type of search (Only Postcode at the moment)
		//if(document.mapform.searchtype[0].checked){									
			var theType = "pcode";		
		//}else if(document.mapform.searchtype[1].checked){				
		//	var theType = "street";
		//}		
		document.mapform.mapaction.value = "search";	
		var qstring = "mapaction=" + document.mapform.mapaction.value + "&searchtype=" + theType + "&searchinput=" + searchString;
		sndReq(qstring);		
	}else{
		alert("Ensure search string entered."); 
	}				
}

//----------------------------------------------------------SHAPE EDITING SCRIPTS
//******************Delete the selected feature
function deleteFeature(){

	//Delete any labels that are selected
	deleteLabel();

	var noSelected = editingLayer.selectedFeatures.length
	var nofeatures = editingLayer.features.length

	//Get selected features' geometry
	for(p=0; p < noSelected;p++){
		var theSelectedFeature = editingLayer.selectedFeatures[p];
		var theSelFeatureGeometry = theSelectedFeature.geometry;	
	}

	//Deselect
	selControl.unselectAll();

	//Delete the feature
	var nofeatures = editingLayer.features.length
	for(p=0; p < nofeatures;p++){
		var theFeatureGeometry = editingLayer.features[p].geometry;	
		if(theFeatureGeometry == theSelFeatureGeometry){
			editingLayer.removeFeatures(editingLayer.features[p])
			break;
		}
	}

}	

//******************Delete the selected label
function deleteLabel(){
	if(Number(document.mapform.labelcount.value) >= 0){					//Has labels
		for(c=0; c <= Number(document.mapform.labelcount.value);c++){		
			var labelObject = document.getElementById('labelback_' + String(c));
			if(labelObject != null){
				if((labelObject.style.backgroundColor.toUpperCase() == "#FF0000") || (labelObject.style.backgroundColor == "rgb(255, 0, 0)")){
					map.removePopup(popup[c]);
				}
			}
		}
	}
}


//----------------------------------------------------------GENERAL SCRIPTS

//******************Hides/displays the relavant tabs
function toggleTabs(passedTab,theSet) {

	if(theSet == "1"){
		var allTabs = new Array("searching","maplayerslayer","policyresultslayer","overviewmap");
	}else if(theSet == "1a"){
		var allTabs = new Array("overviewmap","searching","maplayerslayer","admin");
	}else{
		var allTabs = new Array("maplayerslayer","legend");
	}
	
	var tabsToHide = new Array();
	toHideCnt = 0;	
	for (c=0;c< allTabs.length;c++){
		if(allTabs[c] != passedTab){			
			tabsToHide[toHideCnt] = allTabs[c];
			toHideCnt += 1;
		}
	}

	//SHOW
	//Define the tab to show
	//var tabToShow = document.getElementById(passedTab);
	//tabToShow.style.display = "block";
	$(passedTab).appear({ duration: 0.9, from: 0, to: 1 });
	
	//Define the image to show
	var onImage = document.getElementById(passedTab + "_img");
	onImage.src = "images/" + passedTab + "_on.jpg";
	
	//HIDE
	if(passedTab != "searchresultslayer"){
		for (c=0;c< tabsToHide.length;c++){
			var tabToHide = document.getElementById(tabsToHide[c]);
			if(tabToHide != null){
				tabToHide.style.display = "none";
			}
			var offImage = document.getElementById(tabsToHide[c] + "_img");
			if(offImage != null){
				offImage.src = "images/" + tabsToHide[c] + "_off.jpg";
			}
		}
	}
}

//******************Activates the selected tool
function activateTool(toolType)	{
		
	//Initially ensure watermark layer shows (stops editing working)
	toggleWatermark("html");
	
	//Resey the map action - defines what happend on the click event
	document.mapform.mapaction.value = "";
	
	//Deactivate controls (need to deactivate for delete action after we have retreived the selected features)
	if(toolType !='deletetool'){
		drawPointControl.deactivate();
		drawLineControl.deactivate();
		drawPolyControl.deactivate();	
		modifyControl.deactivate();
	}	
	
	var theMapLayer = document.getElementById("maplayer");				//Get the map layer (Used to update the map cursor)
	
	//Activate the passed tool		 
	if(toolType=='polydrawtool'){
		drawPolyControl.activate();
		click.deactivate();
		toggleTools(toolType);
		theMapLayer.style.cursor='default';				
	}else if(toolType=='edittool'){
		modifyControl.mode = OpenLayers.Control.ModifyFeature.RESHAPE;
		modifyControl.mode |= OpenLayers.Control.ModifyFeature.DRAG;
		modifyControl.activate();
		toggleTools(toolType);
		theMapLayer.style.cursor='default';
		//Hide the watermark layer (stops editing working)
		toggleWatermark("openlayers")			
	}else if(toolType=='pantool'){
		click.deactivate();
		toggleTools(toolType);
		theMapLayer.style.cursor='move';				
	}else if(toolType=='pointdrawtool'){
		drawPointControl.activate();
		click.deactivate();
		toggleTools(toolType);
		theMapLayer.style.cursor='default';
	}else if(toolType=='linedrawtool'){
		drawLineControl.activate();
		click.deactivate();
		toggleTools(toolType);
		theMapLayer.style.cursor='default';		
	}else if(toolType=='deletetool'){
		deleteFeature();									//Detete any selected features
		toggleWatermark("openlayers");						//Hide the watermark layer (stops editing working)
	}else if(toolType=='savetool'){
		saveRepresentation();
	}else if(toolType=='infotool'){
		click.activate();									//Activate the click control
		toggleTools(toolType);
		theMapLayer.style.cursor='pointer';
		document.mapform.mapaction.value = "mapquery";
	}else if(toolType=='labeltool'){
		click.activate();									//Activate the click control
		toggleTools(toolType);
		theMapLayer.style.cursor='pointer';
		document.mapform.mapaction.value = "addlabel";		
	}	 
}

//******************Updates tool images when selected
function toggleTools(passedTool) {
	var allTools = new Array("infotool","pantool"); //,"polydrawtool","pointdrawtool","linedrawtool","edittool","deletetool");	
	for (c=0;c< allTools.length;c++){
		var toolImage = document.getElementById(allTools[c]);
		if(allTools[c] == passedTool){										//Show on state		
			toolImage.src = "images/" + allTools[c] + "ON.bmp";		
		}else{																//Show off state
			toolImage.src = "images/" + allTools[c] + ".bmp";
		}
	}
}

//****************Show Tool tip (Not Used)
function showTip(tipContent,e){

	evt = e || window.event;
	var theX = evt.clientX;
	var theY = evt.clientY;

	$('planvutooltip').innerHTML =  "<p>" + tipContent + "</p>";
	$('planvutooltip').style.display="block";
	$('planvutooltip').style.left = evt.clientX + 10 + "px";
	$('planvutooltip').style.top = evt.clientY - 10 + "px";
}

//****************Hide Tool tip (Not Used)
function hideTip(){
	$('planvutooltip').style.display="none";
}

//******************Toggles between HTML watermark layer and openlayers watermark layer (HTML layer stops feature editing working)
function toggleWatermark(theAction){

	if(theAction == "openlayers"){									//Show the Openlayers image layer		
		if($('watermarklayer').style.display != "none"){			//HTML layer is currently visble therefore openlayers layer needs turning on
			$('watermarklayer').style.display="none";				//Hide HTML watermark layer				
			var currentBounds = map.getExtent();					//Get current Map bounds
			watermarkLayer = new OpenLayers.Layer.Image(
				'watermark',
				waterMarkImagePath,  
				currentBounds, 
				new OpenLayers.Size(600, 600),
				{ singleTile: true, isBaseLayer: false, opacity: 0.2}
			);
			//Add as a image layer to Openlayers
			map.addLayers([watermarkLayer]);
		}
		
	}else if(theAction == "updateopenlayers"){						//Update the position of the Openlayers watermark - called after a pan-zoom performed with this layer displaying				
		map.removeLayer(watermarkLayer);							//Hide Openlayer watermark layer
		var currentBounds = map.getExtent();						//Get current Map bounds
		watermarkLayer = new OpenLayers.Layer.Image(
			'watermark',
			waterMarkImagePath,   
			currentBounds, 
			new OpenLayers.Size(600, 600),
			{ singleTile: true, isBaseLayer: false, opacity: 0.2}
		);
		//Add as a image layer to Openlayers
		map.addLayers([watermarkLayer]);
			
	}else{															//Show the HTML layer
		if($('watermarklayer').style.display == "none"){			//HTML layer is currently invisble	
			map.removeLayer(watermarkLayer);						//Hide Openlayer watermark layer
			$('watermarklayer').style.display="block";				//Show HTML watermark layer
			watermarkLayer = null;
		}
	}
}

//----------------------------------------------------------LABEL SCRIPTS

//******************Setup to start moving the label
function startLabelMove(labelObj){

	//Define if a label is selected
	var moveTheLabel = false;	
	if(Number(document.mapform.labelcount.value) >= 0){					//Has labels
		for(c=0; c <= Number(document.mapform.labelcount.value);c++){		
			var labelObject = document.getElementById('labelback_' + String(c));
			if(labelObject != null){
				if((labelObject.style.backgroundColor.toUpperCase() == "#FF0000") || (labelObject.style.backgroundColor == "rgb(255, 0, 0)")){
					moveTheLabel = true;
					break;
				}
			}
		}
	}
	
	if(moveTheLabel){
		$('editlabel').value = "yes";
		toggleWatermark("html");
	}
	
}
//******************Complete moving the label
function endLabelMove(){
	if($('editlabel').value == "yes"){
		$('editlabel').value = "no";
		toggleWatermark("openlayers");
		document.mapform.mapaction.value = "movelabel"
	}
}

//******************Moves the label based on mousemove action
function moveLabel(e){
	if($('editlabel').value == "yes"){ 
		evt = e || window.event;
		var theX = evt.clientX;
		var theY = evt.clientY;

		if(is_nav6up){
			var theX = evt.layerX;
			var theY = evt.layerY;
		}else{
			var theX = evt.x; 
			var theY = evt.y; 			
		}	
		var pixPos = new OpenLayers.Pixel(theX,theY);		
		thePopupIndex = -1;	
		if(Number(document.mapform.labelcount.value) >= 0){					//Has labels
			for(c=0; c <= Number(document.mapform.labelcount.value);c++){		
				var labelObject = document.getElementById('labelback_' + String(c));
				if(labelObject != null){
					if((labelObject.style.backgroundColor.toUpperCase() == "#FF0000") || (labelObject.style.backgroundColor == "rgb(255, 0, 0)")){
						thePopupIndex = c;
						break;
					}
				}
			}
		}
		if(thePopupIndex != -1){
			popup[thePopupIndex].moveTo(pixPos);
		}	
	}
}

//******************Resizes the label when the text is changed
function updateLabelText(theLabelObj){

	//Define x-y label scaling based on a character height and width
	var pixPerLetterWidth = 8;
	var pixPerLetterHeight = 16;

	//Get the label text and check if a double banked label
	var theLabelString = theLabelObj.value;  
	var hasReturn = theLabelString.indexOf(String.fromCharCode(10));					
	
	//Define the label height and width
	if(hasReturn != -1){
		var theLabelStringArray = theLabelString.split(String.fromCharCode(10));
		var theLongestLine = 0;
		for(c=0; c < theLabelStringArray.length;c++){
			var testLength = theLabelStringArray[c].length;
			if(c==0){
				theLongestLine = theLabelStringArray[c].length;
			}else{
				if(theLabelStringArray[c].length > theLongestLine){
					theLongestLine = theLabelStringArray[c].length;
				}
			}
		}
		var labelWidth = String(theLongestLine * pixPerLetterWidth);
		var labelHeight = String(pixPerLetterHeight * theLabelStringArray.length);		
	}else{
		var labelWidth = String(theLabelString.length * pixPerLetterWidth);
		var labelHeight = String(pixPerLetterHeight);	
	}

	//Update the size of textarea that contains the text
	theLabelObj.style.width = labelWidth + "px";
	theLabelObj.style.height = labelHeight + "px";

	//Get the popup index from the label name
	var sep = theLabelObj.id.indexOf("_");   
	var popupIndex = theLabelObj.id.substring((sep+1));

	//Update the size of layer that contains the text
	var theLabelLayerObj = document.getElementById("labelback_" + popupIndex);
	labelWidth = String(Number(labelWidth) + 2);
	labelHeight = String(Number(labelHeight) + 2);
	theLabelLayerObj.style.width = labelWidth + "px";
	theLabelLayerObj.style.height = labelHeight + "px";

	//Update the size of the OpenLayers popup that contains the label
	popup[popupIndex].updateSize();
}

//******************Select the label (Highlights it)
function selectLabel(theLabelObj){
	deselectLabels();									//Deselect any other labels selected
	theLabelObj.style.backgroundColor = "#FF0000";		//Hightlight the clicked label
}

//******************Deselect any other labels selected
function deselectLabels(){
	if(Number(document.mapform.labelcount.value) >= 0){					//Has labels
		for(c=0; c <= Number(document.mapform.labelcount.value);c++){		
			var labelObject = document.getElementById('labelback_' + String(c));
			if(labelObject != null){
				labelObject.style.backgroundColor = "#FFFFFF";
			}
		}
	}
}


//----------------------------------------------------------USER MESSAGE SCRIPTS

//****************Show or hide the welcome message on opening the map page
function showMessage(theAction){	
	//Turn on-off	
	if(theAction == "on"){
		$('userprompt').appear({ duration: 4, from: 0, to: 1 });						
	}else{
		$('userprompt').style.display="none";	
	}
}

//****************Check if the cookie exists
function getCookie(cookieName)  {
	//Checks if a cookie of the passed variable name exists
    var arg = cookieName + "="	
    var argLength = arg.length
    var cookieLength = document.cookie.length

 	if(cookieLength > 0){	
		var pos  = (document.cookie.indexOf(arg))
		if(pos != -1){
			var offset =pos +  argLength
			var end  = (document.cookie.indexOf(";",pos))
			if(end == -1){
				end = document.cookieLength
			}			
   			return unescape(document.cookie.substring(offset, end))
		}else{
			return null;
		}
	}else{
		return null;
	}

}

//****************Register cookie
function register(theName) {		
	//Registers the cookie (ie. to signify the user never wants to see the opening page again.
	var userName = "Unknown User"									//Set user as unknown
	// If no cookie called exists called theName variable, creste one.
	if(getCookie(theName) == null) {
		// Set the expiration date to a date exactly one year in the future.
		var expdate = new Date()
		expdate.setTime(expdate.getTime() + (1000 * 60 * 60 * 24 * 365)); 
		//Define the cookie.
		setCookie(theName, userName, expdate);  
	 }
}

//****************Set cookie
function setCookie(name, value) {
   
    // Capture all the arguments passed to the setCookie() function.
    var argv = setCookie.arguments

    // Determine the number of arguments passed into this function
    var argc = setCookie.arguments.length
	
    // We expect the 3rd argument passed in to be the expiration date.
    // If there isn't a third argument, set the expires variable to null.
    // (An expiration date of null marks a cookie as transient.  Transient
    // cookies are not saved to disk.)
    var expires = (argc > 2) ? argv[2] : null

    // We expect the 4th argument passed in to be the path.
    // If there isn't a fourth argument, set the path variable to null. 
    var path = (argc > 3) ? argv[3] : null

    // We expect the 5th argument passed in to be the domain.
    // If there isn't a fifth argument, set the domain variable to null. 
    var domain = (argc > 4) ? argv[4] : null

    // We expect the 6th argument passed in to be true or false, 
    // depending on whether this cookie is secure (can be transmitted
    // only to a secure server via https) or not.
    // If there isn't a sixth argument, set the secure variable to false. 
    var secure = (argc > 5) ? argv[5] : false

    // Set the cookie.
    document.cookie = name + "=" + escape(value) + 
        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
        ((path == null) ? "" : ("; path=" + path)) + 
        ((domain == null) ? "" : ("; domain=" + domain)) + 
        ((secure == true) ? "; secure" : "")
		
}

//****************Delete cookie
function deleteCookie(toDelete){
	if(getCookie(introCookieName) != null) {								//cookie exists, delete it!
		var expired = new Date()
		expired.setTime(expired.getTime() - 1000000000)
		var cookieValue = getCookie(toDelete)
		document.cookie = toDelete + "=" + cookieValue + ";expires=" + expired.toGMTString
	}
}

//----------------------------------------------------------ANNOTATION SAVING SCRIPTS

//****************Saves the current map view as a map image (including any drawn annotations)
function saveRepresentation(){
	//Get list of all the layers that are visible (need to pass this to ensure we only query visible layers)
	var theMapLayersString = getMapLayers(); 				
	var theMapLayerInfo = theMapLayersString.split("|");   
	//Get current view extent       		
	var theViewExtent = map.getExtent().toBBOX();						
	//Get the drawn annotations
	var annotations = getFeatures();	
	var labelString = getLabelFeatures();
		
	//Set query string to pass all info to image creation script
	if((annotations[0] != "none") || (labelString != "")){
		//Store the annotations as a "|" seperated string
		var annotationsString = "";
		for(c=0; c < annotations.length; c++){
			if(c==0){
				annotationsString = annotations[c];
			}else{
				annotationsString += "|" + annotations[c];
			}
		}		
		var qstring = "mapaction=save&extent=" + theViewExtent + "&mapLayers=" + theMapLayerInfo[0] + "&layerGroups=" + theMapLayerInfo[1] + "&layerGroups2=" + theMapLayerInfo[2] + "&annotations=" + annotationsString + "&labels=" + labelString;
		sndReq2(qstring);
	}else{
		alert('Please ensure that annotations have been drawn before saving.'); 
	}
}

//****************Run mapserver mapscript functions to return save a map image of the requested area
function sndReq2(qstring) {
	http = createRequestObject();
	http.open('get', 'savemapimage.php?' + qstring); 
	http.onreadystatechange = saveMapResponse;
	http.send(null);
}

//****************Response from creating the mmap image
function saveMapResponse(){
	if(http.readyState == 4){	
		var response = http.responseText;
		//alert(response)
		if((response.indexOf("error") == -1) && (response != "")){
			alert("Image saved OK.");	
		}else{
			alert("Image could not be saved.");
		}
	}
}

//****************Stores all drawn annotaion features in an array
function getFeatures(){
	var annotations = new Array();
	if(editingLayer.features.length > 0){	
		for(c=0; c < editingLayer.features.length;c++){	
			var theGeometryAsString = editingLayer.features[c].geometry;
			annotations[c] = theGeometryAsString		
		}
	 }else{		
		annotations[0] = "none"; 
	 } 
	return annotations;
}

//****************Stores all drawn annotaion label features in an array
function getLabelFeatures(){
	var labelsString = "";
	var labelCnt = 0;
	
	if(Number(document.mapform.labelcount.value) >= 0){					//Has labels
		for(c=0; c <= Number(document.mapform.labelcount.value);c++){
			var labelID = "label_" + String(c);
			if($(labelID) != null){
				labelCnt +=1;
				var popupPos = popup[c].lonlat;
				theX = popupPos.lon;
				theY =  popupPos.lat;
				if(labelCnt == 1){
					labelsString = $(labelID).value + "|" + theX + "|" + theY;
				}else{
					labelsString += "|" + $(labelID).value + "|" + theX + "|" + theY;
				}
			}
		}
	}
	//Return info on the labels as a string "LABEL|X|Y|LABEL|X|Y......."
	return labelsString;
}

//-------------------------------End of  File