function onLoad() {
  map = new GMap2(document.getElementById("map")); 

  map.setCenter(new GLatLng(52.069377, 5.366821), 8);
  map.addControl(new GSmallMapControl());
  map.disableDoubleClickZoom();
  map.enableScrollWheelZoom();
     
  geocoder = new GClientGeocoder();
  // Create the virtual car marker, add it to the map, and then reset the map
  currentLocation = createCarMarker(startPoint);
  map.addOverlay(currentLocation);
  resetMap();
 
  // Retrieve the data from masseursbestand
  getJSON();
  
  // genereer route
  initialize();
} 



function addTR(id) {
  var layerTR = document.createElement("div");
  layerTR.id = "mydiv";
  var nameTD = document.createElement("div");
  nameTD.id = "floatleft";
  var nameA = document.createElement("a");
  nameA.href = "#"; 
  nameA.onclick = function () { zoomToProvincie(layers[id].name); }; 
  var name = document.createTextNode(layers[id].name);
  nameA.appendChild(name);
  nameTD.appendChild(nameA);
  
  /*
  var maskTD = document.createElement("div");
  maskTD.id = "floatright";
  var mask = document.createElement("input");
  mask.type = "checkbox";
  mask.id = id;
  mask.onclick = function () { toggleGeoXML2(this.id, this.checked); };
  maskTD.appendChild(mask);
  */
  
  layerTR.appendChild(nameTD);
  /*layerTR.appendChild(maskTD);*/
  document.getElementById("sidebarTBODY").appendChild(layerTR);
}

function zoomToGeoXML(geoXml) {
  
  var center = geoXml.getDefaultCenter();
  var span = geoXml.getDefaultSpan();
  var sw = new GLatLng(center.lat() - span.lat() / 2,
                       center.lng() - span.lng() / 2);
  var ne = new GLatLng(center.lat() + span.lat() / 2,
                       center.lng() + span.lng() / 2);
  var bounds = new GLatLngBounds(sw, ne);
  map.setCenter(center);
  map.setZoom(map.getBoundsZoomLevel(bounds));
  
}

function toggleGeoXML2(id, checked) {
  if (checked) {
    var geoXmlmap = new GGeoXml(layers[id].urlmap);
    GEvent.addListener(geoXmlmap, 'load', function() {
      if (geoXmlmap.loadedCorrectly()) {
        geoXmlmap.gotoDefaultViewport(map);
        layers[id].geoXmlmap = geoXmlmap;
        document.getElementById("status").innerHTML = "";
      }
    });
    layers[id].geoXmlmap = geoXmlmap;
    map.addOverlay(layers[id].geoXmlmap);
    document.getElementById("status").innerHTML = "Loading Kaart Informatie...";
  
  } else if (layers[id].geoXmlmap) {
    map.removeOverlay(layers[id].geoXmlmap);
  }
}


// NIEUWE SCRIPT VOOR ZOEKEN

