var map;
var centerLatitude = 20;
var centerLongitude = -156; 
var startZoom = 10;
var n_buttonText="Map"; //Text that shows up on the button for the custom layer (n=normal, s=sat)
var s_buttonText="Satellite";
var user_datas;
var large_projects;
var noise;
var organisations;
var minisites;
var gainsborough;
var noise;
var classes;
var madeinarchway;
var greenareas;
var reuserecycle;
var historical;


var historicalIcon;
var historicalClusterIcon;
var eventsIcon;
var eventsClusterIcon;
var organisationsIcon;
var organisationsClusterIcon
var user_datasIcon;
var user_datasClusterIcon;
var large_projectsImage;
var large_projectsClusterIcon;
var gainsboroughIcon;
var gainsboroughClusterIcon;
var classesIcon;
var classesClusterIcon; 
var reuserecycleIcon;
var reuserecycleClusterIcon; 
var greenareasIcon;
var greenareasClusterIcon; 
var madeinarchwayIcon;
var madeinarchwayClusterIcon; 
 


var historicalImage;
var historicalClusterImage;
var user_datasImage;
var user_datasClusterImage;
var organisationsImage;
var organisationsClusterImage;
var eventsImage;
var eventsImageClusterImage;
var gainsboroughImage;
var gainsboroughClusterImage;

var classesImage;
var classesClusterImage;


var reuserecycleImage;
var reuserecycleClusterImage;
var greenareasImage;
var greenareasClusterImage;
var madeinarchwayImage;
var madeinarchwayClusterImage;



var xmlUpdateMap;

function createXMLHttpRequest() {
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
   try { return new XMLHttpRequest(); } catch(e) {}
   alert("XMLHttpRequest not supported");
   return null;
 }

function preloadImages() {

	large_projectsImage = new Image();
	large_projectsImage.src = "../images/large_projects.png";
	
	large_projectsClusterImage = new Image();
	large_projectsClusterImage.src = "../images/large_projectsCluster.png";

	user_datasImage = new Image();
	user_datasImage.src = "../images/user_datas.png";

	user_datasClusterImage = new Image();
	user_datasClusterImage.src = "../images/user_datasCluster.png";

	organisationsImage = new Image();
	organisationsImage.src = "../images/organisations.png";
	organisationsClusterImage = new Image();
	organisationsClusterImage.src = "../images/organisationsCluster.png";

	eventsImage = new Image();
	eventsImage.src = "../images/events.png";
	eventsImageClusterImage = new Image();
	eventsImageClusterImage.src = "../images/eventsCluster.png";

	gainsboroughImage = new Image();
	gainsboroughImage.src = "../images/gainsborough.png";

	gainsboroughClusterImage = new Image();
	gainsboroughClusterImage.src = "../images/gainsborough.png";

	classesImage = new Image();
	classesImage.src = "../images/single.png";
	classesClusterImage = new Image();
	classesClusterImage.src = "../images/single.png";


	reuserecycleImage = new Image();
	reuserecycleImage.src = "../images/single.png";
	reuserecycleClusterImage = new Image();
	reuserecycleClusterImage.src = "../images/single.png";
	greenareasImage = new Image();
	greenareasImage.src = "../images/single.png";
	greenareasClusterImage = new Image();
	greenareasClusterImage.src = "../images/single.png";
	madeinarchwayImage = new Image();
	madeinarchwayImage.src = "../images/single.png";
	madeinarchwayClusterImage = new Image();
	madeinarchwayClusterImage.src = "../images/single.png";


	historicalImage = new Image();
	historicalImage.src = "../images/historical.png";
	historicalClusterImage = new Image();
	historicalClusterImage.src = "../images/single.png";



}

