/*
Javascript file for customizemap page
Called from customizemaps.php
Nov 2009
*/

//------------------------------------------------------------GLOBALS	
var map;								//Openelayers map layer

//TESTING
//var zoomResolutions = new Array(2,1,0.5);
var zoomScales = new Array(8000,1900,950,475);     //Array(3800,1900,950,475);
var baseMapLayers = 'baselayer'; 
var mapExtentArray = new Array();
var avaialableMapsArrayIndex = -1;

var http;
var extentLayer;						//Layer that contains the map extent
var baselayer;							//Layer that contains the mapping
var annoLayer;							//Layer that contains the user annotation 
var polygonExtentFeature;
var drawFeatureControl;					//Openlayers drawing controls
var drawPointControl;
var drawLineControl;
var drawPolyControl;
var modifyControl;
var modifyExtentControl;
var zoomBoxControl;
var selectedGraphic = "star"; 
var selectedLabel = "";
var graphicLabels = ["", "", "", "", "", ""];				
var graphics = ["star", "cross", "x", "square", "triangle", "circle"];
	
/*OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '2';
OpenLayers.Feature.Vector.style['default']['fillColor'] = '#ffffff';
OpenLayers.Feature.Vector.style['default']['strokeColor'] = '#ff0000';
OpenLayers.Feature.Vector.style['default']['fillOpacity'] = '0.4';
OpenLayers.Feature.Vector.style['default']['graphicOpacity'] = '1';
OpenLayers.Feature.Vector.style['select']['strokeWidth'] = '3';
OpenLayers.Feature.Vector.style['select']['fillColor'] = '#ffffff';
OpenLayers.Feature.Vector.style['select']['strokeColor'] = '#0000ff';
OpenLayers.Feature.Vector.style['select']['fillOpacity'] = '0.2';
OpenLayers.Feature.Vector.style['select']['graphicOpacity'] = '1';*/


OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '3';
OpenLayers.Feature.Vector.style['default']['fillColor'] = '#FFFFFF';
OpenLayers.Feature.Vector.style['default']['strokeColor'] = '#000000';
OpenLayers.Feature.Vector.style['default']['fillOpacity'] = '0.5';
OpenLayers.Feature.Vector.style['default']['graphicOpacity'] = '1';
OpenLayers.Feature.Vector.style['default']['strokeDashstyle'] = 'dash';
OpenLayers.Feature.Vector.style['select']['strokeWidth'] = '3';
OpenLayers.Feature.Vector.style['select']['fillColor'] = '#FFFFFF';
OpenLayers.Feature.Vector.style['select']['strokeDashstyle'] = 'dash';
OpenLayers.Feature.Vector.style['select']['strokeColor'] = '#000000';
OpenLayers.Feature.Vector.style['select']['fillOpacity'] = '0.5';
OpenLayers.Feature.Vector.style['select']['graphicOpacity'] = '1';

var annostyle = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
        {fillColor: "white", fillOpacity: 0.3, strokeWidth: 2, graphicOpacity: 1, strokeDashstyle: "none", strokeColor: "red"},
        OpenLayers.Feature.Vector.style["default"]));


var avaialableMapISBNs = new Array ("9781868097654","9781868099658","9781868099665","9781868098934","9781868098620","9781868099382","9781868098873","9781868099191","9781868098903","9781868099078","9781868099375","9781868099696","9781868099788","9781868098118","9781868099795","9781868098200","9781868097975","9781868097920","9781770260184","9781868097999","M2572");
var avaialableMapNames = new Array ("Africa Commercial","Botswana Physical","Botswana Political","Free State Provincial","Gauteng Provincial","Limpopo Provincial","Mozambique","Namibia","North West Provincial","Northern Cape Provincial","Pretoria Regional ","RSA Provincial","SADC Political [2 sheets]","Southern Africa Physical","Southern Africa Political","Western Cape Provincial","World Commercial","World Executive Antique","World Executive Large [4 sheets]","World Physical","World Political");
var avaialableMapSizes = new Array ("1.05x0.97","1.10x0.80","1.10x0.80","0.87x1.12","1.09x0.91","0.74x1.08","1.44x0.93","0.91x0.67","0.65x0.98","0.89x1.14","1.01x1.47","0.89x1.02","1.61x1.32","0.94x1.21","0.84x1.20","0.84x1.09","1.16x1.79","1.05x1.57","1.55x2.65","0.66x0.98","0.66x0.98");
var avaialableMapScales= new Array (8000000,6500000,6500000,600000,250000,650000,1400000,1750000,700000,1000000,65000,2000000,3000000,2500000,3000000,700000,17000000,25000000,1000000,32000000,40000000);
var openingMapScales= new Array (8000000,6500000,6500000,600000,250000,650000,1400000,1750000,700000,1000000,65000,2000000,3000000,2500000,3000000,700000,17000000,25000000,1000000,32000000,40000000);