function resetMap()
{
// Pan the map back to the original start location
map.panTo(startPoint, 15);
// Set the virtual car location back to the start location
currentLocation.setLatLng(startPoint);
// Set the polygon radius and direction based upon user selection
radiusInMiles = document.getElementById('radius').options[document.getElementById('radius').selectedIndex].value;
direction = document.getElementById('direction').options[document.getElementById('direction').selectedIndex].value;
// Enable the "Start" button, and check the auto-move option
document.getElementById("startButton").disabled = false;
document.getElementById("autoMove").checked = true;
// Redraw the polygon around the car
redrawPoly();
}
/*
* Function to create the car marker, returning a GMarker object.
* @param {GLatLng} latlng - the location object defining where to create the GMarker
* @returns GMarker for the virtual car
*/
function createCarMarker(latlng)
{
// create a custom "car" icon from an image, setting the size and other attributes
var func_icon = new GIcon();
func_icon.image = "http://maps.google.com/mapfiles/kml/pal4/icon62.png";
func_icon.iconSize = new GSize(40, 40);
func_icon.shadowSize = new GSize(30, 30);
func_icon.iconAnchor = new GPoint(20, 20);
func_icon.infoWindowAnchor = new GPoint(5, 1);
var func_markerOpts = {};
func_markerOpts.icon = func_icon;
// allow the marker to be moved around
func_markerOpts.draggable = true;
// create the GMarker object with the specified options
var func_marker = new GMarker(latlng, func_markerOpts);
// capture marker drag events
GEvent.addListener(func_marker, "dragstart", function() {
  pointBeingMoved = func_marker.getLatLng().lat() + ';' + func_marker.getLatLng().lng();
});
GEvent.addListener(func_marker, "dragend", function() {
  currentLocation = func_marker;
  // redraw the polygon surrounding the marker when the user stops dragging the marker around
  redrawPoly();
});
// other events to listen for, if desired
GEvent.addListener(func_marker, "click", function() {
});
GEvent.addListener(func_marker, "dblclick", function() {
});
return func_marker;
}
/*
* Function to redraw the polygon surrounding the car icon.
* Polygon is essentially an octagon shape, but could include more points for a
* more circular-looking shape.
*/
function redrawPoly()
{
// Since we're redrawing the polygon, let's remove it first from the map.
// For a smoother transition, this could be enhanced to slowly fade the old polygon while fading in the new one.
if (polygon)
{
  map.removeOverlay(polygon);
}
// Create the eight points of the polygon, using the current "radius"
var func_points = new Array(9);
var func_newLat = currentLocation.getLatLng().lat() + radiusInMiles/milesPerLat;
var func_newLng = currentLocation.getLatLng().lng() - ((0.50 * radiusInMiles)/milesPerLng);
func_points.push(new GLatLng(func_newLat, func_newLng));
func_newLat = currentLocation.getLatLng().lat() + (0.50*radiusInMiles)/milesPerLat;
func_newLng = currentLocation.getLatLng().lng() - (radiusInMiles/milesPerLng);
func_points.push(new GLatLng(func_newLat, func_newLng));
func_newLat = currentLocation.getLatLng().lat() - (0.50*radiusInMiles)/milesPerLat;
func_newLng = currentLocation.getLatLng().lng() - (radiusInMiles/milesPerLng);
func_points.push(new GLatLng(func_newLat, func_newLng));
func_newLat = currentLocation.getLatLng().lat() - radiusInMiles/milesPerLat;
func_newLng = currentLocation.getLatLng().lng() - (0.50*radiusInMiles/milesPerLng);
func_points.push(new GLatLng(func_newLat, func_newLng));
func_newLat = currentLocation.getLatLng().lat() - radiusInMiles/milesPerLat;
func_newLng = currentLocation.getLatLng().lng() + (0.50*radiusInMiles/milesPerLng);
func_points.push(new GLatLng(func_newLat, func_newLng));
func_newLat = currentLocation.getLatLng().lat() - (0.50*radiusInMiles)/milesPerLat;
func_newLng = currentLocation.getLatLng().lng() + (radiusInMiles/milesPerLng);
func_points.push(new GLatLng(func_newLat, func_newLng));
func_newLat = currentLocation.getLatLng().lat() + (0.50*radiusInMiles)/milesPerLat;
func_newLng = currentLocation.getLatLng().lng() + (radiusInMiles/milesPerLng);
func_points.push(new GLatLng(func_newLat, func_newLng));
func_newLat = currentLocation.getLatLng().lat() + radiusInMiles/milesPerLat;
func_newLng = currentLocation.getLatLng().lng() + (0.50*radiusInMiles/milesPerLng);
func_points.push(new GLatLng(func_newLat, func_newLng));
func_newLat = currentLocation.getLatLng().lat() + radiusInMiles/milesPerLat;
func_newLng = currentLocation.getLatLng().lng() - ((0.50 * radiusInMiles)/milesPerLng);
func_points.push(new GLatLng(func_newLat, func_newLng));
// create the polygon with a transparency level that allows viewing the map underneath
polygon = new GPolygon(func_points, "#f33f00", 1, 1, "#ff0000", 0.2);
// add the polygon to the map
map.addOverlay(polygon);
// finally, check the array of (store) locations to determine if any are now within the bounds of the polygon.
checkPoints();
}

