//------------------------------------------------------------GLOBALS	
var map;								//Openelayers map layer
var theMapFile = "mapstudio.map";	//Path to the map file
var http;
var vlayer;								//Layer that contains the mapping
var rLayer;								//Layer that contains Radials
var baselayer;							//Layer that contains the mapping
var pointLayer = new OpenLayers.Layer.Markers( "Markers" );
var polygonExtentFeature;
var polygonRadialFeature = new Array();
var drawFeatureControl;
var modifyControl;
//var zoomScales = new Array(8850000,4425000,2212500,885000,442500,221250,88500,44250,22125,8850,4500);   
var zoomScales = new Array(11320000,5660000,2830000,1132000,566000,283000,113200,56600,28300,11320,5660);  
var initialExtent = new Array(1800000,-4000000,3800000,-2400000);
var fullExtent = new Array(0,-5000000,5000000,0);
var baseMapLayers = '20m 10m 5m 2m 1m 500k 200k 100k 50k 20k 10k';   
var zoomWidth = 16000
var popup, feature, marker;


//POI/Product point Globals
var currentViewWidth = 2241654.62284;
var currentViewHeight = 1561040.8237049999;
var poiThresholdSize =  15000;
var prodThresholdSize = 100000;
var poiLayerArray = new Array();
var poiCheckBoxes = new Array("chkAirport","chkATM","chkFilling","chkHospital","chkNature","chkPolice","chkShopping","chkSchools","chkTourist","chkProducts");

var poiBufferDistance = 5000; //Metres
var prodBufferDistance = 15000; //Metres
var poiCentreX = null;
var poiCentreY = null;
var prodCentreX = null;
var prodCentreY = null;

var poiScriptPath = "http://www.mapstudio.co.za/getpoi.php?";  //"http://77.246.162.227/getpoi.php?";  			//Location of script to retrieve the POIs
var prodScriptPath = "http://www.mapstudio.co.za/getproducts.php?";  //"http://77.246.162.227/getproducts.php?";  			//Location of script to retrieve the Product points
var selFeatureControl;
var poiLayer;
var productsLayer = null;

var feature = null;

OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '3';
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'] = 'red';
OpenLayers.Feature.Vector.style['select']['strokeColor'] = 'red';
OpenLayers.Feature.Vector.style['select']['fillOpacity'] = '0.3';
OpenLayers.Feature.Vector.style['select']['graphicOpacity'] = '1';

//------------------------------------------------------------MAP SETUP

//**************************************Initializes the map

var SHADOW_Z_INDEX = 10;
var MARKER_Z_INDEX = 11;