//------------------------------------------------------------MAP SETUP
//**************************************Defines which map to use
function defineMap(theMap,passedCoordinates,passedAnno,passedAnnoLabels,passedAnnoSymbols){
	
	//Set the labels for each of the graphics if been passed
	if(passedAnnoLabels != ""){
		var passedAnnoLabelsArray = passedAnnoLabels.split("|");
		var passedAnnoSymbolsArray = passedAnnoSymbols.split("|");
		for(l=0; l < passedAnnoSymbolsArray.length; l++){
			for(g=0; g < graphics.length; g++){
				if(graphics[g] == passedAnnoSymbolsArray[l]){
					graphicLabels[g] = passedAnnoLabelsArray[l];
					break;
				}
			}
		}
	}
	
	
	if(theMap == ""){
		//Initialization - show opening message
		//alert("Start by choosing a map to");
			
	}else{
		for(c=0; c < avaialableMapISBNs.length;c++){
			if(avaialableMapISBNs[c] == theMap){
				avaialableMapsArrayIndex = c;
			}
		}	
		//If a map has been found initialize it
		if(avaialableMapsArrayIndex != -1){
			initMap(avaialableMapsArrayIndex,passedCoordinates,passedAnno,passedAnnoLabels,passedAnnoSymbols);
		}else{
			alert("This map is currently unavailable for customisation online.  Please call  Cindy-Lee Arendse on 021 462 4360 to discuss your requirements or choose another map to customise.");
			showLayers("step1ON")
		}
		
		document.frmMap.baseMapType.value = theMap;
	}
}
//**************************************Initializes the map
function initMap(avaialableMapsArrayIndex,passedCoordinates,passedAnno,passedAnnoLabels,passedAnnoSymbols){

	//Define graphic map styles
	var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
	//layer_style.fillOpacity = 0.2;
	//layer_style.graphicOpacity = 1;

	/*Map extent styles
	mapextenstyle = OpenLayers.Util.extend({}, layer_style);
	mapextenstyle.strokeColor = "#ff0000";
	mapextenstyle.fillColor = "#ff0000";
	mapextenstyle.strokeWidth = 3;
	mapextenstyle.fillOpacity = 0.3;
	*/
	
	//If a map already set destroy it
	if(map != null){
		map.destroy();
	}
	
	//Define the extent as an array
	var mapSizeString = avaialableMapSizes[avaialableMapsArrayIndex];
	var mapSizeArray = mapSizeString.split("x");		 
	//var mapExtentArray = new Array(0,0,	(Number(mapSizeArray[1]) * 1000),(Number(mapSizeArray[0]) * 1000));	 		//In mm (origin always 0,0)
	mapExtentArray[0] = 0;
	mapExtentArray[1] = 0;
	mapExtentArray[2] = Number(mapSizeArray[1]) * 1000;
	mapExtentArray[3] = Number(mapSizeArray[0]) * 1000;
	
	//Define the map file
	var theMapFile = avaialableMapISBNs[avaialableMapsArrayIndex] + ".map";   
				 			 
	//Define the map and relvant options
	map = new OpenLayers.Map( $('mapContainerWide'), { controls: [], 
		units:'m',  
		maxExtent: new OpenLayers.Bounds(mapExtentArray[0],mapExtentArray[1],mapExtentArray[2],mapExtentArray[3]),				
		scales: zoomScales
		});

	//Create base mapping layer				  
	baselayer = new OpenLayers.Layer.MapServer( "Base",
					"http://77.246.172.232/cgi-bin/mapserv.exe",
					{ map:theMapFile,
					  layers: baseMapLayers}, { singleTile: false, isBaseLayer: true, transitionEffect: 'resize'});				  
	
	//Create layer for Extents to be drawn on
	extentLayer = new OpenLayers.Layer.Vector("Map Extents");
	
	//Add the annotation layer
	annoLayer = new OpenLayers.Layer.Vector("Annotation",{styleMap: annostyle});
			
	//Add layers to the map and zoom to map extent		
	map.addLayers([baselayer, extentLayer, annoLayer]);
	map.fractionalZoom = true;
	var bounds = new OpenLayers.Bounds(mapExtentArray[0],mapExtentArray[1],mapExtentArray[2],mapExtentArray[3]);
	//var testbounds = new OpenLayers.Bounds(mapExtentArray[0],mapExtentArray[1],mapExtentArray[3],mapExtentArray[3]);
	//var testbounds = new OpenLayers.Bounds(mapExtentArray[0],mapExtentArray[1],mapExtentArray[3],mapExtentArray[3]);
	//alert(testbounds.toBBOX())
	//map.zoomToExtent(testbounds)
	//alert(String(mapExtentArray[0]) + "," + String(mapExtentArray[1]) + "," + String(mapExtentArray[2]) + "," + String(mapExtentArray[3]))
	if (!map.getCenter()) map.zoomToExtent(bounds);
	 	 
	//Add map controls 
	map.addControl(new OpenLayers.Control.PanZoomBar());
  	map.addControl(new OpenLayers.Control.Navigation());
		
	//map.addControl(new OpenLayers.Control.Scale()); 
	//map.addControl(new OpenLayers.Control.MousePosition());
	//map.addControl(new OpenLayers.Control.LayerSwitcher());

	//Mark E Zoom control
	zoomBoxControl = new OpenLayers.Control.ZoomBox({alwaysZoom:true});  	
	map.addControl(zoomBoxControl);

 	//Draw feature controls for map extent and user annotation
	drawFeatureControl = new OpenLayers.Control.DrawFeature(extentLayer,
				OpenLayers.Handler.RegularPolygon,
				{handlerOptions: {sides: 4}})	  
	map.addControl(drawFeatureControl);

	drawPointControl = new OpenLayers.Control.DrawFeature(annoLayer,OpenLayers.Handler.Point);
    drawLineControl = new OpenLayers.Control.DrawFeature(annoLayer, OpenLayers.Handler.Path);
    drawPolyControl = new OpenLayers.Control.DrawFeature(annoLayer,OpenLayers.Handler.Polygon);
	map.addControl(drawPointControl);
	map.addControl(drawLineControl);
	map.addControl(drawPolyControl); 
	 
	//Modify controld for extent and anno layers 	 
	modifyControl =  new OpenLayers.Control.ModifyFeature(annoLayer);	
	map.addControl(modifyControl);	  
	modifyExtentControl =  new OpenLayers.Control.ModifyFeature(extentLayer);	
	map.addControl(modifyExtentControl);	
	  
	//Register map evemts 
	//Re-Centre the map if the extent is moved or edited
	extentLayer.events.register('featureadded', extentLayer, function(evt) { 
	if(extentLayer.features.length > 0){
		  //Zoom to shape
		  var theGeometryasBounds = extentLayer.features[0].geometry.getBounds();
		  var theExtentWidth = theGeometryasBounds.getWidth();
		  var theExtentHeight = theGeometryasBounds.getHeight();
		  	  
		  //Define full map extent is being used
		  if(avaialableMapsArrayIndex == -1){
		  	var isFullExtent = false;
		  }else{  
		  	var minX = mapExtentArray[0];
		  	var minY = mapExtentArray[1];
		  	var maxX = mapExtentArray[2];
		  	var maxY = mapExtentArray[3];
			var theFullExtentWidth = maxX - minX;
			var theFullExtentHeight = maxY - minY;				  
			if((theExtentWidth == theFullExtentWidth) && (theExtentHeight == theFullExtentHeight)){
				var isFullExtent = true;
			}else{
				var isFullExtent = false;
		    }
		  }
		  if(isFullExtent == false){
			  var centreLatLon = theGeometryasBounds.getCenterLonLat();
			  var theX = centreLatLon.lon;
			  var theY = centreLatLon.lat; 
			  var blx = (theX - (theExtentWidth/2)) - (theExtentWidth/4);
			  var bly = (theY - (theExtentHeight/2)) - (theExtentHeight/4);
			  var urx = (theX + (theExtentWidth/2)) + (theExtentWidth/4);
			  var ury = (theY + (theExtentHeight/2)) + (theExtentWidth/4);
			  var bounds = new OpenLayers.Bounds(blx,bly,urx,ury);		  
			  map.zoomToExtent(bounds);
			  drawFeatureControl.deactivate();
			  modifyControl.deactivate();
			  modifyExtentControl.deactivate();
			  //toggleTools("pantool");
			  activateTool("pantool");
			  //document.getElementById("bTips").style.display = "none";	
		  }
	  }  
	}); 
	extentLayer.events.register('featuremodified', extentLayer, function(evt) { 
		if(extentLayer.features.length > 0){
			thegeometryasBounds = extentLayer.features[0].geometry.getBounds();
			var centreLatLon = thegeometryasBounds.getCenterLonLat();
			map.setCenter(centreLatLon,map.getZoom(),false,false);    
		}
	}); 
	
	//Remove existing map extent before a new one is added
	extentLayer.events.register('beforefeaturesadded', extentLayer, function(evt) { 
		extentLayer.removeFeatures(extentLayer.features[0]);		
	}); 
	
	annoLayer.events.register('featureadded', annoLayer, function(evt) { 
		if(annoLayer.features.length > 0){
			var theAnnoFeature = annoLayer.features[annoLayer.features.length-1];
			//Apply style for point features
			var testGeom = String(theAnnoFeature.geometry);
			if(testGeom.indexOf("POINT(") == 0){
			
				defAnnoStyle = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
				defAnnoStyle.fillOpacity= 0.3;
				defAnnoStyle.graphicOpacity= 1;
				
				if(document.getElementById("symbolLabelText") == null){						//Text box not visible - redrawing a label use stored label instead
					defAnnoStyle.label = selectedLabel;
				}else{
					defAnnoStyle.label = document.getElementById("symbolLabelText").value;
				}
				
				defAnnoStyle.fontColor = "#000000";
				defAnnoStyle.fontSize = "20px";
				defAnnoStyle.fontFamily = "Arial";
				defAnnoStyle.fontWeight = "normal";
				defAnnoStyle.labelAlign = "bl";
				
				//defAnnoStyle.labelXOffset = "20px";   //OFFSET NOT WORKING
				//defAnnoStyle.labelYOffset = "20px";
			
				defAnnoStyle.fillColor= "white";
				defAnnoStyle.strokeWidth= 2;	
				defAnnoStyle.strokeDashstyle= "none";
				defAnnoStyle.strokeColor=  "red";
				defAnnoStyle.pointerEvents= "visiblePainted";
				defAnnoStyle.graphicName = selectedGraphic
				theAnnoFeature.style = defAnnoStyle;
				
				
				if(document.getElementById("symbolLabelText") == null){						//Text box not visible - redrawing a label use stored label instead
					theAnnoFeature.attributes.id = selectedLabel;  		//Store label as id of the shape
				}else{
					theAnnoFeature.attributes.id = document.getElementById("symbolLabelText").value;
				}
					
				theAnnoFeature.attributes.sym = selectedGraphic;									//Store symbol used to draw the shape
				
				//Store the label used to display this point
				if(document.getElementById("symbolLabelText") == null){
					//If redrawing already stored
				}else{
					for(g=0; g < graphics.length; g++){
						if(graphics[g] == selectedGraphic){			
							graphicLabels[g] = document.getElementById("symbolLabelText").value;
							break;
						}
					}
				}

				annoLayer.redraw();
			}	
			activateTool("pantool");
			//document.getElementById("bTips").style.display = "none";
		}	
	});
	
			
				
	//Redraw any passed extent or user annoation
	if(passedCoordinates != ""){
		recreateExtent(passedCoordinates);	
		if(passedAnno != ""){					//Anno items passed need to be recreated
			recreateAnno(passedAnno,passedAnnoLabels,passedAnnoSymbols);
		}		
	}	
		
}