/* [listing 6-8] */
function changeBodyClass(from, to) {
     document.body.className = document.body.className.replace(from, to);
     return false;
}
/* [listing 6-8 end] */

 function getIconLocationPreload(datatype, clustered) {
         
         
         var iconlocation = "../images/single.png";
         
         
 	if (clustered == true) {
 		iconlocation = "../images/"+datatype;
 		iconlocation = iconlocation + "Cluster.png";
 	}
 	else  {
 		iconlocation = "../images/"+datatype;
 		iconlocation = iconlocation + ".png";
 	}
 	
 	return iconlocation;
}

 
 function createIcons () {

 	historicalIcon = cacheIcons("historical",false);
 	historicalClusterIcon = cacheIcons("historical",true);

 	
 	eventsIcon = cacheIcons("events",false);
 	eventsClusterIcon = cacheIcons("events",true);
 	organisationsIcon = cacheIcons("organisations",false);
 	organisationsClusterIcon = cacheIcons("organisations",true);
 	user_datasIcon = cacheIcons("user_datas",false);
 	user_datasClusterIcon = cacheIcons("user_datas",true);
	large_projectsIcon = cacheIcons("large_projects",false);
	large_projectsClusterIcon = cacheIcons("large_projects",true);
	gainsboroughIcon = cacheIcons("gainsborough",false);
	gainsboroughClusterIcon = cacheIcons("gainsborough",true);

	classesIcon = cacheIcons("classes",false);
	classesClusterIcon = cacheIcons("classes",true);

	reuserecycleIcon = cacheIcons("reuserecycle",false);
	reuserecycleClusterIcon = cacheIcons("reuserecycle",true);
	greenareasIcon = cacheIcons("greenareas",false);
	greenareasClusterIcon = cacheIcons("greenareas",true);
	madeinarchwayIcon = cacheIcons("madeinarchway",false);
	madeinarchwayClusterIcon = cacheIcons("madeinarchway",true);



 }
 
 function cacheIcons (layername, clustered) {
 	// create a number of icons and cache them to speed up display
 	
 	   var icon;
 	   var bicon = new GIcon();
 
	    bicon.iconSize = new GSize(20, 20);
	    bicon.iconAnchor = new GPoint(10, 10);

	    iconlocation = getIconLocationPreload(layername,clustered);
	    theIcon = new GIcon(bicon, iconlocation, null, null );
	    return theIcon;

  }
  function resizeDiv() {
  
  	  	var el = document.getElementById("map-canvas");
  	  	var currWidth = parseInt(getStyle(el,"width"));
  		var newWidth = parseInt(document.body.clientWidth) - 300;
  		setStyle("map-canvas", "width", newWidth + "px");
      	//document.getElementByID("map").style.width = (document.body.clientWidth - 300) + "px";
  
  }
 
 function init() {
 	resizeDiv();
	waitingHTML = "<div style=\"position: absolute;margin-left:100px;margin-top: 100px;width: auto;height: 19px;padding: 4px 10px 0px 10px;"
	waitingHTML += "color: #CC0000;background-color: rgb(221, 221, 238);border: 1px solid #979797;font-size: 14px;font-weight: 800;\">Loading map, please wait . . . this may take some time</div>";       


/*				<div style="position: absolute;
							top: 48%;
							left: 33%;
							width: auto;
							height: 19px;
							padding: 4px 10px 0px 10px; 
							color: #CC0000; 
							background-color: rgb(221, 221, 238); 
							border: 1px solid #979797; 
							font-size: 12px; 
							font-weight: 800;
							">Loading map, please wait . . .
				</div>*/


	document.getElementById('map-canvas').innerHTML = waitingHTML;

 	preloadImages();
 	createIcons();
	//loadMap();
        geocoder = new GClientGeocoder();
        geocoder.setBaseCountryCode("UK"); // gr is the iso code for great britain!
        
 	
        
//	var polyline = new GPolyline([new GLatLng(51.51, 0.08),new GLatLng(51.50, 0.07)], "#FF0000", 5);
//	map.addOverlay(polyline);
//	alert("added ");

//	drawPoint(51.51,0.08);
//	drawPoint(51.50,0.07);

	  
	      //map.enableScrollWheelZoom();
	      //map.enableDoubleClickZoom();
	      
	 //map.checkResize(); 
	 
	 // rather than do an update map event now, put an xmlhttp  request ... that way the page
	 // will load and the data will be calld separately ...
	 
	 xmlUpdateMap = createXMLHttpRequest();
	 xmlUpdateMap.open("POST", "mapDataAvailable.php", true);
	 xmlUpdateMap.onreadystatechange = mapDataAvailable;
	 
	 try {
	   //xmlUpdateMap.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   xmlUpdateMap.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
	 	// this only works in internet explorer
	 }
	 xmlUpdateMap.send(null);
	 

} 

