var map = null;
var geocoder = null;
var icon = new Array();

//var autozoom = false;
var so_busy = false;

// waar te beginnen op de kaart
var initial_center = new GLatLng(54.2, 6.0);
var initial_zoom = 3;
var city_zoom = 12;
var address_zoom = 16;

// globale variabelen kunnen/moeten aangepast worden door de gebruiker voordat init() aangeroepen wordt
var map_id = "map";
var message_id = "message";
var key = null;	// zonder geldige key geen objecten in de kaart!
var objects_url = "api/getobjects.php";
var icon_image = 'an2.png';
var icon_width = 13;
var icon_height = 19;

/***************************************************************************
** createIcons															  **
**																		  **
** specify all the icons needed for this collection 					  **
**																		  **
***************************************************************************/
function createIcons()
{
	// haal alle gebruikte iconen op
	var request = GXmlHttp.create();
	url = "icons.xml";
// 	url += key;
	request.open("GET", url, true);
	request.onreadystatechange = function()
	{
		if(request.readyState == 4)
		{
			var icons = request.responseXML.getElementsByTagName("icon");
			for(i = 0; i < icons.length; i++)
			{
			 	var index = icons[i].getAttribute("id");
			 	// maak icoon aan
				icon[index] = new GIcon(G_DEFAULT_ICON);
				icon[index].image = icons[i].getAttribute("path");
				// icon[index].iconAnchor = new GPoint(7,19);
//   	alert("Anker="+icons[i].getAttribute("ax")+","+icons[i].getAttribute("ay"));

				icon[index].iconAnchor = new GPoint(icons[i].getAttribute("ax"), icons[i].getAttribute("ay"));
				icon[index].shadow = '';
				icon[index].iconSize = new GSize(icons[i].getAttribute("width"), icons[i].getAttribute("height"));
			}
			
			// default vergrootglas icoon
			icon['0'] = new GIcon(G_DEFAULT_ICON);
			icon['0'].image = icon_image
			icon['0'].iconAnchor = new GPoint(7,19);
			icon['0'].shadow = '';
			icon['0'].iconSize = new GSize(icon_width, icon_height);
		}
	}
	request.send(null);		
}


/***************************************************************************
** createmarker														  	  **
**																		  **
** create a marker from infomation send by server						  **
**																		  **
***************************************************************************/
function createMarker(obj)
{
//   	alert("ic="+obj.getAttribute("ic"));
	var marker =  new GMarker(new GLatLng(obj.getAttribute("y"), obj.getAttribute("x")), { icon: icon[obj.getAttribute("ic")], title: obj.getAttribute("in")});
	
	if(obj.getAttribute("a") == 1)
	{
		GEvent.addListener(
							marker, 
							"click",
							function()
							{
								map.closeInfoWindow();
								map.setCenter(marker.getPoint(), address_zoom);
								// haal de informatie van de server
							 	var request = GXmlHttp.create();
							 	url = "toonid.php?id=" + obj.getAttribute("id");
							 	request.open("GET", url, true);
							 	request.onreadystatechange = function()
							 			{
							 			if(request.readyState==4)
								marker.openInfoWindowHtml(request.responseText);
										}
 								request.send(null);
							}
						   )	
	}
	else
	{
		GEvent.addListener(
							marker, 
							"click",
							function()
							{
								map.closeInfoWindow();
								map.setCenter(marker.getPoint(), map.getZoom()+2);
							}
						   )	
		
	}
	
	return marker;
}

