
/*
How the marker query:

Get all markers within visible bounds at zoom level
On move end - check for load event in progress
	if load flag
		do not fire request
	else
		fire request - set load flag

*/

var saveCastleOnce;

var mapRequestInProgress;

//the map control
var map;
var yourCastleMarker;
var geocoder;
var enemyCastleIcon;

//Name of location
var google_castleLocation;
//coords of castle
var google_castleLong;
var google_castleLat;

//Saving info
var playerCastle_Long;
var playerCastle_Lat;
var playerCastle_Country;
var playerCastle_Area;
var playerCastle_SubArea;
var playerCastle_Locality;
var playerCastle_ShortDesc;
var playerCastle_LongDesc;
var playerCastle_FullAddress;

//visible castles array
var visibleCastles;
var visiblePolygons;

var mapServerScriptUrl = "ajaxphp/map_ajax.php";

function SiteYourCastleControl() {}

function setup_googlemap()
{		
	SiteYourCastleControl.prototype = new GControl();
	SiteYourCastleControl.prototype.initialize = 
	function(map) 
	{  
		//Add UI to map
		var container = document.createElement("div");
		var buttonDIV = document.createElement("div");		
		
		buttonDIV.id = "siteButton";		
		setButtonStyle(buttonDIV);
		buttonDIV.appendChild(document.createTextNode("Click here to Site your Castle"));				
		container.appendChild(buttonDIV);
		
		//Create a new castle button click
		GEvent.addDomListener(buttonDIV, "click", 
			function()
			{   
				var point = map.getCenter();			
				
				if(!yourCastleMarker)
				{
					// Create your castle marker icon
					var castleIcon = new GIcon(G_DEFAULT_ICON);
					castleIcon.image = "26-Castle-32x32.png";						
					yourCastleMarker = new GMarker(point, {icon:castleIcon,draggable:true,title:"Your Castle"});									
					map.addOverlay(yourCastleMarker);	
				}
				else
				{
					map.removeOverlay(yourCastleMarker);
					
					yourCastleMarker.setLatLng(point);
					var castleIcon = new GIcon(G_DEFAULT_ICON);
					castleIcon.image = "26-Castle-32x32.png";				
					yourCastleMarker = new GMarker(point, {icon:castleIcon,draggable:true,title:"Your Castle"});									
					map.addOverlay(yourCastleMarker);
				}
				$("siteButton").innerHTML = "Click here to re-site your castle";
				
				getLocationFromPoint(yourCastleMarker.getLatLng());
				//Drop castle marker
				GEvent.addDomListener(yourCastleMarker, "dragend", 
					function()
					{
						if(yourCastleMarker)
							getLocationFromPoint(yourCastleMarker.getLatLng());						
					});
			});							
			
		//Site button event handlers
		GEvent.addDomListener(buttonDIV, "mouseover", 
			function()
			{   
				buttonDIV.style.backgroundColor = "#aaaaaa";  
			});
		GEvent.addDomListener(buttonDIV, "mouseout", 
			function()
			{   
				buttonDIV.style.backgroundColor = "white";  
			});
		
		map.getContainer().appendChild(container);
		return container;
	}
	SiteYourCastleControl.prototype.getDefaultPosition = 
	function()
	{  
		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
	}
}

