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(52.18553,5.26496); //       map.setCenter(new GLatLng(52.18553,5.26496), 7);

var initial_zoom = 7;
var city_zoom = 13;
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 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);
								map.setCenter(marker.getPoint());
								// 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;
		
        if (document.getElementById("g").checked==true) { var g ="0";} else { var g="1"; }
        if (document.getElementById("s").checked==true) { var s ="0";} else { var s="1"; }
        if (document.getElementById("u").checked==true) { var u ="0";} else { var u="1"; }
        if (document.getElementById("c").checked==true) { var c ="0";} else { var c="1"; }
        if (document.getElementById("h").checked==true) { var h ="0";} else { var h="1"; }
        if (document.getElementById("f").checked==true) { var f ="0";} else { var f="1"; }

        if (document.getElementById("e").checked==true) { var e ="0";} else { var e="1"; }
        if (document.getElementById("d").checked==true) { var d ="0";} else { var d="1"; }
        if (document.getElementById("t").checked==true) { var t ="0";} else { var t="1"; }
        if (document.getElementById("v").checked==true) { var v ="0";} else { var v="1"; }
        if (document.getElementById("m").checked==true) { var m ="0";} else { var m="1"; }

	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();
// alert("URL"+url);
 	var url = "toonxml.php?xzw="+ map.getBounds().getSouthWest().lng()+"&yzw="+map.getBounds().getSouthWest().lat()+"&xno="+ map.getBounds().getNorthEast().lng()+"&yno="+ map.getBounds().getNorthEast().lat()+"&g="+ g +"&s="+ s+"&u="+ u+"&c="+ c+"&h="+ h+"&f="+ f+"&e="+ e +"&d="+ d+"&t="+ t+"&v="+ v+"&m="+ m;
// 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]));
			}

var aant = document.getElementById("ag"); aant.firstChild.nodeValue="GSM 900 mast (0)";
var aant = document.getElementById("as"); aant.firstChild.nodeValue="GSM 1800 mast (0)";
var aant = document.getElementById("au"); aant.firstChild.nodeValue="UMTS mast (0)";
var aant = document.getElementById("ac"); aant.firstChild.nodeValue="C2000 mast (0)";
var aant = document.getElementById("ah"); aant.firstChild.nodeValue="Wi-Fi HotSpot (0)";
var aant = document.getElementById("af"); aant.firstChild.nodeValue="FON WiFi (0)";
var aant = document.getElementById("ae"); aant.firstChild.nodeValue="Eduroam Wi-Fi (0)";
var aant = document.getElementById("ad"); aant.firstChild.nodeValue="Digitale TV (0)";
var aant = document.getElementById("at"); aant.firstChild.nodeValue="Digitale Radio (0)";
var aant = document.getElementById("av"); aant.firstChild.nodeValue="Analoge TV (0)";
var aant = document.getElementById("am"); aant.firstChild.nodeValue="Analoge FM radio (0)";

                        var nummers = xmlDoc.documentElement.getElementsByTagName("aantal");
			// alert("items.length = "+items.length);
			for (i = 0; i < nummers.length; i++) 
			{
                           if (nummers[i].getAttribute("id")=="ag") { var aant = document.getElementById("ag");	aant.firstChild.nodeValue="GSM 900 mast ("+nummers[i].getAttribute("a")+")"; }
                           if (nummers[i].getAttribute("id")=="as") { var aant = document.getElementById("as");	aant.firstChild.nodeValue="GSM 1800 mast ("+nummers[i].getAttribute("a")+")"; }
                           if (nummers[i].getAttribute("id")=="au") { var aant = document.getElementById("au");	aant.firstChild.nodeValue="UMTS mast ("+nummers[i].getAttribute("a")+")"; }
                           if (nummers[i].getAttribute("id")=="ac") { var aant = document.getElementById("ac");	aant.firstChild.nodeValue="C2000 mast ("+nummers[i].getAttribute("a")+")"; }
                           if (nummers[i].getAttribute("id")=="ah") { var aant = document.getElementById("ah");	aant.firstChild.nodeValue="WiFi HotSpot ("+nummers[i].getAttribute("a")+")"; }
                           if (nummers[i].getAttribute("id")=="af") { var aant = document.getElementById("af");	aant.firstChild.nodeValue="FON WiFi ("+nummers[i].getAttribute("a")+")"; }
                           if (nummers[i].getAttribute("id")=="ae") { var aant = document.getElementById("ae");	aant.firstChild.nodeValue="Eduroam Wi-Fi ("+nummers[i].getAttribute("a")+")"; }
                           if (nummers[i].getAttribute("id")=="ad") { var aant = document.getElementById("ad");	aant.firstChild.nodeValue="Digitale TV ("+nummers[i].getAttribute("a")+")"; }
                           if (nummers[i].getAttribute("id")=="at") { var aant = document.getElementById("at");	aant.firstChild.nodeValue="Digitale Radio ("+nummers[i].getAttribute("a")+")"; }
                           if (nummers[i].getAttribute("id")=="av") { var aant = document.getElementById("av");	aant.firstChild.nodeValue="Analoge TV ("+nummers[i].getAttribute("a")+")"; }
                           if (nummers[i].getAttribute("id")=="am") { var aant = document.getElementById("am");	aant.firstChild.nodeValue="Analoge FM Radio ("+nummers[i].getAttribute("a")+")"; }
			}
// var head1 = document.getElementById("head1");
//   head1.firstChild.nodeValue=items.length;

//var ag = document.getElementById("ag");
//    ag.firstChild.nodeValue="GSM 900 mast ("+items.length+")";
			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 = "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+", nl",
		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.addControl(new GScaleControl());
                map.enableScrollWheelZoom();
//		map.setMapType(G_SATELLITE_MAP);
// 		map.setMapType(MAP);
		// create the geocoder
		geocoder = new GClientGeocoder();
		// load the objects from the server
		createIcons();
		
		showObjects(map);
		GEvent.addListener
		(
			map, 
			"moveend", 
			function() 
			{
			    showObjects();
			}
		);
	}
}