function initMap(passedCoordinates,passedRadials,passedCenter,userX,userY,passedExtent,theClassCode){
	//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 = "#CC0000";
	mapextenstyle.fillColor = "#666666";
	mapextenstyle.strokeWidth = 4;
	//If a map already set destroy it
	if(map != null){
		map.destroy();
	}
		
	//Define the map and relvant options
	map = new OpenLayers.Map( $('mapContainerWide'), { controls: [], 
	//map = new OpenLayers.Map( mapObj, { controls: [], 
		//projection: 'EPSG:2805',    //4326',
		units:'m',  
		maxExtent: new OpenLayers.Bounds(fullExtent[0],fullExtent[1],fullExtent[2],fullExtent[3]), 				
		scales: zoomScales});



	//Create base mapping layer				  
	baselayer = new OpenLayers.Layer.MapServer( "Base",
					//"http://www.planvu.co.uk/cgi-bin/mapserv",
					"http://77.246.162.227/cgi-bin/mapserv.exe",
					{ map: theMapFile,
					  layers: baseMapLayers}, { singleTile: true, isBaseLayer: true, transitionEffect: 'null'});				  
	
	
	
	//Create layer for markers to be drawn on
	map.addLayers([baselayer, pointLayer]);
	map.fractionalZoom = false;
	
	var bounds = new OpenLayers.Bounds(initialExtent[0],initialExtent[1],initialExtent[2],initialExtent[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.ScaleLine());
	//map.addControl(new OpenLayers.Control.LayerSwitcher());
	
	
	if((userX!="") && (userY!="")){
		//alert("info has been passed")
		userZoom(userX,userY);
	} 

	/*Re-Centre the map if the extent is moved
	vlayer.events.register('featureadded', vlayer, function(evt) { 
		if(vlayer.features.length > 0){
		//Zoom to shape
		var theGeometryasBounds = vlayer.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)
		}
	
	});
	
	vlayer.events.register('featuremodified', vlayer, function(evt) { 
	   if(vlayer.features.length > 0){
		 thegeometryasBounds = vlayer.features[0].geometry.getBounds();
		 var centreLatLon = thegeometryasBounds.getCenterLonLat();
		map.setCenter(centreLatLon,map.getZoom(),false,false);    
	   }
	  }); 
	vlayer.events.register('beforefeaturesadded', vlayer, function(evt) { 
		vlayer.removeFeatures(vlayer.features[0]);		
	}); */
	
	//Redraw any passed extent or radials
		if(passedCoordinates != ""){
			alert("Passed Coordinates doesn\'t equal nothing!")
			recreateExtent(passedCoordinates);		
			if(passedRadials != ""){
				addExtent(passedRadials, 'circle');
			}
		}
		
	//Redraw any passed extent or radials		
		if(passedCenter != ""){
			var centerArray = passedCenter.split("|")
			var cX = Number(centerArray[0])
			var cY = Number(centerArray[1])
			recreatePoint(cX,cY,zoomWidth)		
		}
			
	
	
	//Draw POI on map move
	map.events.register('moveend', map, function(evt) { 

		
		baselayer.transitionEffect = "null";
		
		
		//Check if we need to get new selection (No if zooming in)
		var theViewExtent = map.getExtent().toBBOX();
		var theViewExtentArray = theViewExtent.split(",");	
		var newViewWidth = (theViewExtentArray[2] - theViewExtentArray[0]);
		var newViewHeight = (theViewExtentArray[3] - theViewExtentArray[1]);	
		
		//Check if any of the POI have been initialised - they have not we may need to retrieve the locations on a zoom in
		var poiLayersDefined = false;	
		for(c=0; c < poiCheckBoxes.length; c++){	
			if(poiLayerArray[c] != null){				
				poiLayersDefined = true;
				break;
			}
		}	
			
		if(((newViewWidth < currentViewWidth) && (newViewHeight < currentViewHeight)) && (poiLayersDefined)){
			//Zooming in and poi are showing - no need to retrieve 
			//Ensure the POI check boxes are enabled and user message hides
			updatePOIList(false,true,"block","Check a box to view the POI on the map");				
		}else if ((newViewWidth > poiThresholdSize) && (newViewHeight > poiThresholdSize)){
			//Current view is bigger than the threshold (too many points to show - so don't)
			//Ensure the POI check boxes are disabled and user message shows
			updatePOIList(true,false,"block","Please zoom in to view points of interest");	
		}else{
			//Ensure the POI check boxes are enabled and user message hides
			updatePOIList(false,true,"block","Check a box to view the POI on the map");

			var getPoi = false;
			if((poiCentreX == null) || (poiCentreY == null)){
				getPoi = true;
			}else{
				if(Math.sqrt((poiCentreX - map.getCenter().lon) * (poiCentreX - map.getCenter().lon)) > poiBufferDistance){
					getPoi = true;
				}
				if(Math.sqrt((poiCentreY - map.getCenter().lat) * (poiCentreY - map.getCenter().lat)) > poiBufferDistance){
					getPoi = true;
				}
			}	
			if(getPoi){
				var theClassCodes = getPOIClassCodes();		//Get class codes from the check box states		
				if(theClassCodes != ""){
					var theClassCodesArray = theClassCodes.split("|");
					for(c=0; c < theClassCodesArray.length; c++){								//Loop through each POI class code and add to map if selected
						if(theClassCodesArray[c] != ""){			
							var qstring = "extent=" + theViewExtent + "&classcode=" + theClassCodesArray[c] + "&buffer=" + poiBufferDistance;		
							addPOI(qstring, c);
						}else{
							if(poiLayerArray[c] != null){					//Ensure the POI is removed before adding
								map.removeLayer(poiLayerArray[c]);
								poiLayerArray[c] = null;
							}
						}			
					}	
				}else{									//No layers showing - ensure  all POI layers is removed
					for(c=0; c < poiCheckBoxes.length; c++){				//Loop through each POI class code and add to map if selected
						if(poiLayerArray[c] != null){				
							map.removeLayer(poiLayerArray[c]);
							poiLayerArray[c] = null;
						}			
					}				
				}		
			
				//Store the center point that the POI were retrieved from
				poiCentreX = map.getCenter().lon;
				poiCentreY = map.getCenter().lat;
			}	
				
		}	
		
		//Add products point onto the map
		//if((newViewWidth < currentViewWidth) && (newViewHeight < currentViewHeight)){
			//Zooming in and poi are showing - no need to retrieve 
		//	alert("no need 1");
		//}else if ((newViewWidth > prodThresholdSize) && (newViewHeight > prodThresholdSize)){
		//	alert("no need 2");
			//Current view is bigger than the threshold (too many points to show - so don't)
		//if((((newViewWidth < currentViewWidth) && (newViewHeight < currentViewHeight)) || ((newViewWidth > poiThresholdSize) && (newViewHeight > poiThresholdSize))) && (poiLayersDefined)){
			//Zooming in - no need to retrieve or current view is bigger than the threshold (too many points to show - so don't)
		//}else{
			//alert("checking new products");
			var theCheckBox = document.getElementById("chkProducts");
			if(theCheckBox.checked){
				var getProds = false;
				if((prodCentreX == null) || (prodCentreY == null)){
					getProds = true;
				}else{
					if(Math.sqrt((prodCentreX - map.getCenter().lon) * (prodCentreX - map.getCenter().lon)) > prodBufferDistance){
						getProds = true;
					}
					if(Math.sqrt((prodCentreY - map.getCenter().lat) * (prodCentreY - map.getCenter().lat)) > prodBufferDistance){
						getProds = true;
					}
				}	
				if(getProds){
					//alert("getting new products");
					addProductMarkers();
				}
			}	
		//}
		
		currentViewWidth = newViewWidth;
		currentViewHeight = newViewHeight;
		
		crossSell();
	});
			
	if(theClassCode != ""){													//Zoom to passed location and show the passed POI 
		showPOIbyCat(theClassCode,passedExtent);
	}else{																	//Zoom to passed location
		if(passedExtent != ""){
			var passedExtentArray = passedExtent.split(",");
			var bounds = new OpenLayers.Bounds(passedExtentArray[0],passedExtentArray[1],passedExtentArray[2],passedExtentArray[3]);
			map.zoomToExtent(bounds);
		}
		
	}
		
	//Add products point onto the map on load
	//addProductMarkers();
	

	//Register events to change transistion effect when zooming and panning
	map.events.registerPriority("click", map, function(e) {
	baselayer.transitionEffect = "null";
	})	
	map.events.registerPriority("mousedown", map, function() {
	baselayer.transitionEffect = "resize";
	})



}


//Function to zoom to the point if a user has included X&Y in URL
function userZoom(theX,theY){

	var shopZoomLevel = 100000
	var theX = theX
	var theY = theY

	var blx = theX - (shopZoomLevel/2);
	var bly = theY - (shopZoomLevel/2);
	var urx = theX + (shopZoomLevel/2);
	var ury = theY + (shopZoomLevel/2);
    
	var zoomCenter = new OpenLayers.LonLat(theX,theY)
	var bounds = new OpenLayers.Bounds(blx,bly,urx,ury);
	map.zoomToExtent(bounds);
	map.setCenter(zoomCenter,map.getZoom(),false,false);

	addMarker(theX,theY)

 }


//--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){
   vlayer.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,mapextenstyle);
 
  vlayer.addFeatures(polygonExtentFeature);
  
  //Zoom to shape
		  var theGeometryasBounds = vlayer.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);
 }
 else if(theType=='circle'){
	 
	 //Remove any existing
	 for (i=0;i<polygonRadialFeature.length;i++){
	  if(polygonRadialFeature[i] != null){
	   rlayer.removeFeatures(polygonRadialFeature[i])
	  }
	 }
		
	 if (theSize != 'user'){
		var radialArray = new Array()
		theWidth = vlayer.features[0].geometry.getBounds().getWidth();
		theHeight = vlayer.features[0].geometry.getBounds().getHeight();
		
		
		if (theWidth > theHeight){
			var maxSize = theWidth/2
		}else{
			var maxSize = theHeight/2
		}
		//alert(maxSize)
		var currentSize = Number(theSize)
		
		for(i=0;i<50;i++)	{
			if(currentSize > maxSize){
				break
			}
			radialArray[i] = currentSize
			currentSize += Number(theSize)
		}
	 }else{
		if(document.getElementById('txtRadial').value == ''){
		alert('Please enter a value')
		}else{
	 	var radialArray = document.getElementById('txtRadial').value.split(" ")
			for (i=0; i < radialArray.length; i++){
			radialArray[i] = radialArray[i]*1000
			}
		}
	}
	 
	 for (i=0; i < radialArray.length; i++){
    //alert(radialFeatures[i2])
    var pointList = [];
    for (n=0;n<72;n++){
     strXtemp = (Math.round(((Math.cos((n*5)*(Math.PI/180)))*Number(radialArray[i]))))  + centreX;
     strYtemp = (Math.round(((Math.sin((n*5)*(Math.PI/180)))*Number(radialArray[i]))))  + centreY;
     var newPoint = new OpenLayers.Geometry.Point(strXtemp,strYtemp);
     pointList.push(newPoint);
     
    }
    pointList.push(pointList[0]);   
    var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
    radialArray[i] = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null,radialStyle);
	polygonRadialFeature = radialArray
    rlayer.addFeatures(radialArray[i]);
 
   }

 }
}