//------------------------------------------------------------MAP EXTENT AND ANNOATION DRAWING SCRIPTS

//**************************************Function to add an extent to the map
function addExtent(theSize, theType){
   
	//Get the map centre
	var theMapCentre = map.getCenter(); 
	var centreX = theMapCentre.lon; 
	var centreY = theMapCentre.lat;  
	
	if(theType == "rect"){  

		//Remove any existing
		if(polygonExtentFeature != null){
			extentLayer.destroyFeatures()
		}
	
		var pointList = [];
		var newPoint = new OpenLayers.Geometry.Point(centreX - (theSize/2),centreY - (theSize/2));
		pointList.push(newPoint); 
		var newPoint = new OpenLayers.Geometry.Point(centreX - (theSize/2),centreY + (theSize/2));
		pointList.push(newPoint);  
		var newPoint = new OpenLayers.Geometry.Point(centreX + (theSize/2),centreY + (theSize/2));
		pointList.push(newPoint);  
		var newPoint = new OpenLayers.Geometry.Point(centreX + (theSize/2),centreY - (theSize/2));
		pointList.push(newPoint);    
		pointList.push(pointList[0]);
		
		var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
		polygonExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);		
		extentLayer.addFeatures(polygonExtentFeature);
		
		//Zoom to shape
		var theGeometryasBounds = extentLayer.features[0].geometry.getBounds();
		var theExtentWidth = theGeometryasBounds.getWidth();
		var theExtentHeight = theGeometryasBounds.getHeight();
		var centreLatLon = theGeometryasBounds.getCenterLonLat();
		var theX = centreLatLon.lon;
		var theY = centreLatLon.lat; 
		var blx = (theX - (theExtentWidth/2)) - (theExtentWidth/4);
		var bly = (theY - (theExtentHeight/2)) - (theExtentHeight/4);
		var urx = (theX + (theExtentWidth/2)) + (theExtentWidth/4);
		var ury = (theY + (theExtentHeight/2)) + (theExtentWidth/4);
		var bounds = new OpenLayers.Bounds(blx,bly,urx,ury);
		map.zoomToExtent(bounds);
	}
}