function init_googlemap()
{      			
	yourCastleMarker = null;
	if(debug_switch)
		alert("init googlemap");
	$("locationNextButton").disabled = true;	
	mapRequestInProgress = false;
	
	if (GBrowserIsCompatible()) 
	{        						
		geocoder = new GClientGeocoder();
		setup_googlemap();
		
		//IF IE then hide normal version and show IE version of map
		if(global_IE7_Compat_mode)
		{
			if($('IeMapWrapperDIV'))
			{
				$('IeMapWrapperDIV').style.display = 'block';			
				centerLightbox();
			
				map = new GMap2(document.getElementById("ie_map_canvas"));		
			}
		}
		else
		{
			if($('IeMapWrapperDIV'))
			{
				$('IeMapWrapperDIV').style.display = 'none';	
				map = new GMap2(document.getElementById("map_canvas"));		
			}
		}							
		
		//set UI options
		var customUI = map.getDefaultUI();
		customUI.controls.scalecontrol = false;
		customUI.maptypes.normal = false;
		customUI.maptypes.satellite = false;
		customUI.maptypes.hybrid = false;
		customUI.maptypes.physical = false;
		
		//set map UI
		map.setUI(customUI);
		map.addControl(new SiteYourCastleControl());
		
		//May not be compatible with odd browsers!!?!?!?!?!?
		//map.enableContinuousZoom();
		
		//Set to physical (terrain) map
		map.setMapType(G_PHYSICAL_MAP);
		
		//Restrict the zoom - don't let people find your house!
		GEvent.addListener(map, "zoomend", 
			function(oldLevel,newLevel) 
			{  							
				if(newLevel>13 || newLevel <3)
					map.setZoom(oldLevel);
				getCastles();
			});
		GEvent.addListener(map, "moveend", 
			function() 
			{  											
				getCastles();
			});
		GEvent.addListener(map, "dragend", 
			function() 
			{  											
				getCastles();
			});
		
		//Load enemy castles
		enemyCastleIcon = new GIcon(G_DEFAULT_ICON);
		enemyCastleIcon.image = "08-Castle-32x32.png";						

		visibleCastles = new Array();
		visiblePolygons = new Array();
				
		//is this the player's first visit?
		//default to somewhere near london.		
		//or hover over your castle (and zoom in) BEFORE getting castles.		
		if($("LastCastlePos_Long") && $("LastCastlePos_Lat"))
		{
			var lastlat = $("LastCastlePos_Lat").value;
			var lastlong = $("LastCastlePos_Long").value;
			map.setCenter(new GLatLng(lastlat, lastlong), 13);		
			$("siteButton").innerHTML = "Click here to re-site your castle";
		}
		else
		{
			map.setCenter(new GLatLng(51.5, 0), 4);		
		}			
	}    
}

//set style on a map button
function setButtonStyle(element)
{
	element.style.color = "#800000";  
	element.style.backgroundColor = "white";  
	element.style.font = "small Arial";  
	element.style.border = "1px solid black";  
	element.style.padding = "2px";  
	element.style.marginBottom = "3px";  
	element.style.textAlign = "center";  	
	element.style.cursor = "pointer";
}

//Google's default address lookup provider - TODO: use a better one for UK postcodes.
function showAddress(address) 
{  	
	geocoder.getLatLng(    address,
		function(point)
		{      
			if (!point) 
			{        
				alert(address + " not found");      
			} 
			else
			{       
				map.setCenter(point, 13);				     				
				map.openInfoWindowHtml(point,"Did you mean here?");				
			}    
		});
}