function recreateExtent(passedCoordinates){	
		vlayer.destroyFeatures()
		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);
		}				
		//pointList.push(pointList[0]);	
		var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
		polygonExtentFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null,mapextenstyle);
		vlayer.addFeatures(polygonExtentFeature);
		
		//Zoom to shape
		var theGeometryasBounds = vlayer.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)
	
	}


// Activate the drawing tools
 function activateTool(toolType)	{
	 drawFeatureControl.deactivate()
	 modifyControl.deactivate()
	 //moveFeatureControl.activate()
	 //panFeatureControl.activate()
	 //resizeFeatureControl.activate()
	 
	 if (toolType=='draw'){
			if(polygonExtentFeature != null){
			vlayer.destroyFeatures()
			}
			drawFeatureControl.handler.irregular = true;
			drawFeatureControl.activate()
			document.getElementById("drawTool").src = "images/btnDrawON.png"
			document.getElementById("moveTool").src = "images/btnModify.png"
			document.getElementById("panTool").src = "images/btnPan.png"
	}else if (toolType=='move'){
			modifyControl.mode = OpenLayers.Control.ModifyFeature.DRAG;
			modifyControl.mode |= OpenLayers.Control.ModifyFeature.RESIZE;
			modifyControl.activate()
			document.getElementById("drawTool").src = "images/btnDraw.png"
			document.getElementById("moveTool").src = "images/btnModifyON.png"
			document.getElementById("panTool").src = "images/btnPan.png"
	 }else if (toolType=='pan'){
			document.getElementById("drawTool").src = "images/btnDraw.png"
			document.getElementById("moveTool").src = "images/btnModify.png"
			document.getElementById("panTool").src = "images/btnPanON.png"
	 }
	 
 }
 
 function destroyMap(){
	vlayer.destroyFeatures()
	rlayer.destroyFeatures()
	map.zoomToMaxExtent();
}