//******************Recreate the user drawn annotaion on the  main interface
function recreateAnno(passedAnno,passedAnnoLabels,passedAnnoSymbols){

	//Destroy any existing featyures
	annoLayer.destroyFeatures();
	
	//Loop thru each anno item
	var fullAnnoArray = passedAnno.split("|");	
	var fullAnnoLabelsArray = passedAnnoLabels.split("|");
	var fullAnnoSymbolsArray = passedAnnoSymbols.split("|");
	
	for(a=0; a < fullAnnoArray.length; a++){
		var annoItem = fullAnnoArray[a];
		if(annoItem.indexOf("POLYGON") != -1){
			var newGeomString = annoItem.substring(9,(annoItem.length - 2));
			var pointList = [];			
			var theCoordArray = newGeomString.split(",");		
			for (c=0; c< theCoordArray.length ;c++){
				var theXY =  theCoordArray[c].split(" ");
				var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
				pointList.push(newPoint);
			}			
			var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
			polygonFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);  //,annostyle);
			annoLayer.addFeatures(polygonFeature);
		
		}else if(annoItem.indexOf("LINESTRING") != -1){
			var newGeomString = annoItem.substring(11,(annoItem.length - 1));		
			var pointList = [];			
			var theCoordArray = newGeomString.split(",");		
			for (c=0; c< theCoordArray.length ;c++){
				var theXY =  theCoordArray[c].split(" ");
				var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
				pointList.push(newPoint);
			}			
			lineFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(pointList));
			annoLayer.addFeatures(lineFeature);
		
		}else if(annoItem.indexOf("POINT") != -1){
			var newGeomString = annoItem.substring(6,(annoItem.length - 1));	
			var theXY =  newGeomString.split(" ");			
			pointFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(theXY[0],theXY[1]));	
			selectedGraphic = fullAnnoSymbolsArray[a];
			selectedLabel = fullAnnoLabelsArray[a];	
			annoLayer.addFeatures(pointFeature);	
		}
	}
}