function getLocationFromPoint(point)
{	
	geocoder.setBaseCountryCode('UK');
	geocoder.getLocations(point,
		function(address)
		{			
			if(!address["Placemark"] || address["Placemark"].length <1)
			{				
				alert("Sorry, you cannot site your castle there.");
				
				clearCastles();
				map.removeOverlay(yourCastleMarker);
				yourCastleMarker = null;
				getCastles();
				return;				
			}
		
			var pm = address["Placemark"];
			
			if(console)
				console.log(pm);
			
			var aa = "";
			var saa = "";
			var loc = "";
			var homenation = "";
			var country = "";													
						
			for(l =0;l<pm.length;l++)
			{
				if(pm[l].AddressDetails.Country)
				{			
					if(console)
						console.log(pm[l]);
					//find home nations
					if(pm[l].AddressDetails && pm[l].AddressDetails.Country && pm[l].AddressDetails.Country.AddressLine && pm[l].AddressDetails.Country.AddressLine[0])
					{				
						homenation = pm[l].AddressDetails.Country.AddressLine[0]
						if(console)
							console.log(homenation);
					}
					else
					{
						if(console)
							console.log("no home nation");
					}
				
					//country				
					if(pm[l].AddressDetails.Country.CountryName)
					{
						if(country == "")
							country = pm[l].AddressDetails.Country.CountryName;
					}		

					//area
					if(pm[l].AddressDetails.Country.AdministrativeArea)
					{
						if(aa == "" || aa == country)
							aa = pm[l].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName.trim();		

						//sub area
						if(pm[l].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea)
						{
							if(saa =="" || saa == aa)
								saa = pm[l].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName.trim();
							
							if(pm[l].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality)
							{
								//locality
								if(loc =="" || loc == aa || loc == saa)
									loc = pm[l].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName.trim();
							}
						}
						else if(pm[l].AddressDetails.Country.AdministrativeArea.Locality)
						{
							//locality - Fixes Czech Republic
							if(loc =="" || loc == aa || loc == saa)
								loc = pm[l].AddressDetails.Country.AdministrativeArea.Locality.LocalityName.trim();
						}					
					}
					//sub area - Fixes Sweden
					else if(pm[l].AddressDetails.Country.SubAdministrativeArea)
					{
						if(saa =="" || saa == aa)
							saa = pm[l].AddressDetails.Country.SubAdministrativeArea.SubAdministrativeAreaName.trim();
							
						//locality
						if(pm[l].AddressDetails.Country.SubAdministrativeArea.Locality)
						{						
							if(loc =="" || loc == aa || loc == saa)
								loc = pm[l].AddressDetails.Country.SubAdministrativeArea.Locality.LocalityName.trim();
						}
					}	
				}				
			}
			
			if(loc == saa)
				loc = "";			
			if(saa == aa)
				saa = "";			
			
			playerCastle_Area = aa;
			playerCastle_SubArea = saa;
			playerCastle_Locality = loc;
			
			if(loc != "")
				loc += ", ";
			if(saa != "")
				saa += ", ";
			if(aa != "")
				aa += ", ";					
						
			
			if(country == "")
			{			
				var fulladdress = pm[0].address.split(',');
				country = fulladdress[fulladdress.length-1];						
			}
				
			if(console)
				console.log(country);
			
			if(homenation != "" && (country.trim() == "United Kingdom" || country.trim() == "UK"))			
				country = homenation;			
			else if (country.trim() == "United Kingdom")
				country = "England"; // England is not a country --- but Scotland, Northern Ireland and Wales are!			
				
			google_castleLocation = loc + saa + aa + country;
			
			if(console)
				console.log(google_castleLocation);
					
			map.openInfoWindowHtml(yourCastleMarker.getLatLng(),"<b>Your castle is sited at: " + google_castleLocation + "</b><p>When you are happy with the position of your castle, please click \"Done\".</p>");
			yourCastleMarker.bindInfoWindowHtml("<b>This is your castle: " + google_castleLocation + "</b>");
				
			//enable next button
			$("locationNextButton").disabled = false;
			
			playerCastle_Long = yourCastleMarker.getLatLng().lng();
			playerCastle_Lat = yourCastleMarker.getLatLng().lat();
			playerCastle_Country = country;										
			playerCastle_FullAddress = pm[0].address;	
		});	
}

function clearCastles()
{
	if(visibleCastles && visibleCastles.length >0)
	{
		for(i = 0;i<visibleCastles.length;i++)
		{
			map.removeOverlay(visibleCastles[i]);
		}
	}
	visibleCastles = new Array();
	if(visiblePolygons && visiblePolygons.length >0)
	{
		for(i = 0;i<visiblePolygons.length;i++)
		{
			map.removeOverlay(visiblePolygons[i]);
		}
	}
	visiblePolygons = new Array();
}

//clear castles array and get castles from the db
function getCastles()
{			
	postData = new Array();
	postData["ZoomLevel"] = map.getZoom();
	postData["NorthEastLat"] = map.getBounds().getNorthEast().lat();
	postData["NorthEastLong"] = map.getBounds().getNorthEast().lng();
	postData["SouthWestLat"] = map.getBounds().getSouthWest().lat();
	postData["SouthWestLong"] = map.getBounds().getSouthWest().lng();
		
	if(!mapRequestInProgress)
	{
		mapRequestInProgress = true;
		if(debug_switch)
			alert("getting castles... ");
		doCallbackPost(mapServerScriptUrl,"GetCastles",postData,null);
	}
	else
	{
		if(debug_switch)
			alert("not getting, in progress");
	}
}