/*
* Function that is called whenever the user changes the radius of the polygon surrounding the car, effectively
* changing the search area around the car for interesting points of interest - the redraws the surrounding polygon.
*/
function changeRadius()
{
radiusInMiles = document.getElementById('radius').options[document.getElementById('radius').selectedIndex].value;
if (currentLocation)
  redrawPoly();
}
/*
* Function that is called when the user changes the direction that the virtual car should travel.
*/
function changeDirection()
{
direction = document.getElementById('direction').options[document.getElementById('direction').selectedIndex].value;
}
/*
* Extension to the GPolygon object.
* This is a method for testing if a point is inside a polygon
* The origins of this function can be traced to the code posted at http://alienryderflex.com/polygon/
* @param {GLatLng} point - the point of interest
* @returns boolean - true if poly contains point
*/
GPolygon.prototype.Contains = function(point) {
var j=0;
var func_oddNodes = false;
var x = point.lng();
var y = point.lat();
for (var i=0; i < this.getVertexCount(); i++) {
  j++;
  if (j == this.getVertexCount()) {j = 0;}
  if (((this.getVertex(i).lat() < y) && (this.getVertex(j).lat() >= y))
  || ((this.getVertex(j).lat() < y) && (this.getVertex(i).lat() >= y))) {
	if ( this.getVertex(i).lng() + (y - this.getVertex(i).lat())
	/  (this.getVertex(j).lat()-this.getVertex(i).lat())
	*  (this.getVertex(j).lng() - this.getVertex(i).lng())<x ) {
	  func_oddNodes = !func_oddNodes
	}
  }
}
return func_oddNodes;
}

/*
* Function to retrieve data from a Google Spreadsheet, published as a JSON feed.
*/
function getJSON() {
// Create and insert a <script/> element in the document, where the source of the
//  script is the feed from the Google Spreadsheet with a defined call-back function.
var script = document.createElement('script');
script.setAttribute('src', 'http://www.jobmassage.nl/ADMIN/ADMIN/masseursMap/values.json.php');
script.setAttribute('src', 'http://masseurs.jobmassage.net/data/values.json.php');
script.setAttribute('id', 'jsonScript');
script.setAttribute('type', 'text/javascript');
script.setAttribute('charset', 'iso-8859-1');
document.documentElement.firstChild.appendChild(script);
}

/*
* Function called when the Google Spreadsheet data has been returned to the browser.
* @param {String} json - the JavaScript Object Notation string containing data retrieved from the
*  Google Spreadsheet.
*/




/**
 * Function called when marker on the map is clicked.
 * Opens an info window (bubble) above the marker.
 * @param {Number} markerNum Number of marker in global array
 */
function cm_markerClicked(markerNum) {
  markerArray[markerNum].openInfoWindowHtml(cm_mapHTMLS[markerNum], {maxWidth:400});
  markerArray[markerNum].setImage('http://maps.google.com/mapfiles/kml/pal2/icon23.png');
  //showInfoInWindow(nummerToUserid[markerNum]);
}

/* Function showInfoInwindow called when marker is clicked or sidebar item clicked
 * gets information from Ajax file
 */
function showInfoInWindow(markerNum) {	
	// get ajaxCall and put it in infoCanvas
	ajaxpage(rootdomain+'/ADMIN/ADMIN/ajax/masseursInfo.php?id='+markerNum, 'infoCanvas');
	document.getElementById('map9').innerHTML="Toon masseur informatie"; 
} 
 
function clearInfoInWindow() {	
	// get ajaxCall and put it in infoCanvas
	document.getElementById('infoCanvas').innerHTML=""; 
} 


