/**
 * @author Theo Bakker, WHELP.nl
 * @title 31
 */

//load Google Map
function load() {
  if (GBrowserIsCompatible()) {
    var delay = 200; // Delay inbetween geocoding the addresses, the faster the better, but faster might break the code (google only allows a number of geocoding actions per second
  	var map = new GMap2(document.getElementById("map"));
	var geocoder = new GClientGeocoder();
	//geocoder.setBaseCountryCode("NL");
	map.setCenter(new GLatLng(52.43878, 6.50164), 8);
	
	//add controls
    map.addControl(new GMapTypeControl());
	map.addControl(new GLargeMapControl()); 

	//create randomnumber to prevent caching and retrieve xml file
	var randomnumber=Math.floor(Math.random()*11111)
    GDownloadUrl("http://www.hulpaanhuis.nl/address.php?random="+randomnumber, function(data, responseCode) {
    var xml = GXml.parse(data);

	//store markers in markers array
    var markers = xml.documentElement.getElementsByTagName("marker");

	// create marker icon

	// create marker icon
	var icon = new GIcon();
	icon.image = "http://www.hulpaanhuis.nl/skins/default/files/js/mapstip.png";
	icon.iconSize = new GSize(24, 23);
	icon.iconAnchor = new GPoint(0, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);

	// Adds the address blobs to the map
	function showNextAddress( index ) {
		if( index < markers.length ) {
			var address = markers[index].getAttribute("address");
			var html = GXml.value(markers[index].getElementsByTagName("infowindow")[0]);
			
			setTimeout( function() {
				showAddress( map, geocoder, address, html, icon, index )
			}, delay ); // Add the next address with a delay, because of Google API throttling
		}
	}
	
	//showAddress
	function showAddress(map,geocoder,address,html,icon,index) {
	  geocoder.getLatLng(
		address,
		function(point) {
		  if (!point) {
			alert(address + " niet gevonden");
		  } else {
			//var marker = createMarker(point,html+'<br/><br/>'+address,icon);
			var marker = createMarker(point,html,icon);
			map.addOverlay(marker);
			map.addControl(new GMapTypeControl());
		  }
		}
	  );
	  
	  index++;
	  showNextAddress( index );
	}
	
	// Start Geocoding the addresses
	showNextAddress( 0 );

	  }
	); //close GDownloadUrl

//Create marker and set up event window
function createMarker(point,html,icon){
  var marker = new GMarker(point,icon);
  GEvent.addListener(marker, "click", function() {
     marker.openInfoWindowHtml(html);
  });
  return marker;
}


  } //close GBrowserIsCompatible
} //close load