//Now handles ALL castles FLAGS and the Player's castle
function putEnemyCastle(lat,lng,shortDesc,longDesc,username,count,mycastle)
{
	var opacity = 0.01*count;

	if(username == "Country")
	{				
		if(count >0)
		{
		point = new GLatLng(lat,lng);
		var CountryIcon = new GIcon(G_DEFAULT_ICON);		
		//CountryIcon.image = "mapicon.php?text="+count;
		CountryIcon.image = getPopulationFlag(count,username);
		CountryIcon.iconSize = new GSize(20, 14);
		CountryIcon.shadow = null;
		CountryIcon.iconAnchor = new GPoint(0,14);
		CountryMarker = new GMarker(point, {icon:CountryIcon,draggable:false,title:shortDesc});
		map.addOverlay(CountryMarker);
		CountryMarker.bindInfoWindowHtml("<b>"+shortDesc+"</b><p>"+longDesc+"</p><p>"+ username +"</p>");
		visibleCastles[visibleCastles.length] = CountryMarker;	
		}
	}
	else if(username == "Area" )
	{
		//var polygon = new GPolygon([
//			new GLatLng(lat, lng - 0.5),
			//new GLatLng(lat + 0.5, lng),
			//new GLatLng(lat, lng + 0.5),
			//new GLatLng(lat - 0.5, lng), 
			//new GLatLng(lat, lng - 0.5)  ], "#f33f00", 0, 1, "#ff0000", opacity);
		
		//map.addOverlay(polygon);
		//visiblePolygons[visiblePolygons.length] = polygon;
		
		if(count >0)
		{
		point = new GLatLng(lat,lng);
		var CountryIcon = new GIcon(G_DEFAULT_ICON);
		//CountryIcon.image = "mapicon.php?text="+count;
		CountryIcon.image = getPopulationFlag(count,username);
		CountryIcon.iconSize = new GSize(20, 14);
		CountryIcon.shadow = null;
		CountryIcon.iconAnchor = new GPoint(0,14);
		CountryMarker = new GMarker(point, {icon:CountryIcon,draggable:false,title:shortDesc});
		map.addOverlay(CountryMarker);
		CountryMarker.bindInfoWindowHtml("<b>"+shortDesc+"</b><p>"+longDesc+"</p><p>"+ username +"</p>");
		visibleCastles[visibleCastles.length] = CountryMarker;	
		}
	}
	else if(username == "SubArea")
	{		
		if(count >0)
		{
		point = new GLatLng(lat,lng);
		var CountryIcon = new GIcon(G_DEFAULT_ICON);
		//CountryIcon.image = "mapicon.php?text="+count;
		CountryIcon.image = getPopulationFlag(count,username);
		CountryIcon.iconSize = new GSize(20, 14);
		CountryIcon.shadow = null;
		CountryIcon.iconAnchor = new GPoint(0,14);
		CountryMarker = new GMarker(point, {icon:CountryIcon,draggable:false,title:shortDesc});
		map.addOverlay(CountryMarker);
		CountryMarker.bindInfoWindowHtml("<b>"+shortDesc+"</b><p>"+longDesc+"</p><p>"+ username +"</p>");
		visibleCastles[visibleCastles.length] = CountryMarker;	
		}
	}
	else if(username == "Locality" )
	{		
		if(count >0)
		{
		point = new GLatLng(lat,lng);
		var CountryIcon = new GIcon(G_DEFAULT_ICON);
		//CountryIcon.image = "mapicon.php?text="+count;
		CountryIcon.image = getPopulationFlag(count,username);
		CountryIcon.iconSize = new GSize(20, 14);
		CountryIcon.shadow = null;
		CountryIcon.iconAnchor = new GPoint(0,14);
		CountryMarker = new GMarker(point, {icon:CountryIcon,draggable:false,title:shortDesc});
		map.addOverlay(CountryMarker);
		CountryMarker.bindInfoWindowHtml("<b>"+shortDesc+"</b><p>"+longDesc+"</p><p>"+ username +"</p>");
		visibleCastles[visibleCastles.length] = CountryMarker;	
		}
	}
	else 
	{
		//This is either a player castle or the current player's castle
		if(mycastle ==0)
		{
			point = new GLatLng(lat,lng);
			CastleMarker = new GMarker(point, {icon:enemyCastleIcon,draggable:false,title:shortDesc});
			map.addOverlay(CastleMarker);
			CastleMarker.bindInfoWindowHtml("<b>"+shortDesc+"</b><p>"+longDesc+"</p><p>"+ username +"</p>");
			visibleCastles[visibleCastles.length] = CastleMarker;		
		}
		else
		{	
			if(!yourCastleMarker)
			{
				point = new GLatLng(lat,lng);
				var castleIcon = new GIcon(G_DEFAULT_ICON);
				castleIcon.image = "26-Castle-32x32.png";						
				yourCastleMarker = new GMarker(point, {icon:castleIcon,draggable:false,title:"Your Castle"});									
				yourCastleMarker.bindInfoWindowHtml("<b>This is your castle: " + google_castleLocation + "</b>");
				map.addOverlay(yourCastleMarker);
			}
		}
	}
}