//**************************************Draws extent that covers the full map
function chooseFullMap(){

	var minX = mapExtentArray[0];
	var minY = mapExtentArray[1];
	var maxX = mapExtentArray[2];
	var maxY = mapExtentArray[3];

	//Remove any existing
	if(polygonExtentFeature != null){
		extentLayer.destroyFeatures()
	}
	
	var pointList = [];
	var newPoint = new OpenLayers.Geometry.Point(minX,minY);
	pointList.push(newPoint); 
	var newPoint = new OpenLayers.Geometry.Point(minX,maxY);
	pointList.push(newPoint);  
	var newPoint = new OpenLayers.Geometry.Point(maxX,maxY);
	pointList.push(newPoint);  
	var newPoint = new OpenLayers.Geometry.Point(maxX,minY);
	pointList.push(newPoint);    
	pointList.push(pointList[0]);
		
	var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
	polygonExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);		
	extentLayer.addFeatures(polygonExtentFeature);
	
}

//**************************************Resets the map session
function destroyMap(){
	extentLayer.destroyFeatures()
	map.zoomToMaxExtent();
}

//**************************************Deletes all drawn extents
function destroyExtent(){
	extentLayer.destroyFeatures()
}

//**************************************Draws a map extent over the map from the passed coordinate string	  
function recreateExtent(passedCoordinates){	
	//Remove any existing map extents
	extentLayer.destroyFeatures();
	
	//Create the map exten from the coordinates and add
	var pointList = [];			
	var theCoordArray = passedCoordinates.split(",");		
	for (c=0; c < theCoordArray.length ;c++){
		var theXY =  theCoordArray[c].split(" ");
		var newPoint = new OpenLayers.Geometry.Point(theXY[0],theXY[1]);
		pointList.push(newPoint);
	}					
	var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
	polygonExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null);
	extentLayer.addFeatures(polygonExtentFeature);

	/*Zoom to shape
	var theGeometryasBounds = extentLayer.features[0].geometry.getBounds();
	var theExtentWidth = theGeometryasBounds.getWidth();
	var theExtentHeight = theGeometryasBounds.getHeight();
	var centreLatLon = theGeometryasBounds.getCenterLonLat();
	var theX = centreLatLon.lon;
	var theY = centreLatLon.lat;	
	var blx = (theX - (theExtentWidth/2)) - (theExtentWidth/4);
	var bly = (theY - (theExtentHeight/2)) - (theExtentHeight/4);
	var urx = (theX + (theExtentWidth/2)) + (theExtentWidth/4);
	var ury = (theY + (theExtentHeight/2)) + (theExtentWidth/4);
	var bounds = new OpenLayers.Bounds(blx,bly,urx,ury);
	map.zoomToExtent(bounds);
*/
}