/*
* Function that creates a GMarker object for the location of interest, using a custom icon
* @param {GLatLng} point - place to create the marker
* @param {String} storeNum - HTML string containing a "store number" (i.e. for a retail location)
* @param {String} html - HTML string containing descriptive content for the InfoWindow
* @returns GMarker for the location
*/
function createStoreMarker(point, storeNum, html, i)
{
var func_icon = new GIcon();
func_icon.image = "http://maps.google.com/mapfiles/kml/pal2/icon31.png";
func_icon.iconSize = new GSize(30, 30);
func_icon.shadowSize = new GSize(41, 30);
func_icon.iconAnchor = new GPoint(6, 20);
func_icon.infoWindowAnchor = new GPoint(15, 1);
var func_markerOpts = {};
func_markerOpts.icon = func_icon;
func_markerOpts.title = storeNum;
var func_marker = new GMarker(point, func_markerOpts);

// extra ingevoerd
GEvent.addListener(func_marker, "click", function() {
	func_marker.setImage('http://maps.google.com/mapfiles/kml/pal2/icon23.png');
	func_marker.openInfoWindowHtml(html, {maxWidth:400});
	//showInfoInWindow(nummerToUserid[i]);
});
/*
GEvent.addListener(func_marker, "mouseover", function() {
	func_marker.setImage('http://gmaps-samples.googlecode.com/svn/trunk/markers/circular/yellowcirclemarker.png');
});

GEvent.addListener(func_marker, "mouseout", function() {
	func_marker.setImage('http://maps.google.com/mapfiles/kml/pal2/icon14.png');
});
*/
GEvent.addListener(func_marker, "infowindowclose", function() {
	func_marker.setImage('http://maps.google.com/mapfiles/kml/pal2/icon31.png');
	//clearInfoInWindow();
});
//einde extra ingevoerd
return func_marker;
}