//Save castle to db
function createPlayerCastle(sh3)
{
	//if(saveCastleOnce == null || saveCastleOnce == 0)
	//{
		saveCastleOnce=1;

		//alert("long: " + playerCastle_Long + "lat: " + playerCastle_Lat + "country: " + playerCastle_Country 
		//+ "area: " + playerCastle_Area + "subarea: " + playerCastle_SubArea + "locality: " + playerCastle_Locality + "full: " + playerCastle_FullAddress);
	
		//float 0 gets passed as null or empty string!
	
		if(playerCastle_Long == 0)	
			playerCastle_Long = 0.0001;			//todo find a better workaround
			
		if(playerCastle_Lat == 0)	
			playerCastle_Lat = 0.0001;	
	
		var postData = new Array();					
		postData["long"] = playerCastle_Long;
		postData["lat"] = playerCastle_Lat;
		postData["country"] = playerCastle_Country;
		postData["area"] = playerCastle_Area;
		postData["subarea"] = playerCastle_SubArea;
		postData["locality"] = playerCastle_Locality;
		postData["fulladdress"] = playerCastle_FullAddress;
		
		if(sh3 && sh3 == "1")
			postData["SH3"] = "1";

		if(debug_switch)
		{
			alert("long: "+playerCastle_Long+"\r\n");
			alert("lat: "+playerCastle_Lat+"\r\n");
			alert("country: "+playerCastle_Country+"\r\n");
			alert("area: "+playerCastle_Area+"\r\n");
			alert("subarea: "+playerCastle_SubArea+"\r\n");
			alert("locality: "+playerCastle_Locality+"\r\n");
			alert("fulladdress: "+playerCastle_FullAddress+"\r\n");
		}
	
		//alert("CreateCastle");
		doCallbackPost(mapServerScriptUrl,"SaveCastle",postData,"");
	//}
}

function getPopulationFlag(count,level)
{
	var imagename = "";
	var density;
	var factor =0;

	switch(level)
	{
		case "Country":
			factor = 5;
			break;
		case "Area":
			factor =3;
			break;
		case "SubArea":
			factor = 2;
			break;
		case "Locality":
			factor =1;
			break;
	}
	
	//alert(count);
	//alert(factor);
	//alert(count/factor);
	//alert(Math.floor(count/factor));
	
	density = Math.floor(count/factor);
	
	if(density ==0)
		density = 1;
	if(density >20)
		density = 20;
		
	imagename = "./img/flag_"+density+".png";
	
	return imagename;
}







