var map = null;
var geocoder = null;

function loadMap(id) {
	initializeMap();
	
	$.getJSON("/efe/opleiding-ajax/get-startdata-json/id/" + id, function(data) {
		$.each(data, function(i, location) {
			var address = location.postcode + ", " + location.plaats;
			var info = "<strong>" + location.cursusnaam + "</strong><br />" + location.postcode + " " + location.plaats + "<br /><br /><a href=\"/inschrijven/-/id/" + location.opleidingId + "/start/" + location.id + "\">Direct inschrijven</a>";
			showLocation(address, info);
		});
	});
}

function initializeMap() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		map.setUIToDefault();
		geocoder = new GClientGeocoder();
	}
}

function showSearchLocation(address) {
	if (geocoder)
	{
	    geocoder.getLatLng(address + " NL",
	        function (point)
	        {
		    	if (!point) {
		    		// If not found, try again - might cause a loop if it really cannot be found! but hey, living on the edge! ;)
		    		window.setTimeout("showSearchLocation('" + address + "')", 500);
		    	}
		    	else {
		        	map.setCenter(point, 9, G_NORMAL_MAP);
		            map.addOverlay(createSearchMarker(point, address));
		    	}
	        }
	    );
	}
}

function showLocation(address, info) {
	if (geocoder)
	{
	    geocoder.getLatLng(address + " NL",
	        function (point)
	        {
	    		if (!point) {
	    			//alert(address + " not found!");
	    		}
	    		else {
	    			map.setCenter(point, 9, G_NORMAL_MAP);
		            map.addOverlay(createLocation(point, info));
	    		}
	        }
	    );
	}
}

function createSearchMarker(point, address) {
	var marker = new GMarker(point);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml("<strong>U heeft gezocht op:</strong><br />" + address);
	});
	return marker;
}

function createLocation(point, info) {
	var efeIcon = new GIcon(G_DEFAULT_ICON);
	efeIcon.image = "/images/efe-logo.png";
	efeIcon.iconSize = new GSize(36, 36);
	
	markerOptions = { icon:efeIcon };
	
	var marker = new GMarker(point, markerOptions);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(info);		
	});
	return marker;
}
