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("mapinterface");
	var currWidth = parseInt(getStyle(el,"width"));
	var newWidth = parseInt(document.body.clientWidth) - 300;
	setStyle("mapinterface", "width", newWidth + "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>";       

	document.getElementById('mapinterface').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
			
	}
	
	//alert("toggle layer");
	if (layername == "user_datas") {
		alert("user_datas");
		for (var i=1;i = user_datas.allMarkers.length; i++) {
			user_datas.map.removeOverlay(user_datas.allMarkers[i]);
		}
	
	}
}*/
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
   	//alert("map data available");
	var responseText = xmlUpdateMap.responseText;
	//alert(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);
	//alert("map updated");

	setUpSearchTab();
	setupAddContentTab1();
	
	
	// get all the required javascript to process data adding etc?
	setupJavaScript();
	
	GEvent.addListener(map,'moveend',function() {
		// only add icons if we are not in edit mode ..
		if (currentTab != "edit") {
			updateMap(true);
		}
		if (infodisplayed == true) {
			doCloseInfoWindow();
		}

	}); 
}
function finishMap(pts,p) {
   //var zoomLevel = getZoomLevelForPoints(pts);
      map = new GMap2(document.getElementById("mapinterface"));
      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);  
   //alert (zoomLevel);
      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 checkEditEnter(event){
	if(event.keyCode==13)
	doAdminLogin();
}


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;
	   	}
	//alert("show info window");
	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,html4) {
	
	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

	
	
	  var ni = document.getElementById('mapwrapper');
	  var newdiv = document.createElement('div');
	  var divIdName = 'infowindow';
	  newdiv.setAttribute('id',divIdName);
	  newdiv.setAttribute('class','png');
	  newdiv.setAttribute('style', 'visibility: visible');
	 
	 
	  var infoHeader = "<h2 class=\"maphidden\">Info Window</h2>";
	  
	  //infoHeader = infoHeader + "<div id=\"infotabs\">"; 
	  //infoHeader = infoHeader + "<ul><li class=\"infotab01current png\"><span class=\"maphidden\">Info</span></li>";
	  //infoHeader = infoHeader + "</ul></div>";
	  	
	  infoHeader = infoHeader + html4;
	  //alert(infoHeader);
	  
	  /*<div id="infotabs"> 
		<ul>
		<li><a class="infotab01 png" href="map_legend_info.html"><span class="maphidden">Info</span></a></li>
		<li class="infotab02current png"><span class="maphidden">Photos</span></li>
		<li><a class="infotab03 png" href="map_legend_noise.html"><span class="maphidden">Noise</span></a></li>
		</ul>	
		</div> */

	  
	  var mapLatLng = new GLatLng(lat,lng);
	  var theGPoint = map.fromLatLngToContainerPixel(mapLatLng);
	  var xPix = theGPoint.x;
	  var yPix = theGPoint.y;
	  var infoHeight = 300;


	  if (xPix > 350) {
	  	  var infoArrow = "<div id=\"infopointerright\" class=\"png\"></div>";
	  }
	  else {
		  var infoArrow = "<div id=\"infopointerleft\" class=\"png\"></div>";
	  }
	  
	  var infoWrapper = "<div id=\"infocontent\" class=\"png\">";
	  infoWrapper = infoWrapper + "<img onclick=\"doCloseInfoWindow()\" src=\"images/butt_close_off.gif\" alt=\"Close\" width=\"16\" height=\"16\"";
	  infoWrapper = infoWrapper + "class=\"closebutton\" />";

	  //alert(headerHTML);
	  newdiv.innerHTML = infoHeader + infoWrapper + headerHTML+"<div id=\"infodescription\">"+infoHTML + "</div></div>" + infoArrow;
	  ni.appendChild(newdiv);
	  
	  
	  
	  document.getElementById('infowindow').style.top = (yPix - infoHeight/2)+ "px";
	  
	  if (xPix > 350) {
	 	 document.getElementById('infowindow').style.left = (xPix -315) + "px";
	  	document.getElementById('infopointerright').style.top = 125+ "px";
	  	document.getElementById('infopointerright').style.left = 290 + "px";
	  
	  }
	  else {
	 	 document.getElementById('infowindow').style.left = 15+xPix+ "px";
	  	document.getElementById('infopointerleft').style.top = 125+ "px";
	  	document.getElementById('infopointerleft').style.left = -18 + "px";
	  }
	
	// make the info box visible
	document.getElementById('infowindow').style.visibility = "visible";
}
function doCloseInfoWindow() {
	infodisplayed = false;
	
	  var ni = document.getElementById('mapwrapper');
	  
	  // try this - is the window already visible?
	  try {
		  var infodiv = document.getElementById('infowindow');
		  ni.removeChild(infodiv);
	  }
	  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) {
	}
	

}

function toggleAllLayers() {
	// switch all layers on or off
	if (document.getElementById('allLayersOn').checked == true)  {
		switchAllLayersOn();
	}
	else {
		trackLayerStatus();
		switchAllLayersOff();
	}

}