//******************Delete the selected annotation feature
function deleteFeature(){

	var noSelected = annoLayer.selectedFeatures.length
	var nofeatures = annoLayer.features.length

	//Get selected features' geometry
	for(p=0; p < noSelected;p++){
		var theSelectedFeature = annoLayer.selectedFeatures[p];
		var theSelFeatureGeometry = theSelectedFeature.geometry;	
	}

	//Deselect
	//selControl.unselectAll();
	modifyControl.deactivate();
	modifyControl.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])
			break;
		}
	}

	//If the map extent is selected destroy it
	var extentSelected = extentLayer.selectedFeatures.length
	if(extentSelected != 0){
		destroyExtent();
	}

}	
//******************Defines the symbol to use for the point anno
function setPointSymbol(passedSymbol){
	for(g=0; g < graphics.length; g++){
		if(graphics[g] == passedSymbol){
			selectedGraphic = graphics[g];
			//selectedLabel = document.getElementById("symbolLabelText").value;
			drawPointControl.activate();
			document.getElementById("symbolLabel").style.display = "block";			
			document.getElementById("symbolLabelText").value = graphicLabels[g];		//Show stored label for this point
			break;
		}
	}
}


//------------------------------------------------------------GENRAL SCRIPTS

//******************If user has pressed "delete" button call the delete function
function keyPressDown(e){
	evt = e || window.event;	
	var unicode=evt.keyCode? evt.keyCode : evt.charCode
	if(unicode == 46){
		deleteFeature();
	}	
}

function showLayers(theLayers){
	var tabImage = document.getElementById('tabImage')
	tabImage.src = "images/" + theLayers + ".jpg"
	var allLayers = new Array("step1ON","step2ON"); 
	for(m=0; m < allLayers.length;m++){
		if (theLayers == allLayers[m]){
		  var layerObj = document.getElementById(allLayers[m])
		  layerObj.className='layerOn'
		  
		}else{
		  var layerObj = document.getElementById(allLayers[m])
		  layerObj.className='layerOff'
		}
	}
}

