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 minisites;
var xmlUpdateMap;
var xmlGetInfo;
var infodisplayed;
var infopolyline; // this is the line between the info box and the item in question ..
var theAdminPolygon;
var theAdminLine;
var theAdminPoint;
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 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 initOverviewMap() {
  	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>";       
 
 	document.getElementById('map-canvas').innerHTML = waitingHTML;
 
	// this is the main page so we have a fixed zoom
	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,{});
	var zoomLevel = getZoomLevelForPoints(pts);
	   
	map = new GMap2(document.getElementById("map-canvas"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GOverviewMapControl());
	   
 	map.setCenter(getCenterPointFromPolyline(p),zoomLevel,G_HYBRID_MAP);

 	geocoder = new GClientGeocoder();
	geocoder.setBaseCountryCode("UK"); // gr is the iso code for great britain!

	 xmlUpdateMap = createXMLHttpRequest();
	 xmlUpdateMap.open("POST", "minisiteMapDataAvailable.php");
	 xmlUpdateMap.onreadystatechange = processOverviewMap;
	 
	 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 processOverviewMap() {
           if (xmlUpdateMap.readyState != 4)  {
	   		return;
	   	}
	
	var responseText = xmlUpdateMap.responseText;
	
	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.text = responseText;
	headID.appendChild(newScript);
	updateOverviewMap();
	GEvent.addListener(map,'moveend',function() {
		updateOverviewMap();
		if (infodisplayed == true) {
			moveInfoLine();
		}

	}); 
}
function updateOverviewMap() {
        // generate the icon and layer colours for minisites
        // this is separate from the usual site

	// now add the data layer
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var getVars = 'ne=' + northEast.toUrlValue()
	+ '&sw=' + southWest.toUrlValue()

	var showminisites = true;
	var minisitesdatastring = "../includes/processDataRequest.php?approved=1&queryType=layer&tablename=minisites&" + getVars;
	minisites = new GeoXml("minisites", "MiniSites", "map",false, showminisites, map,  minisitesdatastring, {sidebarid:"minisitesHTML"});
	minisites.parse();
}
 
 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>";       

	document.getElementById('map-canvas').innerHTML = waitingHTML;

	//loadMap();
        geocoder = new GClientGeocoder();
        geocoder.setBaseCountryCode("UK"); // gr is the iso code for great britain!
        
	 // 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?minisitename="+minisitename, 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 toggleLayer(layername)  {
	
	var layerdiv = document.getElementById(layername+"HTML");
	var d = layerdiv.getElementsByTagName('div');
	var ischecked = true;
	// has the user checked or unchecked the box?
	if (document.getElementById(layername+"toggle").checked) {
		// toggle all the sub values to cheecked
		ischecked = true;
	}
	else  {
		// uncheck all the sub values
		ischecked = false;
	}
	
	for (i=0;i< d.length; i++) {
		el = d[i];
		subelements = el.getElementsByTagName('input');
		//alert(el.id);
		for (j=0;j<subelements.length;j++) {
			//alert(subelements[j].id);
			//alert(subelements[j].checked);
			if (subelements[j].checked != ischecked) {
				subelements[j].click();
			}
		}
			// check or uncheck the sub div checkboxes
			
	}
}
function changeLayerTree(layername) {
	
	var layerdiv = document.getElementById(layername+"HTML");
	var d = layerdiv.getElementsByTagName('div');
	
	// find out whether the sub layers are visible or not at the minute ...
	// and change their visibility
	for (i=0;i< d.length; i++) {
		el = d[i];
		//alert(el.id);
		if (el.style.display == "" || el.style.display == "block") {
			el.style.display = "none";
		}
		else  {
			el.style.display = "block";
		}
		
	}


}
function mapDataAvailable() {
   if (xmlUpdateMap.readyState != 4)  {
   		return;
   	}
	// the return for the xmlhttp request
   	
	var responseText = xmlUpdateMap.responseText;
	
	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.text = responseText;
	headID.appendChild(newScript);

	
 	preloadImages();
 	createIcons();
	
	loadMap();
	updateMap(false);
	// add the search tool

	GEvent.addListener(map,'moveend',function() {
		updateMap(true);
		
		if (infodisplayed == true) {
			moveInfoLine();
		}

	}); 
}
function finishMap(pts,p) {
   //var zoomLevel = getZoomLevelForPoints(pts);
      map = new GMap2(document.getElementById("map-canvas"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.addControl(new GOverviewMapControl());
     /* for (i=0;i<pts.length;i++) {
      	alert(pts[i].lat());
      	alert(pts[i].lng());
      }*/
      var p = new GPolygon(pts, "#FF00FF",5,0.5,{});
     // map.setCenter(getCenterPointFromPolyline(p),zoomLevel);
   var zoomLevel = getZoomLevelForPolygon(p);  
      map.setCenter(getCenterPointFromPolygon(p),zoomLevel);
}
function getZoomLevelForPolygon(p) {
  var zoomlevel = map.getBoundsZoomLevel(p.getBounds());
  return zoomlevel;

}

function getZoomLevelForPoints(pts) {

  var boundary_distance = pts[0].distanceFrom(pts[2]);
  var zoomLevel;
  
  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) {
	return polyline.getBounds().getCenter();	
}

function getCenterPointFromPolygon(polygon) {
	return polygon.getBounds().getCenter();	
}


function checkEnter(event){
	if(event.keyCode==13)
	dosimplesearch();
}
function checkEnterGoto(event) {
	if(event.keyCode==13)
	processStep3Postcode();
}
function getInfo(layername, resultID) {
	 xmlGetInfo = createXMLHttpRequest();
	 xmlGetInfo.open("GET", "getInfoHTML.php?layername="+layername+"&resultID="+resultID);
	 xmlGetInfo.onreadystatechange = showInfoWindow;
	 
	 try {
	   //xmlUpdateMap.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	   xmlGetInfo.setRequestHeader('Content-Type','text/html')
	 }
	 catch (e) {
	 	// this only works in internet explorer
	 }
	 xmlGetInfo.send(null);
	

}
function showInfoWindow() {

           if (xmlGetInfo.readyState != 4)  {
	   		return;
	   	}
	
	var responseText = xmlGetInfo.responseText;
	// split off any javascript
	var readonlyhtml = responseText.split("|XX|");
	var scriptsource = readonlyhtml[2];
	if (scriptsource) {
		if (scriptsource.length > 0) {
			// we will only have source info if there is a photo
		//  	alert(scriptsource);
			var headID = document.getElementsByTagName("head")[0];
			var newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.text = scriptsource;
			headID.appendChild(newScript);
		   }
	}
	var layername = readonlyhtml[0];
	var taggedName = "";
	var desc = readonlyhtml[1];
	  var html1 = desc; //createInfo(this.layername,taggedName,desc);
	  var html2 = generateHeading();
	  var html3 = getInfoCloseButton();

	//var infoHTML = createInfo(layername,taggedName,desc) 
	
	
	// get the lat lng as the centre of the map in this case ..!
	lat = map.getCenter().lat();
	lng = map.getCenter().lng();
	
	
	showInfo(html1,html2,html3,lat,lng);

}

function getInfoCloseButton() {
	  html = "";
	  if (navigator.appName.indexOf('Microsoft') != -1) {
	         html += "<div style=\"height:8px;width:100%;\"></div>";  // a gap before the close button
	         html += "<button style=\"margin-bottom:0px;margin-right:5px;float:right;\" id=\"closeinfowindow\" type=\"button\" name=\"closeinfowindow\" ";
	  	 html += " onclick=\"doCloseInfoWindow()\">Close</button>";
	  }
	  else {
	        html += "<button style=\"margin-bottom:20px;margin-right:5px;float:right;\" id=\"closeinfowindow\" type=\"button\" name=\"closeinfowindow\" ";
	  	html += " onclick=\"doCloseInfoWindow()\">Close</button>";
	        html += "<div style=\"height:5px;width:100%;\"></div>";  // a gap after the close button
	  }
	  //html += "<button style=\"margin-bottom:2px;margin-right:5px;float:right;\" id=\"closeinfowindow\" type=\"button\" name=\"closeinfowindow\" ";
	  
	  
	return html;
}
function showInfo(infoHTML,headerHTML, footerHTML,lat,lng) {
	
	doCloseInfoWindow();
	infodisplayed = true;
	
	var html = "";	
	  html += "<div style=\"overflow-y:auto;overflow-x:auto;margin-left:3px;height:380px;width:97%;\">";
//	  html += "<div style=\"overflow-y:auto;overflow-x:auto;margin-left:3px;height:380px;width:100px;\">";
	  html += "<div style=\"margin-top:5px;border:2px solid green;border-style: double;\">";
//alert(infoHTML);
	  html +=  infoHTML;
	  html += "</div>"; // the actual data
	  html += "</div>"; // overflow div around the data

	
	document.getElementById('opaquetext').innerHTML = html;
	document.getElementById('topbuttonArea').innerHTML= headerHTML;
	
	//document.getElementById('buttonArea').innerHTML = footerHTML;
	document.getElementById('buttonArea').innerHTML = "";
	document.getElementById('container2').style.display = "block";
	document.getElementById('container2').style.top = "5px";
	document.getElementById('container2').style.margin = "0px";
	document.getElementById('container2').style.height = "95%";//document.getElementById('map-canvas').style.height;//"100%";
	document.getElementById('container2').style.display = "block";
	document.getElementById('opaquetext').style.top = "0px";
	//document.getElementById('opaquetext').innerHTML = infoHTML;
	document.getElementById('container2').style.width = "332px";//"30%";
	document.getElementById('opaquetext').style.width = "100%";
	//document.getElementById('opaquetext').style.height = "100%"

	// add the close button
	

	moveInfoWindow(lat,lng);
}
function moveInfoLine() {
	// if an info box is displayed, redraw the info line to the new position of the
	// element it relates to
	// if the element is now hidden under the info box, then close the info box
	// need to calculate the one third or two thirds again

	// get hold of the start of the polyline - this is the actual item that the info
	// box is pointing to
	pointlat = infopolyline.getVertex(0).lat();
	pointlng = infopolyline.getVertex(0).lng();
	//alert(pointlat);

	map.removeOverlay(infopolyline);

	// if the point is off the map, then close the info window

	if ((pointlat > map.getBounds().getSouthWest().lat() && pointlat < map.getBounds().getNorthEast().lat())
		&& (pointlng > map.getBounds().getSouthWest().lng() && pointlng < map.getBounds().getNorthEast().lng())) {
			//marker = new GMarker(polyline.getVertex(0));
			moveInfoWindow(pointlat,pointlng);
			// recalculate the position of the point
			// where the line intersects the div
	}
	else {
		doCloseInfoWindow();

	}
}
function moveInfoWindow(lat,lng) {

	mapminlat = map.getBounds().getSouthWest().lat();
	mapminlng = map.getBounds().getSouthWest().lng();
	mapmaxlat = map.getBounds().getNorthEast().lat();
	mapmaxlng = map.getBounds().getNorthEast().lng();
	onethirdlng = (mapmaxlng-mapminlng)/3 + mapminlng;
	twothirdslng = (mapmaxlng-mapminlng)*2/3 + mapminlng;
	
	fourninthslng = (mapmaxlng - mapminlng)* 4/9 + mapminlng;
	fiveninthslng = (mapmaxlng - mapminlng)* 5/9 + mapminlng;
	theWidth = parseInt(document.getElementById('map-canvas').style.width);
	// the position is total - 30% - 5px margin
	var newWidth = theWidth - ((40/100*theWidth)+10);

	if ((lng <= fourninthslng)) {
		var newPos = newWidth.toString();
		document.getElementById('container2').style.left = newPos+"px";
		// get the position of the pixel and use as the lng coordinate
		var pos = new GPoint(newWidth,100);
		var latLng = map.fromContainerPixelToLatLng(pos);
		var lng2 = latLng.lng();
		// draw a line between the marker and the info box centre
		infopolyline = new GPolyline([
  		  new GLatLng(lat, lng),
  		  new GLatLng((mapmaxlat-mapminlat)/2 + mapminlat, lng2)
  			], "#000000", 4,1);

	}
	if ((lng > fourninthslng) && (lng < fiveninthslng)) {
		var newWidth =  340; //45/100*theWidth;
		document.getElementById('container2').style.left = "10px";
		var pos = new GPoint(newWidth,100);
		var latLng = map.fromContainerPixelToLatLng(pos);
		var lng2 = latLng.lng();

        	infopolyline = new GPolyline([
  		  new GLatLng(lat, lng),
  		  new GLatLng((mapmaxlat-mapminlat)/2 + mapminlat, lng2)
		], "#000000", 4,1);
	}
	if ( lng >= fiveninthslng) {
		var newWidth = 340; //45/100*theWidth;
		document.getElementById('container2').style.left = "10px";
		var pos = new GPoint(newWidth,100);
		var latLng = map.fromContainerPixelToLatLng(pos);
		var lng2 = latLng.lng();
        	infopolyline = new GPolyline([
  		  new GLatLng(lat, lng),
  		  new GLatLng((mapmaxlat-mapminlat)/2 + mapminlat, lng2)
  		  ], "#000000", 4,1);
	}
	map.addOverlay(infopolyline);
}
function doCloseInfoWindow() {
	infodisplayed = false;
	document.getElementById('opaquetext').innerHTML = "";
	//document.getElementById('container2').style.left = "-4000px";
	
	document.getElementById('subTables').style.display = "none";
	document.getElementById('container2').style.display = "none";
	
	// remove the polyline that shows which item the info window refers to!
	infodisplayed = false;
	try {
		// just in case there is an existing polyline + info box open
		map.removeOverlay(infopolyline);
	}
	catch (e) {
	}

	// just in case the user is in moderation mode, remove the temporary moderation point line poly from the map
	try {
		// just in case there is an existing polyline + info box open
		map.removeOverlay(theAdminPoint);
	}
	catch (e) {
	}
	try {
		// just in case there is an existing polyline + info box open
		map.removeOverlay(theAdminLine);
	}
	catch (e) {
	}
	try {
		// just in case there is an existing polyline + info box open
		map.removeOverlay(theAdminPolygon);
	}
	catch (e) {
	}
	

}