function mapDataAvailable() {
   if (xmlUpdateMap.readyState != 4)  {
   		return;
   	}
   	
	var responseText = xmlUpdateMap.responseText;
	
	// the return for the xmlhttp request
	
	if (responseText == "Data Available") {
		loadMap();
		updateMap(false);
		// add the search tool
		
		
		GEvent.addListener(map,'moveend',function() {
			updateMap(true);
		}); 
	}
	else {
		if (confirm ("Temporarily unable to connect to map data.  Select YES to try again. NO will open the London21 website.")) {
				open("http://communitymaps.london21.org","replace");
		}
		else {
			open("http://www.london21.org","replace");
		}
	}
	

}
function loadMap() {

   

	var sPath = window.location.pathname;
   	      
   
   // depending on the page, either shown the mini-site boundaries or show the 
   	// minisite data 
        if (sPath.indexOf("Community") > 0)  {
          	// this is the main page
          	var pts = [new GLatLng(51.5157934336253,-0.09613037109375),new GLatLng(51.5157934336253,0.075531005859375),new GLatLng(51.4972021458538,0.075531005859375),new GLatLng(51.4972021458538,-0.09613037109375),new GLatLng(51.5157934336253,-0.09613037109375)]; 
   		var p = new GPolyline(pts, "#FF00FF",5,0.5,{});
          }
	if (sPath.indexOf("Royal") > 0 ){
		   // for Royal Docks
		document.getElementById('searchforplace').innerHTML = step3postcodehtml;
   		var pts = [new GLatLng(51.5157934336253,0.009613037109375),new GLatLng(51.5157934336253,0.075531005859375),new GLatLng(51.4972021458538,0.075531005859375),new GLatLng(51.4972021458538,0.009613037109375),new GLatLng(51.5157934336253,0.009613037109375)]; 
   		var p = new GPolyline(pts, "#FF00FF",5,0.5,{});
   	}
	if (sPath.indexOf("Hackney") > 0 ){
		   // for Hackney Wick
		document.getElementById('searchforplace').innerHTML = step3postcodehtml;
   		
   		var pts = [new GLatLng(51.529464940927,-0.0384521484375), new GLatLng(51.529464940927,0.00017166137695312), new GLatLng(51.555194687636,0.00017166137695312), new GLatLng(51.555194687636, -0.0384521484375), new GLatLng(51.529464940927, -0.0384521484375)];
   		//var pts = [new GLatLng(51.5157934336253,0.009613037109375),new GLatLng(51.5157934336253,0.075531005859375),new GLatLng(51.4972021458538,0.075531005859375),new GLatLng(51.4972021458538,0.009613037109375),new GLatLng(51.5157934336253,0.009613037109375)]; 
   		var p = new GPolyline(pts, "#FF00FF",5,0.5,{});
   	}
	if (sPath.indexOf("ThamesWard") > 0 ){
		document.getElementById('searchforplace').innerHTML = step3postcodehtml;
   		var pts = [new GLatLng(51.529300999999997, 0.087890000000000), new GLatLng( 51.532341000000002,0.104620000000000), new GLatLng(51.532927999999998,0.108830000000000), new GLatLng(51.532908999999997,0.110400000000000), new GLatLng(51.532893999999999,0.112309000000000 ), new GLatLng(51.532963000000002,0.112631000000000), new GLatLng(51.533203000000000,0.112803000000000), new GLatLng(51.534443000000003,0.113297000000000), new GLatLng(51.534458000000001,0.114219000000000 ), new GLatLng( 51.529300999999997,0.087890000000000)];
   		//var pts = [new GLatLng(51.529464940927,-0.0384521484375), new GLatLng(51.529464940927,0.00017166137695312), new GLatLng(51.555194687636,0.00017166137695312), new GLatLng(51.555194687636, -0.0384521484375), new GLatLng(51.529464940927, -0.0384521484375)];
   		//var pts = [new GLatLng(51.5157934336253,0.009613037109375),new GLatLng(51.5157934336253,0.075531005859375),new GLatLng(51.4972021458538,0.075531005859375),new GLatLng(51.4972021458538,0.009613037109375),new GLatLng(51.5157934336253,0.009613037109375)]; 
   		var p = new GPolyline(pts, "#FF00FF",5,0.5,{});
   	}
	if (sPath.indexOf("Archway") > 0 ){
		   // for Archway
		   
		document.getElementById('searchforplace').innerHTML = step3postcodehtml;
   		//var pts = [new GLatLng(51.529464940927,-0.0384521484375), new GLatLng(51.529464940927,0.00017166137695312), new GLatLng(51.555194687636,0.00017166137695312),  new GLatLng(51.555194687636, -0.0384521484375), new GLatLng(51.529464940927, -0.0384521484375)];
   		//var pts = [new GLatLng(51.557576176671,-0.1460285477518), new GLatLng(51.557193994,-0.1220008626495586), new GLatLng(51.573792232946,-0.12131671213190004), new GLatLng(51.574174641478, -0.1453531381518), new GLatLng(51.557576176671, -0.1460285477518)];
   		var pts = [new GLatLng(51.557576176671,-0.1460285477518), new GLatLng(51.557193994,-0.1220008626495586), new GLatLng(51.573792232946,-0.12131671213190004), new GLatLng(51.574174641478, -0.1453531381518), new GLatLng(51.557576176671, -0.1460285477518)];


   		//var pts = [new GLatLng(51.5157934336253,0.009613037109375),new GLatLng(51.5157934336253,0.075531005859375),new GLatLng(51.4972021458538,0.075531005859375),new GLatLng(51.4972021458538,0.009613037109375),new GLatLng(51.5157934336253,0.009613037109375)]; 
   		var p = new GPolyline(pts, "#FF00FF",5,0.5,{});
   	}
   
   
   var zoomLevel = getZoomLevelForPoints(pts);
   
    // TEMPORARY FIX FOR ARCHWAY ...
	if (sPath.indexOf("Archway") > 0 ){
		zoomLevel = zoomLevel + 1;
	}

   //document.getElementById("map-canvas").innerHTML = "";
      map = new GMap2(document.getElementById("map-canvas"));
   
   
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.addControl(new GOverviewMapControl());
   //map.enableContinuousZoom();
   
   
  if (sPath.indexOf("Community") > 0 ) {
	   map.setCenter(getCenterPointFromPolyline(p),zoomLevel,G_HYBRID_MAP);
}
else {
	   map.setCenter(getCenterPointFromPolyline(p),zoomLevel);
}
   
}