/*
* Function to check all locations/stores of interest to determine if any fall within the polygon surrounding the virtual car
*/
function checkPoints()
{
// If there are no points in the array, just return
if (!markerArray || markerArray.length == 0)
  return;
// Iterate over the location/store array to see if any are within the current polygon area, and show/hide accordingly.
for (n=0 ; n < markerArray.length ; n++ )
{
  if (polygon.Contains(markerArray[n].getLatLng()))
  {
	markerArray[n].show();
	// show sitebar entry
	var testing = document.getElementById("markerDivA_"+n);
	testing.style.display = 'block';	
  }
  else
  {
	markerArray[n].hide();
	// hide sitebar entry
	var testing = document.getElementById("markerDivA_"+n);
	testing.style.display = 'none';
  }
}
}
/*
* Function called on a timer, or manually, to move the location of the virtual car
*/
function moveLocation()
{
// Return immediately if the virtual car isn't already drawn on the map
if (!currentLocation)
  return;
// calculate the lat/lng distance to travel
var func_latDist = deltaDistance/milesPerLat;
var func_lngDist = deltaDistance/milesPerLng;
var func_newLat = currentLocation.getLatLng().lat();
var func_newLng = currentLocation.getLatLng().lng();
// determine the direction to travel, and set the new lat/lng accordingly
if (direction == "NW")
{
  func_newLat = func_newLat + func_latDist;
  func_newLng = func_newLng - func_lngDist;
}
else if (direction == "N")
{
  func_newLat = func_newLat + func_latDist;
}
else if (direction == "NE")
{
  func_newLat = func_newLat + func_latDist;
  func_newLng = func_newLng + func_lngDist;
}
else if (direction == "E")
{
  func_newLng = func_newLng + func_lngDist;
}
else if (direction == "SE")
{
  func_newLat = func_newLat - func_latDist;
  func_newLng = func_newLng + func_lngDist;
}
else if (direction == "S")
{
  func_newLat = func_newLat - func_latDist;
}
else if (direction == "SW")
{
  func_newLat = func_newLat - func_latDist;
  func_newLng = func_newLng - func_lngDist;
}
else if (direction == "W")
{
  func_newLng = func_newLng - func_lngDist;
}
// move the current virtual car GMarker
currentLocation.setLatLng(new GLatLng(func_newLat, func_newLng));
// redraw the polygon surrounding the virtual car
redrawPoly();
checkBounds();
// if the user has chosen the option to have the car move automatically, set up a Javascript timer to 
//  have it move within a defined number of seconds.
if (document.getElementById("autoMove").checked)
{
  document.getElementById("startButton").disabled = true;
  motionTimer = setTimeout('moveLocation()', timeStepSecs*1000);
}
}
/*
* Function to pan the map if the polygon has moved outside of the bounds, and pans the map
* to where the current location is centered on the map.
*/
function checkBounds()
{
 var polyBounds = polygon.getBounds();
 if (!map.getBounds().containsBounds(polyBounds))
 {
	map.panTo(currentLocation.getLatLng());
 }
}

	function showAddress() {
	  var address = document.getElementById("addressTEXT").value;
	  geocoder.getLatLng(
		address,
		function(latlng) {
		  if (!latlng) {
			alert(address + " niet gevonden");
		  } else {
			map.setCenter(latlng, 11);
		  }
		}
	  );
	}
	
	function goToAddress(add) {
	  if (add == 0){
	  	var address = document.getElementById("addressTEXT").value;
	  }else{
	  	var address = add;
	  }
	  geocoder.getLatLng(
		address,
		function(latlng) {
		  if (!latlng) {
			alert(address + " niet gevonden");
		  } else {
			// Pan the map back to the original start location
			map.panTo(latlng, 15);
			// Set the virtual car location back to the start location
			currentLocation.setLatLng(latlng);
			// Set the polygon radius and direction based upon user selection
			radiusInMiles = document.getElementById('radius').options[document.getElementById('radius').selectedIndex].value;
			direction = document.getElementById('direction').options[document.getElementById('direction').selectedIndex].value;
			// Redraw the polygon around the car
			redrawPoly();
		  }
		}
	  );
	}
	
	
	function initialize() {
      if (GBrowserIsCompatible()) {      
        //map = new GMap2(document.getElementById("map"));
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "addoverlay", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

        //setDirections("de linde 2 Hellevoetsluis", "M.A. de Ruyterstraat 30 Utrecht", "nl_NL");
		
		toggleMinMaxZoekMasseur();
      }
    }
    
    function setDirections(fromAddress, toAddress, locale) {
      toggleDetails('show');
	  gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }
	
	function clearRoute() {
		toggleDetails('hide');
		gdir.clear();
	}

    function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("Er kan geen goede geografische plaats worden bepaald voor een van de adressen. Dit kan komen door dat het adres relatief nieuw is of dat het een foutief gespeld adres is.\nError code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
     alert("Aan het verzoek kan niet worden voldaan, de exacte reden is onbekend.\n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
     alert("Er is een script fout!. \n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
     alert("Het antwoord op uw verzoek kan niet correct vertaald worden.\n Error code: " + gdir.getStatus().code);
   else alert("Oeps een onbekende fout!");
    }

  function onGDirectionsLoad(){ 
   //var poly = gdir.getPolyline(); 
  }
	
  function toggleDetails(override){
  	var details = document.getElementById("sidebar2"); 
	
	if(override == 'show'){
		details.style.display = 'block';
	}else if(override == 'hide'){
		details.style.display = 'none';
	}
	
  }
  
      
  function showHelpTekst(toggle){
 	if(toggle == 'aan'){
		var elem = document.getElementById('sidebar4');
		elem.style.display = 'block';
	}
	if(toggle == 'uit'){
		var elem = document.getElementById('sidebar4');
		elem.style.display = 'none';
	}	    
  }
  
  function reisVan(add){
	var elem = document.getElementById('fromAddress');
	elem.value = add;
	
  }
	
	function reisNaar(add){
	var elem = document.getElementById('toAddress');
	elem.value = add;
  }		  