function destroyExtent(){
	vlayer.destroyFeatures()
	rlayer.destroyFeatures()
}


function createRequestObject() {
var ro;		
	if (window.XMLHttpRequest) { 	
		ro = new XMLHttpRequest();
	}else if (window.ActiveXObject) {
		try {
			ro = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			ro = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	return ro;
}
	

function zoomToSearchPoint(theType){
	document.getElementById("sfDistanceCalc").style.display = 'block'
	var theCoords = document.getElementById("theCoords").value;
	var coordArray = theCoords.split(",");
	
	var theX = Number(coordArray[0]);
	var theY = Number(coordArray[1]);
	if(theType == "street"){		//Street search
		var searchZoomWidth = 1000;
	}else if(theType == "Suburb"){
		var searchZoomWidth = 5000;	
	}else{													//Town search
		var searchZoomWidth = 16000;
	}
	
	var blx = theX - (searchZoomWidth/2);
	var bly = theY - (searchZoomWidth/2);
	var urx = theX + (searchZoomWidth/2);
	var ury = theY + (searchZoomWidth/2);
	
	var bounds = new OpenLayers.Bounds(blx,bly,urx,ury);
	map.zoomToExtent(bounds);

	document.getElementById("distanceStart").innerHTML = theLoc;
	
	
	addMarker(theX,theY)
	crossSell();

	
	
}




function zoomToPoint(){
	document.getElementById("sfDistanceCalc").style.display = 'block'
	var theCoords = document.getElementById("theCoords").value
	//alert(theCoords)
	var coordArray = theCoords.split(",")
	
	var theX = Number(coordArray[0])
	var theY = Number(coordArray[1])
	
	
	var blx = theX - (zoomWidth/2);
	var bly = theY - (zoomWidth/2);
	var urx = theX + (zoomWidth/2);
	var ury = theY + (zoomWidth/2);
	
	var bounds = new OpenLayers.Bounds(blx,bly,urx,ury);
	map.zoomToExtent(bounds);

	document.getElementById("distanceStart").innerHTML = theLoc;
	
	
	addMarker(theX,theY)
	crossSell();

	
	
}


function crossSell(){
	var theViewExtent = map.getExtent().toBBOX();
	
	http = createRequestObject();
	http.open('get', 'crossSell.php?type=map&ext='+theViewExtent); 
	http.onreadystatechange = handleSellResponse;
	http.send(null);
	document.getElementById("crossSellMap").style.display = 'block';
	document.getElementById("crossSellMapMiddleContent").innerHTML = '<img src="images/loader.gif" alt="Loading up some products" /> Searching for products in this area...';
	
	crossSellLeft();

}

function crossSellLeft(){	
	document.getElementById("crossSell").style.display = 'block';
	document.getElementById("crossSell").innerHTML = '<img src="images/loader.gif" alt="Loading up some products" /> Searching for products in this area...';
	
	var theViewExtent = map.getExtent().toBBOX();
	
	lhttp = createRequestObject();
	lhttp.open('get', 'crossSellLeft.php?ext='+theViewExtent); 
	lhttp.onreadystatechange = handleLeftResponse;
	lhttp.send(null);	
}

function handleLeftResponse() {

	if(lhttp.readyState == 4){
		var thelResponse = lhttp.responseText;
		document.getElementById("crossSell").innerHTML = thelResponse;
	}

}

function handleSellResponse() {
	if(http.readyState == 4){
		var theResponse = http.responseText;
		document.getElementById("crossSellMapMiddleContent").innerHTML = theResponse;
	}
}

//------------------------------------------------------TOWN LOCATOR MARKER
function addMarker(theMarkerX,theMarkerY) {
	var size = new OpenLayers.Size(22,36);
	var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
	var theIcon = new OpenLayers.Icon('http://77.246.162.227/images/mapmarker.png',size,offset);
	
	feature = new OpenLayers.Feature(pointLayer, new OpenLayers.LonLat(theMarkerX,theMarkerY), {icon: theIcon});
	marker = feature.createMarker();
	pointLayer.addMarker(marker);
	
	marker.events.register("click", marker, showPopup); 
}

function showPopup(evt) {
	if (popup == null){
		
		var theForm = "<form id=\"frmDistance\" method=\"post\" action=\"\">";
		var txtDistance = "<input type=\"text\" name=\"txtDistance\" id=\"txtDistance\" onkeyup=\"getEndPoint()\"  value=\"\" style=\"margin-bottom:5px;margin-top:5px;\">";
		var endPointLayer = "<div id=\"endPointList\"></div>";
		var popupHTML = "<div style='height:162px;padding:15px;background-image:url(images/distanceBackground.png);'> \
						"+theForm+" \
						<img src=\"images/distancecalculator.png\" alt=\"distance calculator\" /><br /> \
						<span style=\"font-size:11px;\">Calculate the distance from here to...</span><br /> \
						"+txtDistance+" \
						"+endPointLayer+" \
						</form> \
						</div>";
		
		
		popup = feature.createPopup(true);
		popup.setContentHTML(popupHTML);
		popup.setBackgroundColor("transparent");
		popup.setBorder("2px solid black");
		//popup.autoSize=true;  
		popup.setOpacity(1);
		pointLayer.map.addPopup(popup);
	}else{
		popup.toggle();
	}
	OpenLayers.Event.stop(evt);
} 



//------------------------------------------------------POI STUFF
//**************************Show the POI by category
function showPOIbyCat(theClassCode,theMapExtent){

	var zoomExtent = theMapExtent.split(",");
	var bounds = new OpenLayers.Bounds(zoomExtent[0],zoomExtent[1],zoomExtent[2],zoomExtent[3]);
	map.zoomToExtent(bounds);

	//Add the poi for the passed class codes
	var qstring = "extent=" + theMapExtent + "&classcode=" + theClassCode;
	var poiScript = poiScriptPath + qstring;
	
	//var poiScript = "http://www.mapsinternational.co.uk/mapstudio/getallpoi.php?" + qstring;
	poiLayer = new OpenLayers.Layer.GML(theClassCode, poiScript, { format: OpenLayers.Format.Text});
	map.addLayer(poiLayer);
	
	
	//Define the visible POI layers
	var visibleLayers = new Array();
	var visLayCnt = -1;
	for(c=0; c < poiCheckBoxes.length; c++){
		if(poiLayerArray[c] != null){
			visLayCnt += 1;				
			visibleLayers[visLayCnt] = poiLayerArray[c];
		}			
	}


	//----NEW	
	if(productsLayer != null){
		visLayCnt += 1;				
		visibleLayers[visLayCnt] = productsLayer;	
	}
	//----
	visLayCnt += 1;
	
	//alert(visLayCnt)
					
	visibleLayers[visLayCnt] = poiLayer;
	selFeatureControl = new OpenLayers.Control.SelectFeature(visibleLayers); 
 	map.addControl(selFeatureControl);
	selFeatureControl.activate();
			
	poiLayer.events.on({
   'featureselected': onFeatureSelect,
    'featureunselected': onFeatureUnselect
	});
		
	
}

//**************************Get list of class codes from the check box states
function getPOIClassCodes(){
	var theClassCodes = "";
	var classCodeCount = 0;
	for(c=0; c < poiCheckBoxes.length; c++){
		if(poiCheckBoxes[c] != "chkProducts"){
			var theCheckBox = document.getElementById(poiCheckBoxes[c]);
			if(theCheckBox.checked){											//Add value to list		
				classCodeCount += 1;
				if(classCodeCount == 1){
					theClassCodes = theCheckBox.value;
				}else{
					theClassCodes += "|" + theCheckBox.value;
				}
			}else{																//Add nothing to list (ie not checked)
				classCodeCount += 1;
				if(classCodeCount == 1){
					theClassCodes = "";
				}else{
					theClassCodes += "|" + "";
				}
			}
		}
	}
	return theClassCodes;						//Return list of the selected layers
}

//**************************Retrieve POI from database and add to layer
function addPOI(qstring,poiLayerIndex){
	//Ensure the POI layers is removed before adding
	if(poiLayerArray[poiLayerIndex] != null){
		poiLayerArray[poiLayerIndex].destroy();
		poiLayerArray[poiLayerIndex] = null;
		//Remove any popups showing
		if(feature != null){
			if (feature.popup) {
				popup.feature = null;
				map.removePopup(feature.popup);
				feature.popup.destroy();
				feature.popup = null;
			}
		}
	}
	//Add the POI
	var poiScript = poiScriptPath + qstring;	
	poiLayerArray[poiLayerIndex] = new OpenLayers.Layer.GML("POI_" + String(poiLayerIndex), poiScript, { format: OpenLayers.Format.Text});
	map.addLayer(poiLayerArray[poiLayerIndex]);

	//Define the visible POI layers
	var visibleLayers = new Array();
	var visLayCnt = -1;
	for(c=0; c < poiCheckBoxes.length; c++){
		if(poiLayerArray[c] != null){
			visLayCnt += 1;				
			visibleLayers[visLayCnt] = poiLayerArray[c];
		}			
	}

	//----NEW
	if(productsLayer != null){
		visLayCnt += 1;				
		visibleLayers[visLayCnt] = productsLayer;
	}
	//-----
	
	if(poiLayer != null){
		visLayCnt += 1;				
		visibleLayers[visLayCnt] = poiLayer;
	}	
		
	//Add a selecte feature control for the visible POI layers
	selFeatureControl = new OpenLayers.Control.SelectFeature(visibleLayers); 
 	map.addControl(selFeatureControl);
	selFeatureControl.activate();
	//Define selection events on the POI layer	
	poiLayerArray[poiLayerIndex].events.on({
   'featureselected': onFeatureSelect,
    'featureunselected': onFeatureUnselect
	});	
}
//**************************Update POI - called when checkbox turned on-off
function updatePOI(theCheckBox,poiLayerIndex){
	if(theCheckBox.checked){		//Turn this layer on
	
		//Check how many POI layers are selected
		var testclassCodeCount = -1;
		for(c=0; c < poiCheckBoxes.length; c++){				
			var theTestCheckBox = document.getElementById(poiCheckBoxes[c]);
			if(theTestCheckBox.checked){											//Add value to list
				testclassCodeCount += 1;			
			}
		}
	
		if(testclassCodeCount == 3){
			alert("We are only able to display 3 labels at one time");
			theCheckBox.checked = false;
		}else{
			if(poiLayerArray[poiLayerIndex] != null){				//Layer exists - therefore just make visible
				poiLayerArray[poiLayerIndex].setVisibility(true);
			}else{													//Layer does not exists - therefore retrieve data for it
				var theViewExtent = map.getExtent().toBBOX();
				var theViewExtentArray = theViewExtent.split(",");	
				var newViewWidth = (theViewExtentArray[2] - theViewExtentArray[0]);
				var newViewHeight = (theViewExtentArray[3] - theViewExtentArray[1]);	
				if((newViewWidth > poiThresholdSize) && (newViewHeight > poiThresholdSize)){
					//Current view is bigger than the threshold (too many points to show - so don't)
				}else{
					var qstring = "extent=" + theViewExtent + "&classcode=" + theCheckBox.value + "&buffer=" + poiBufferDistance;
					addPOI(qstring,poiLayerIndex);
					//Store the center point that the POI were retrieved from
					poiCentreX = map.getCenter().lon;
					poiCentreY = map.getCenter().lat;
				}
			}
		}
	}else{
		if(poiLayerArray[poiLayerIndex] != null){				//Layer exists - therefore just make invisible
			poiLayerArray[poiLayerIndex].setVisibility(false);
		}
	}		
}
//**************************Unselect feature on popup close
function onPopupClose(evt) {
	selFeatureControl.unselect(this.feature);
}
//**************************Show popup on feature select
function onFeatureSelect(evt) {
    feature = evt.feature; 
    popup = new OpenLayers.Popup.FramedCloud("featurePopup",
                             feature.geometry.getBounds().getCenterLonLat(),
                             new OpenLayers.Size(100,100),
                             "<h2>"+feature.attributes.title + "</h2>" +
                             feature.attributes.description,
                             null, true, onPopupClose);
    popup.autosize = true;
	popup.panMapIfOutOfView = false;
	feature.popup = popup;		
    popup.feature = feature;
    map.addPopup(popup);		
}
//**************************Destroy popup on feature unselect
function onFeatureUnselect(evt) {
    feature = evt.feature;
    if (feature.popup) {
        popup.feature = null;
        map.removePopup(feature.popup);
        feature.popup.destroy();
        feature.popup = null;
    }
}

function hideCross(){
	document.getElementById("crossSellMapContainer").style.display = 'none';
	document.getElementById("crossSellMapOpen").style.display = 'block';
}
function hideCompletely(){
	document.getElementById("crossSellMapOpen").style.display = 'none';
}
function showCrossSell(){
	document.getElementById("crossSellMapOpen").style.display = 'none';
	document.getElementById("crossSellMapContainer").style.display = 'block';
}

//**************************Ensure the POI check boxes are enabled/disabled and user message shows/hides on zooming in and out
function updatePOIList(checkDisabled,layerVis,messageState,theMessage){
	for(c=0; c < poiCheckBoxes.length; c++){
		if(poiCheckBoxes[c] != "chkProducts"){					//Never disable/enable the products check box automatically
			var theCheckBox = document.getElementById(poiCheckBoxes[c]);
			if(theCheckBox != null){				
				theCheckBox.disabled = checkDisabled;
				if(theCheckBox.checked){						//If poi layer is turned one ensure the map layer shows/hides
					if(poiLayerArray[c] != null){
						poiLayerArray[c].setVisibility(layerVis);
					}						
				}
			}
			
			//Toogle the colour of the check box labels
			var theLabelName = poiCheckBoxes[c].replace("chk","lbl");
			if(checkDisabled){				//Make light grey
				document.getElementById(theLabelName).style.color = "#cccccc";
			}else{							//Make dark grey
				document.getElementById(theLabelName).style.color = "#333333";		
			}
			
		}
	}
	document.getElementById("poimessage").style.display = messageState;
	//document.getElementById("poiMsg").innerHTML = theMessage;

}

//------------------------------------------------------PRODUCT MARKER STUFF
//**************************Adds town markers where there is a town
function addProductMarkers(){
	
	//Define the current view extent	
	var theViewExtent = map.getExtent().toBBOX();
	var theViewExtentArray = theViewExtent.split(",");	
	var newViewWidth = (theViewExtentArray[2] - theViewExtentArray[0]);
	var newViewHeight = (theViewExtentArray[3] - theViewExtentArray[1]);	
		
	var qstring = "extent=" + theViewExtent + "&buffer=" + prodBufferDistance; 		

	if(productsLayer != null){					//Ensure the Products layer is removed before adding	
		productsLayer.destroy();
		productsLayer = null;	
		//Remove any popups showing
		if(feature != null){
			if (feature.popup) {
				popup.feature = null;
				map.removePopup(feature.popup);
				feature.popup.destroy();
				feature.popup = null;
			}
		}
	}
	
	var prodScript = prodScriptPath + qstring;
	
	productsLayer = new OpenLayers.Layer.GML("Products", prodScript, { format: OpenLayers.Format.Text});
	map.addLayer(productsLayer);

	//Check what POI layers are visible and esure they are selectable
	var visibleLayers = new Array();
	var visLayCnt = -1;
	for(c=0; c < poiCheckBoxes.length; c++){				//Loop through each POI class code and add to map if selected
		if(poiLayerArray[c] != null){
			visLayCnt += 1;				
			visibleLayers[visLayCnt] = poiLayerArray[c];
		}			
	}
	visLayCnt += 1;				
	visibleLayers[visLayCnt] = productsLayer;	
	if(poiLayer != null){
		visLayCnt += 1;				
		visibleLayers[visLayCnt] = poiLayer;
	}
	selFeatureControl = new OpenLayers.Control.SelectFeature(visibleLayers); 
	
 	map.addControl(selFeatureControl);
	selFeatureControl.activate();
		
	productsLayer.events.on({
   'featureselected': onFeatureSelect,
    'featureunselected': onFeatureUnselect
	});
	
	//Store the center point that the POI were retrieved from
	prodCentreX = map.getCenter().lon;
	prodCentreY = map.getCenter().lat;
	
		
}
//**************************Updates the visibility of markers when check box clicked
function updateProducts(theCheckBox){
	if(theCheckBox.checked){		//Turn this layer on
		if(productsLayer != null){				//Layer exists - therefore just make visible
			productsLayer.setVisibility(true);
		}else{													//Layer does not exists - therefore retrieve data for it
			var theViewExtent = map.getExtent().toBBOX();
			var theViewExtentArray = theViewExtent.split(",");	
			var newViewWidth = (theViewExtentArray[2] - theViewExtentArray[0]);
			var newViewHeight = (theViewExtentArray[3] - theViewExtentArray[1]);	
			if((newViewWidth > prodThresholdSize) && (newViewHeight > prodThresholdSize)){
				addProductMarkers();
			}else{				
				addProductMarkers();
			}
		}
	}else{
		if(productsLayer != null){				//Layer exists - therefore just make invisible
			productsLayer.setVisibility(false);			
		}
	}
}


//**************************Submit feedback
function showFeedBackWin(){

	//Get the mapping and the map extent
	var theMapExtent = map.getExtent().toBBOX();
	var theScale = map.getScale();

	//Define the base mapping
	if(theScale < 8000){ 
		var theMapBase = "10k";
	}else if((theScale >= 8000) && (theScale < 20000)){ 
		var theMapBase = "20k";
	}else if((theScale >= 20000) && (theScale < 40000)){ 
		var theMapBase = "50k";
	}else if((theScale >= 40000) && (theScale < 80000)){ 
		var theMapBase = "100k";
	}else if((theScale >= 80000) && (theScale < 200000)){ 
		var theMapBase = "200k";
	}else if((theScale >= 200000) && (theScale < 400000)){ 
		var theMapBase = "500k";
	}else if((theScale >= 400000) && (theScale < 800000)){ 
		var theMapBase = "1m";
	}else if((theScale >= 800000) && (theScale < 2000000)){ 
		var theMapBase = "2m";
	}else if((theScale >= 2000000) && (theScale < 4000000)){ 
		var theMapBase = "5m";
	}else if((theScale >= 4000000) && (theScale < 8000000)){ 
		var theMapBase = "10m";
	}else if(theScale >=8000000){
		var theMapBase = "20m";	
	}

	//Open in new window;
	theURL = "mapfeedback.php?extent=" + theMapExtent + "&base=" + theMapBase;	
	winName = "MapFeedback";
	features = "toolbar=no,scrollbars=yes,resizable=yes,width=430,height=310";
	var theWin = window.open(theURL,winName,features);		
	theWin.focus();									//Ensure map window is visible on top


}

//**************************Pass the current view through to custommaps page
function buyArea(){
	//Get the current view extent
	theExtent = map.getExtent().toBBOX();
	var theExtentArray = theExtent.split(","); 
	//Build as polygon
	var coordinateExtentString = "POLYGON((" + theExtentArray[0] + " " + theExtentArray[1] + "," + theExtentArray[0] + " " + theExtentArray[3] + "," + theExtentArray[2] + " " + theExtentArray[3] + "," + theExtentArray[2] + " " + theExtentArray[1] + "," + theExtentArray[0] + " " + theExtentArray[1] + "))";
	//Get the map scale
	//theScale = map.getScale();

	//Open custom maps confirm page
	document.frmBuyCustom.extentInfo.value = coordinateExtentString 
	document.frmBuyCustom.submit();


	//alert(coordinateExtentString+ "Scale: " +theScale)


}

/*---------------------End of File------------*/