function getZoomLevelForPoints(pts) {

//zxv code
  var boundary_distance = pts[0].distanceFrom(pts[2]);
  var zoomLevel;
/*  if(boundary_distance > 24000) {
    zoomLevel = 10;
  }else if(boundary_distance > 12000) {
    zoomLevel = 11;
  }else if(boundary_distance > 6000) {
    zoomLevel = 12;
  }else if(boundary_distance > 2000) {
    zoomLevel = 13;
  }else if(boundary_distance > 1500) {
    zoomLevel = 14;
  }else {
    zoomLevel = 15;
  }*/
  
  if(boundary_distance > 24000) {
    zoomLevel = 11;
  }else if(boundary_distance > 12000) {
    zoomLevel = 12;
  }else if(boundary_distance > 6000) {
    zoomLevel = 13;
  }else if(boundary_distance > 2000) {
    zoomLevel = 14;
  }else if(boundary_distance > 1500) {
    zoomLevel = 15;
  }else {
    zoomLevel = 16;
  }

  return zoomLevel;
}

function getCenterPointFromPolyline(polyline) {
// zxv code
	return polyline.getBounds().getCenter();	
}


function updateMap(mapMoved) {
     var showevents = true;
     var showorgs = true;
     var showminisites = true;
     var showuser_datas = true;
     var showlarge_projects = true;
     var showgainsborough = true;
     var showclasses = true;
     var showgreenareas = true;
     var showhistorical = true;
     var showmadeinarchway = true;
     var showreuserecycle = true;
	
	//document.getElementById("maplegend").innerHTML = "";
	map.clearOverlays();

	if (mapMoved == true) {
		// check the existing layers and whether they are switched on or off
		try {
			if (document.getElementById("events").checked == false) {
				showevents = false;
			}		
		}
		catch (e) {
			showevents = true;
		}
		
		//if (document.getElementById("minisites").checked == false) {
		//	showminisites = false;
		//}	
		try {
			if (document.getElementById("organisations").checked == false) {
				showorgs = false;
			}		
		} 
		catch (e) {
				showorgs = true;
		}
		try {
			if (document.getElementById("user_datas").checked == false) {
				showuser_datas = false;
			}		
		} 
		catch (e) {
				showuser_datas = true;
		}
		try {
			if (document.getElementById("large_projects").checked == false) {
				showlarge_projects = false;
			}		
		} 
		catch (e) {
				showlarge_projects = true;
		}
		try {
			if (document.getElementById("gainsborough").checked == false) {
				showgainsborough = false;
			}		
		} 
		catch (e) {
				showgainsborough = true;
		}
		try {
			if (document.getElementById("classes").checked == false) {
				showclasses = false;
			}		
		} 
		catch (e) {
				showclasses = true;
		}
		try {
			if (document.getElementById("madeinarchway").checked == false) {
				showmadeinarchway = false;
			}		
		} 
		catch (e) {
				showmadeinarchway = true;
		}
		try {
			if (document.getElementById("greenareas").checked == false) {
				showgreenareas = false;
			}		
		} 
		catch (e) {
				showgreenareas = true;
		}
		try {
			if (document.getElementById("historical").checked == false) {
				showhistorical = false;
			}		
		} 
		catch (e) {
				showhistorical = true;
		}

		try {
			if (document.getElementById("reuserecycle").checked == false) {
				showreuserecycle = false;
			}		
		} 
		catch (e) {
				showreuserecycle = true;
		}
		



		
	}

	
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var getVars = 'ne=' + northEast.toUrlValue()
		+ '&sw=' + southWest.toUrlValue()

			       

	      var organisationstring =  "../includes/processDataRequest.php?approved=1&queryType=layer&tablename=organisations&" + getVars;
	      organisations = new GeoXml("organisations", "Organisations","map",false, showorgs, map, organisationstring, {sidebarid:"organisationsHTML"});

	      var eventsdatastring = "../includes/processDataRequest.php?approved=1&queryType=layer&tablename=events&" + getVars;
	      events = new GeoXml("events", "Events", "map", false, showevents, map,  eventsdatastring, {sidebarid:"eventsHTML"});

	      var userdatastring = "../includes/processDataRequest.php?approved=1&queryType=layer&tablename=user_datas&" + getVars;
	      user_datas = new GeoXml("user_datas", "Our Data","map", false, showuser_datas, map, userdatastring, {sidebarid:"user_datasHTML"});

	      var largeprojectstring = "../includes/processDataRequest.php?approved=1&queryType=layer&tablename=large_projects&" + getVars;
	      large_projects = new GeoXml("large_projects", "Large Projects","map", false, showlarge_projects, map, largeprojectstring, {sidebarid:"large_projectsHTML"});

	      var minisitesdatastring = "../includes/processDataRequest.php?approved=1&queryType=layer&tablename=minisites&" + getVars;
	      minisites = new GeoXml("minisites", "MiniSites", "map",false, showminisites, map,  minisitesdatastring, {sidebarid:"minisitesHTML"});
	
	      var gainsboroughdatastring = "../includes/gainsborough.kml";
	      gainsborough = new GeoXml("gainsborough", "Gainsborough<br>&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  Landmarks", "map",true,showgainsborough, map,  gainsboroughdatastring, {sidebarid:"gainsboroughHTML"});


	     var classesdatastring = "../includes/processDataRequest.php?approved=1&queryType=layer&tablename=classes&" + getVars;
	      classes = new GeoXml("classes", "Classes","map", false, showclasses, map, classesdatastring, {sidebarid:"classesHTML"});

	     var reuserecyclestring = "../includes/processDataRequest.php?approved=1&queryType=layer&tablename=reuserecycle&" + getVars;
	      reuserecycle = new GeoXml("reuserecycle", "Reuse/Recycle","map", false, showreuserecycle, map, reuserecyclestring, {sidebarid:"reuserecycleHTML"});
	     var madeinarchwaystring = "../includes/processDataRequest.php?approved=1&queryType=layer&tablename=madeinarchway&" + getVars;
	      madeinarchway = new GeoXml("madeinarchway", "Made in Archway","map", false, showmadeinarchway, map, madeinarchwaystring, {sidebarid:"madeinarchwayHTML"});
	     var greenareasstring = "../includes/processDataRequest.php?approved=1&queryType=layer&tablename=greenareas&" + getVars;
	      greenareas = new GeoXml("greenareas", "Green Areas","map", false, showgreenareas, map, greenareasstring, {sidebarid:"greenareasHTML"});

	     var historicalstring = "../includes/processDataRequest.php?approved=1&queryType=layer&tablename=historical&" + getVars;
	      historical = new GeoXml("historical", "Historical","map", false, showhistorical, map, historicalstring, {sidebarid:"historicalHTML"});



	var sPath = window.location.pathname;
	//var sPage = sPath.substring(sPath.lastIndexOf('\\') + 1);
	var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
	      
	// depending on the page, either shown the mini-site boundaries or show the 
	// minisite data 
       if (sPath.indexOf("Community") > 0)  {
		minisites.parse();
       }
       else { 
       		// for now assume that this is a mini-site
       		if ((sPath.indexOf("Hackney") > 0) || (sPath.indexOf("Docks") > 0))	{	      		
		     user_datas.parse();
		     large_projects.parse(); 
		     events.parse();
		     organisations.parse();
		}
		if (sPath.indexOf("Hackney") > 0 ) {
			gainsborough.parse();
			historical.parse();
		}
		if (sPath.indexOf("ThamesWard") > 0 ) {
		     user_datas.parse();
		     large_projects.parse(); 
		     events.parse();
		     organisations.parse();
		}

		if (sPath.indexOf("Archway") > 0 ) {
			events.parse();
			organisations.parse();
			classes.parse();
			greenareas.parse();
			madeinarchway.parse();
			reuserecycle.parse();
		}
		
	}

	
	// now redraw any points / lines or polygons if we are capturing data
	//if (startCapture == true) {
	//	drawCaptureData();
	//}
}

function checkEnter(event){
	if(event.keyCode==13)
	dosimplesearch();
}
function checkEnterGoto(event) {
	if(event.keyCode==13)
	processStep3Postcode();
}