/***************************************************************************
** showObjects															  **
**																		  **
** show all visible objects on the map, objects that overlap will be 	  **
** joined to one magnifying glass							  **
**																		  **
***************************************************************************/
function showObjects()
{
	if (so_busy) 
		return;
		
	so_busy = true;
// alert("In showObjects");	
	var bounds = map.getBounds();
	var sw = bounds.getSouthWest();
	var ne = bounds.getNorthEast();
	var size = map.getSize();
	// haal alle zichtbare objecten	op
	var request = GXmlHttp.create();
	var url = objects_url+"?";
	url += "env="+sw.toUrlValue()+","+ne.toUrlValue();
	url += "&width="+size.width+"&height="+size.height;
	url += "&zoomlevel="+map.getZoom();
	url += "&key="+key;
// alert("URL"+url);
// url api/getobjects.php?env=50.380502,1.175537,53.75537,8.811035&width=695&height=500&zoomlevel=7&key=abcdef
 	var url = "toonxml.php?xzw="+ map.getBounds().getSouthWest().lng()+"&yzw="+map.getBounds().getSouthWest().lat()+"&xno="+ map.getBounds().getNorthEast().lng()+"&yno="+ map.getBounds().getNorthEast().lat() ;
// alert("URL"+url);
	map.clearOverlays();
// alert("na overlays");
	request.open("GET", url, true);
	request.onreadystatechange = function() 
	{
//		if (request.readyState == 1) 
//		{
//			document.getElementById(message_id).innerHTML = 'Een moment aub ...';
//		}

		if (request.readyState == 4) 
		{
// Let op geen echte XML!?
// 			var items = request.responseXML.getElementsByTagName("marker");
                  var xmlDoc = GXml.parse(request.responseText);
			var items = xmlDoc.documentElement.getElementsByTagName("marker");
			// alert("items.length = "+items.length);
			for (i = 0; i < items.length; i++) 
			{
				map.addOverlay(createMarker(items[i]));
			}

			document.getElementById(message_id).innerHTML = '';
		}
	}
	request.send(null);
	so_busy = false;
}


/***************************************************************************
** getLogUrl																**
**																			**
** construct the url for the logger											**
**																			**
***************************************************************************/
function getLogUrl(code, comment, lat, lng)
{
	var url = "api/log.php?";
	
	url = url + "code="+code 
	url = url + "&key="+escape(key);
	if(comment)
		url = url + "&comment="+escape(comment);
	if(lat)
		url = url + "&lat="+lat;
	if(lng)
		url = url + "&lng="+lng;
	
	return url;
}

/***************************************************************************
** logEvent																	**
**																			**
** send the event to the logger												**
**																			**
***************************************************************************/
function logEvent(code, comment, lat, lng)
{
	var request = GXmlHttp.create();
	request.open("GET", getLogUrl(code, comment, lat, lng), true);
	request.send(null);
}

/***************************************************************************
** findLocation															  **
**																		  **
** find the location specified by the user using the geocoder from Google **
** sends action and result to the remote logger							  **
**																		  **
***************************************************************************/

function findLocation(location)
{
	// log action
//	logEvent(100, location);
	
	// find the location
	geocoder.getLatLng
	(
		location+", europe",
		function(point)
		{
			if (!point) 
			{
//				document.getElementById(message_id).innerHTML = 'locatie ' + location + ' niet kunnen vinden';
				logEvent(101, location);
			}
			else 
			{
				logEvent(102, location, point.lat(), point.lng());
//				document.getElementById(message_id).innerHTML = 'locatie ' + location + ' gevonden';
				map.setCenter(point, city_zoom);
				showObjects();
			} 
		}
	);
}

/***************************************************************************
** init															  		  **
**																		  **
** this is where it all starts, called by the user to start the locator   **
**																		  **
***************************************************************************/
function init()
{
	if (GBrowserIsCompatible()) 
	{
		// create the map
		map = new GMap2(document.getElementById(map_id));
		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		map.setCenter(initial_center, initial_zoom);
		map.setMapType(G_SATELLITE_MAP);
		// create the geocoder
		geocoder = new GClientGeocoder();
		// load the objects from the server
		createIcons();
		
		showObjects(map);
		GEvent.addListener
		(
			map, 
			"moveend", 
			function() 
			{
			    showObjects();
			}
		);
	}
}