//****************Create request object
function createRequestObject() {
	var ro;		
	if (window.XMLHttpRequest) { 				// Mozilla, Safari,...
		ro = new XMLHttpRequest();
		//if (ro.overrideMimeType) {
		//	ro.overrideMimeType('text/xml');
		//}
	}else if (window.ActiveXObject) { 			// IE
		try {
			ro = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			ro = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	return ro;	
}
//**************************************Activates for use the selected tool on the toolbar	 
function activateTool(toolType)	{

	var theMapLayer = document.getElementById("mapContainerWide");				//Get the map layer (Used to update the map cursor)

	if(toolType !='deletetool'){
		drawFeatureControl.deactivate();
		modifyControl.deactivate();
		modifyExtentControl.deactivate();
		drawPointControl.deactivate();
		drawLineControl.deactivate();
		drawPolyControl.deactivate();
		zoomBoxControl.deactivate();
	}
	
	//Activate the passed tool
	if (toolType=='drawextent'){
		if(polygonExtentFeature != null){
			extentLayer.destroyFeatures();
		}
		drawFeatureControl.handler.irregular = true;
		drawFeatureControl.activate();
		toggleTools(toolType);		 
	}else if(toolType=='polydrawtool'){
		drawPolyControl.activate();
		toggleTools(toolType);
		theMapLayer.style.cursor='default';				
	}else if(toolType=='edittool'){			
		modifyExtentControl.deactivate();		
		modifyControl.mode = OpenLayers.Control.ModifyFeature.RESHAPE;
		modifyControl.mode |= OpenLayers.Control.ModifyFeature.DRAG;
		modifyControl.activate();
		toggleTools(toolType);
		theMapLayer.style.cursor='default';	
	
	}else if(toolType=='edittool2'){
		modifyControl.deactivate();	
		modifyExtentControl.mode = OpenLayers.Control.ModifyFeature.DRAG;
		modifyExtentControl.mode |= OpenLayers.Control.ModifyFeature.RESIZE;
		modifyExtentControl.activate();
		toggleTools(toolType);
		theMapLayer.style.cursor='default';						
	}else if(toolType=='pantool'){
		toggleTools(toolType);
		theMapLayer.style.cursor='pointer';				
	}else if(toolType=='pointdrawtool'){
		//drawPointControl.activate();
		toggleTools(toolType);
		theMapLayer.style.cursor='default';
	}else if(toolType=='linedrawtool'){
		drawLineControl.activate();
		toggleTools(toolType);
		theMapLayer.style.cursor='default';		
	}else if(toolType=='deletetool'){
		deleteFeature();									//Detete any selected features		
	}else if(toolType=='zoomtool'){
		zoomBoxControl.activate();							//Activate mark e zoom
		toggleTools(toolType);
		theMapLayer.style.cursor='crosshair';
	}else if(toolType=='resettool'){
		document.frmMap.submit();		
	}
	
}	

//******************Updates tool images when selected
function toggleTools(passedTool) {
	var allTools = new Array("drawextent","pantool","zoomtool","polydrawtool","pointdrawtool","linedrawtool","edittool");
	for (c=0;c< allTools.length;c++){
		var toolImage = document.getElementById(allTools[c]);
		if(allTools[c] == passedTool){										//Show on state		
			toolImage.src = "customizemap/images/" + allTools[c] + "ON.png";		
		}else{																//Show off state
			toolImage.src = "customizemap/images/" + allTools[c] + ".png";
		}
	}
}

//**************************************Selects or deselects customer logo
function chooseLogo(){
	if(document.getElementById("chkLogo").checked){
		document.getElementById("chkLogo").value = "yes";
		//Show message
		document.getElementById("logomessage").style.display = "block";
	}else{
		document.getElementById("chkLogo").value = "no";
		//Hide message
		document.getElementById("logomessage").style.display = "none";
	}
}

//**************************************Selects or deselects customer title
function chooseTitle(){
	if(document.getElementById("chkTitle").checked){
		document.getElementById("chkTitle").value = "yes";
		document.getElementById("titleInfo").style.display = "block";
	}else{
		document.getElementById("chkTitle").value = "no";
		document.getElementById("txtTitle").value = "";
		document.getElementById("titleInfo").style.display = "none";
	}
}

//**************************************Selects customer logo position
function chooseLogoPosition(selObj){
	document.getElementById("selectedLogoPos").value = selObj.value;
}

//**************************************Selects customer title position
function chooseTitlePosition(selObj){
	document.getElementById("selectedTitlePos").value = selObj.value;
}

//---------------------------------------------------------------------------CONFIRM SCRIPTS

//**************************************Stores all drawn annotaion features in an array
function getAnnoFeatures(){
	var annotations = new Array();
	if(annoLayer.features.length > 0){	
		for(c=0; c < annoLayer.features.length;c++){	
			var theGeometryAsString = annoLayer.features[c].geometry;
			annotations[c] = theGeometryAsString		
		}
	 }else{		
		annotations[0] = "none"; 
	 } 
	return annotations;
}


//**************************************Stores all drawn annotaion feature labels in an array (for point features only)
function getAnnoFeatureLabels(){
	var annotationLabels = new Array();	
	if(annoLayer.features.length > 0){	
		for(c=0; c < annoLayer.features.length;c++){
			if(annoLayer.features[c].attributes.id != null){	
				annotationLabels[c] = annoLayer.features[c].attributes.id;
			}else{
				annotationLabels[c] = "";
			}		
		}
	 }else{		
		annotationLabels[0] = "none"; 
	 } 
	return annotationLabels;
}
//**************************************Stores all drawn annotaion feature symbols in an array (for point features only)
function getAnnoFeatureSymbols(){
	var annotationSymbols = new Array();
	if(annoLayer.features.length > 0){	
		for(c=0; c < annoLayer.features.length;c++){
			if(annoLayer.features[c].attributes.sym != null){	
				annotationSymbols[c] = annoLayer.features[c].attributes.sym;
			}else{
				annotationSymbols[c] = "";
			}		
		}
	 }else{		
		annotationSymbols[0] = "none"; 
	 } 
	return annotationSymbols;
}



//**************************************Retrieves info on map extents drawn on the map and move through to the confirm page
function goConfirm(){
	
	//Retrieve the map extent
	if(extentLayer.features.length > 0){
		var proceedToConfirm = true;
	}else{
		var answer = confirm ('Please ensure that you select an area to be covered before proceeding. Do you want to choose the whole map?')
		if(answer){
			var proceedToConfirm = true;
			chooseFullMap();
		}else{
			var proceedToConfirm = false;
		}
	}
		
	if(proceedToConfirm){
		//Retrieve and store the map extent
		thegeometryasstring = extentLayer.features[0].geometry;
		document.frmMap.extentInfo.value = thegeometryasstring;
				
		//Retrieve any user annotations
		var annotations = getAnnoFeatures();
		
		//Retrieve any user annotation labels
		var annotationLabels = getAnnoFeatureLabels();
		
		//Retrieve symbols used for point annotation features
		var annotationSymbols = getAnnoFeatureSymbols();
			
		//Store as a string in hidden field
		var annotationsString = "";
		for(c=0; c < annotations.length; c++){
			if(c==0){
				annotationsString = annotations[c];
				annotationLabelsString = annotationLabels[c];
				annotationSymbolsString = annotationSymbols[c];
			}else{
				annotationsString += "|" + annotations[c];
				annotationLabelsString += "|" + annotationLabels[c];
				annotationSymbolsString += "|" + annotationSymbols[c];
			}
		}	

		document.frmMap.userAnno.value = annotationsString;
		document.frmMap.userAnnoLabels.value = annotationLabelsString;
		document.frmMap.userAnnoSymbols.value = annotationSymbolsString;
		
		//Store maps scale and type
		document.frmMap.baseScale.value = avaialableMapScales[avaialableMapsArrayIndex];
		document.frmMap.baseMapType.value = avaialableMapISBNs[avaialableMapsArrayIndex];	
		
		//Go to confirm page
		document.frmMap.action = "customizemap-confirm.php"
		document.frmMap.submit();			
	}	
		
}		


function getMaps(theOption){
	var mapType = theOption
	var selectedMap = document.frmMap.baseMapType.value;
	http = createRequestObject();
	http.open('get', 'serve-custom-maps.php?type=' + mapType + "&selectedmap=" + selectedMap);
	http.onreadystatechange = displayMaps;
	http.send(null);
}	

function displayMaps() {
		if(http.readyState == 4){
			var theMaps = http.responseText;
			document.getElementById("mapContent").innerHTML = theMaps
				
		}
	}

function selectCMap(theMap,theRad){
	
	if(theRad!=""){
		document.getElementById(theRad).checked = "checked";
	}
	
	var mapISBN = theMap
	document.getElementById("cStep2").style.display = 'block'
	document.getElementById("leftStep2").style.display = 'block'
	//Call the function to load the mapping in the main window
	defineMap(mapISBN,"","","","");
	document.getElementById("startImage").style.display = 'none';
}
function useTools(){
	document.getElementById("tellTool").style.display = 'block'	
}
function startDrawing(){
	document.getElementById("designOption").style.display = 'none'	
	activateTool('drawextent')
}
function useFullMap(){
	document.getElementById("designOption").style.display = 'none'
	chooseFullMap()	
}
//---------------End of file

