/*
 * GMapLib.js, version 0.1
 * A GoogleMaps API (v2) wrapper
 * the purpose of this library is to serve as a reusable set of GoogleMap objects
 * for viewing and creating GPX-files.
 *
 * the basic idea is to import an .gpx file and to display the tracks as polylines and waypoints as markers.  
 *
 * Revision history: 
var version_GMapLib = "0.1  - 29 juli 2006 : Initial version";
var version_GMapLib = "0.2.33  - 01 august 2006 : with routePoint and MapTrack"
var version_GMapLib = "0.3.23  - 16 august 2006 : with speedfunction and output
var version_GMapLib = "0.8  - 17 august 2006 : not everything that I want but it's working!";
var version_GMapLib = "0.81.16  - 27 august 2006 : myFlickrPhoto added"
var version_GMapLib = "0.82.08  - 20 sept 2006 : windowsize added"
var version_GMapLib = "0.83.14  - 23 okt 2006 : routeinfo added";
var version_GMapLib = "0.84.02  - 24 okt 2006 : icons added";
var version_GMapLib = "0.85.01  - 18-03-2007 : waypoints + website";
var version_GMapLib = "0.85.02  - 12-08-2007 : weergavefouten in waypoints opgelost";*/
var version_GMapLib = "0.86.01  - 23-03-2008 : showKML toegevoegd";

/* * Copyright (C) 2006 Michel Duijvestijn (m.d.m.duijvestijn@hro.nl)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

// these functions are needed in the get-directions sections inside the Google Maps object 
// I cannot get them working inside that object
		var gmarkers = [];
		var htmls = [];
		var routePnt = 0;
		// arrays to hold variants of the info window html with get direction forms open
		var to_htmls = [];
		var from_htmls = [];
	
	

	function writeDebug(debugText)  {
	/*	with this function a log message can be written with help of the build in GLog-function
		it requires a 'debug' var to be set true or false at the beginning of the application */
	
		if (debug == true) {
			GLog.write(debugText);
		}
	}
	
	function myWindow()	{
	/*	represents the DOM window element 
		it is presently used to determine the aize of the window 
		code obtained from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow*/
		this.height = 0;
		this.width = 0;
		this.obtainSize = obtainSize;
		
		function obtainSize() {
			if( typeof( window.innerWidth ) == 'number' ) {
    		//Non-IE
    			this.width = window.innerWidth;
    			this.height = window.innerHeight;
  			} else if( document.documentElement && 
				 	( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
    			this.width = document.documentElement.clientWidth;
				this.height = document.documentElement.clientHeight;
			} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    		//IE 4 compatible
				this.width = document.body.clientWidth;
				this.height = document.body.clientHeight;
  			}
		}
	}
	
	function gpxFile(xmlDoc) {
	/*	This object represents the gpx-file to be imported
	  	You can access its tracks, metadata and waypoints
	  	and you can detach the geographical bounds of the region and its center*/
		this.xmlDoc = xmlDoc; //the imported xml-data
		this.getBounds = getBounds; //function to determine the bounds contained in the file
		this.getCenter = getCenter; //function to calculate the center
		
		this.metadata = this.xmlDoc.documentElement.getElementsByTagName("metadata");
		this.gpsTrks = this.xmlDoc.documentElement.getElementsByTagName("trk"); //the complete track
		this.gpsWaypnts = this.xmlDoc.documentElement.getElementsByTagName("wpt"); //the complete set of waypoints
		
		function getBounds() {
		/*	The .gpx file should have an 'bounds' section in which the geographical rectangle what should be 
			displayed is defined.*/
			var bounds = this.metadata[0].getElementsByTagName("bounds");
			var geoMax = new GLatLng(bounds[0].getAttribute("maxlat"),bounds[0].getAttribute("maxlon"));
			var geoMin = new GLatLng(bounds[0].getAttribute("minlat"),bounds[0].getAttribute("minlon"));
			gpxBounds = new GLatLngBounds(geoMin,geoMax)
			return gpxBounds;
		}
		
		function getCenter () {
		/*	as I cannot find a Google function to find the center of a GLatLngBounds rectangle
			I have to do it this way */
			var bounds = this.metadata[0].getElementsByTagName("bounds");
			centerLon = (parseFloat(bounds[0].getAttribute("maxlon"))+parseFloat(bounds[0].getAttribute("minlon")))/2;
			centerLat = (parseFloat(bounds[0].getAttribute("maxlat"))+parseFloat(bounds[0].getAttribute("minlat")))/2;
			gpxCenter = new GLatLng(centerLat, centerLon);
			return gpxCenter;
		}
		
	}
	
	function gpxTracks(gpsTrks) {
	/* 	this object represents the collection of tracks that are present in the GPX file */
		this.gpsTrks = gpsTrks;
		this.printOut = printOut;
		
		function printOut(onMap) {
		//selects the lines
			for (j=0;j < this.gpsTrks.length;j++) {
				trkPts=this.gpsTrks[j].getElementsByTagName("trkpt");  // trkpts is an array of all trackpoints
				plotPoint(onMap,trkPts,j);
			}
		}

		function plotPoint(onMap, trkPts, trkNumber) {
		/*	Draws the polylines from point to point onMap. onMap is the GoogleMap-object that is created before*/
			var myPoints=new Array();
			var tlr=0
			for (i=0;i < trkPts.length;i++) {
				var Lat = trkPts[i].getAttribute("lat");
				var Lng = trkPts[i].getAttribute("lon");
				var ele = trkPts[i].getElementsByTagName("ele")[0].firstChild.nodeValue;
				var time = trkPts[i].getElementsByTagName("time")[0].firstChild.nodeValue;
				var dateObj = new Date(time.substr(0,4),time.substr(5,2)-1,time.substr(8,2),
						time.substr(11,2),time.substr(14,2),time.substr(17,2));
				//writeDebug("punt " + i + ": " + dateObj.toUTCString());
				var pointNw = new GLatLng(Lat, Lng);
				if (i>0) {
					//if distance to previous point < 10 m then skip it
					var dist = pointNw.distanceFrom(pointOud);
					if (dist<1) continue;
				}
				myPoints[tlr] = new routePoint(pointNw,ele,dateObj);
				pointOud = pointNw;
				tlr++;
				//if you try to plot too many points you'll get some kind of timeout.
				if (tlr>100) {
					onMap.plotPoly(myPoints,trkNumber);
					tlr=0;
					myPoints =[];	
				}
     		}
		onMap.plotPoly(myPoints,trkNumber); //display the last bit
		}	
	}
	
	function routePoint(location,ele,time) {
	/*	object representing a geocoded location, with a geographical position (= location),
		an elevation (height above sealevel) and the time the location was (or will be?) visited	*/
		this.location = location; //the GLatLng of the point
		this.ele = ele; //the elevation
		this.time = time; //the time
	}
	
	function photoOnFlickr(photoID, server, secret, location, altitude, timeOfMaking, title, description, tags, sizes) {
	/*	object representing a photo on Flickr with all the relevant information */
		this.photoID=photoID;
		this.server=server;
		this.secret=secret;
		this.location=location;
		this.altitude=altitude;
		this.timeOfMaking=timeOfMaking;
		this.title=title;
		this.description=description;
		this.tags=tags;
		this.sizes=sizes;
	}
	
	function photoArray() {
	/*	object representing the array of pictures that (at first) have to be drawn on the googlemap 
		and (afterwards) should be written to the gpx-files */
		this.AddPhotoToArray = AddPhotoToArray;
		this.DeletePhotoFromArray = DeletePhotoFromArray;
		
		function AddPhotoToArray (photoID,secret) {
			GetPhotoInfo(photoID, secret);
		//	this function adds photo to the photoarray
		}
		function PhotoSize (label,width,height) {
		/*	this object represents a photo-size */
			this.label = label;
			this.width = width;
			this.height = height;
		}
		
		function DeletePhotoFromArray (photoID) {
		//	this function deletes photo from the photoarray
		}
		
		function GetPhotoInfo(photoID,secret) {
		/*	this function invokes an XMLHttpRwquest to obtain the photo-info from Flickr
    	 	branch for native XMLHttpRequest object
		*/
			var url = baseURL + "getPhotoInfo3.php?photoID=" + photoID + "&secret=" + secret;
    		//writeDebug('url =' + url);
			if (window.XMLHttpRequest) {
        		req = new XMLHttpRequest();
        		req.onreadystatechange = processReqChange;
        		req.open("GET", url, true);
        		req.send(null);
    		//	branch for IE/Windows ActiveX version
    		} else if (window.ActiveXObject) {
        		req = new ActiveXObject("Microsoft.XMLHTTP");
        		if (req) {
            		req.onreadystatechange = processReqChange;
            		req.open("GET", url, true);
            		req.send();
        		}
    		}
		}
		
		function processReqChange() {
		/* this function processes the XML-file from GetPhotoInfo */
    	// only if req shows "complete"
  		if (req.readyState == 4) {
        	// only if "OK"
        	if (req.status == 200) {
            	// ...processing statements go here...
      			response  = req.responseXML.documentElement;
				myPhoto = new photoOnFlickr;
				myPhoto.photoID=response.getElementsByTagName('photo')[0].getAttribute('id');
				myPhoto.server=response.getElementsByTagName('photo')[0].getAttribute('server');
				myPhoto.secret=response.getElementsByTagName('photo')[0].getAttribute('secret');
				myPhoto.title=response.getElementsByTagName('title')[0].firstChild.data;
				myPhoto.location=new GLatLng(response.getElementsByTagName('lat')[0].firstChild.data,
							response.getElementsByTagName('lon')[0].firstChild.data);
				myPhoto.altitude=response.getElementsByTagName('alt')[0].firstChild.data;
				myPhoto.timeOfMaking=response.getElementsByTagName('date_taken')[0].firstChild.data;
				
				//description
				myDescription = response.getElementsByTagName('description')[0]
				if ( myDescription.hasChildNodes()) {
					myPhoto.description = myDescription.firstChild.data;
				} else {
					myPhoto.description = "geen omschrijving";
				}

				//tags
				var tagResult = new Array();
				for(x=0;x<response.getElementsByTagName('tag').length;x++) {
					myTag   = response.getElementsByTagName('tag')[x];
					tagResult[x] = myTag.getAttribute('raw');
				}
				myPhoto.tags=tagResult;
				
				//sizes
				var mySizes = new Array();
				for(x=0;x<response.getElementsByTagName('size').length;x++) {
					var mySize = new PhotoSize;
					sizeResult  = response.getElementsByTagName('size')[x];
					mySize.label = sizeResult.getAttribute('label');
					mySize.width = sizeResult.getAttribute('width');
					mySize.height = sizeResult.getAttribute('height');
					mySizes[x] = mySize;
				}
				//writeDebug ('omschrijving is ' + myPhoto.length);
			    for (k=0;k < myPhoto.length;k++) {
					//writeDebug ('res.' + k + ' = ' + myPhoto[k]);
				}
        	} else {
            	alert("There was a problem retrieving the XML-data:\n" + req.statusText);
       		}
    	}
	}


	}
	
	function WayPoints(gpsWaypoints) {
	/*	This object represents the collection of waypoints that are present in the GPX-files
		*/
		this.gpsWaypoints=gpsWaypoints;
		this.generateMarkers=generateMarkers;
		
		function generateMarkers(onMap) {
		/*	Generate an array of markers */
			markers = new Array();
			for (i=0;i < this.gpsWaypoints.length;i++) {
				writeDebug('waypoint nr.' +i);
				var point = new GLatLng(gpsWaypoints[i].getAttribute("lat"),gpsWaypoints[i].getAttribute("lon"));
				var wptNaam = gpsWaypoints[i].getElementsByTagName("name")[0].firstChild.nodeValue;
				//check if there is a comment
				var hasCMT = gpsWaypoints[i].getElementsByTagName("cmt");
				if (hasCMT.length>0) {
					var cmt = gpsWaypoints[i].getElementsByTagName("cmt")[0].firstChild.nodeValue;

				} else {
					var cmt ="waypoint zonder toelichting";
				}
				//check if there is a link
				var hasLink = gpsWaypoints[i].getElementsByTagName("link");
				if (hasLink.length>0) {
					//writeDebug(wptNaam + 'heeft link');
					var wptURL = gpsWaypoints[i].getElementsByTagName("link")[0].getAttribute("href");
					cmt = cmt+';<br /><a href="'+wptURL+'" target="_blank">website</a>';
					//writeDebug("waypoint met link: " + cmt);
				} 
				if (cmt.substr(0,11)=='FlickrPhoto') {
				/*	waypoint is identified as Photo-information. I don't like to use the cmt-tag for this, but this
						is the only tag that is saved when the GPX file is edited by mapsource :( 
						cmt should be build-up as follows: "FlickrPhoto;<Flickr-server>;<flickr-ID>;<flickr-secret>*/
					var photoLink = gpsWaypoints[i].getElementsByTagName("link")[0].getAttribute("href");
					PhotoParams=cmt.split(';');

					info = '<div id="infotitle">'+wptNaam+'</div><div id="infoimg>"';
					info = info+'<a href="'+photoLink+'" ';
					info = info+' title="Click for a full size view" target="_blank">';
					info = info+'<img src="http://static.flickr.com/'+PhotoParams[1]
							+'/'+PhotoParams[2]+'_'+PhotoParams[3]+'_m.jpg" ';
					info = info+' width="160" border="0" height"120" /></a>'+PhotoParams[4]+'</div>';
					writeDebug("info: " + info);
    				//iconID = PhotoParams[1]+'/'+PhotoParams[2]+'_'+PhotoParams[3];
					onMap.showMarker(point,info,'foto');
				} else {
					if (cmt.substr(0,7)=='?route?') {
					/*	waypoint with possibility of routing-info */
						info = '<div id="infotitle">'+wptNaam+'</div>';
						onMap.showMarker(point,info,'route');
					} else {
					/*	every other waypoint */
						info = '<div id="infotitle">'+wptNaam+'</div>';
						info = info+cmt;
						//var iconID = "62/153493829_a489baa8a1";
						onMap.showMarker(point,info,'info');
					}
				}
				//onMap.showMarker(point,info);
			}
		}

	}
	
	function MapTrack () {
	/*	This object represents a track, an array of geographical coordinates
		The difference between a MapTrack object and a GpsTrack object is that in the latter the coordinates 
		are layed down in the form of an XML-file (.gpx) while in the MapTrack object it is an array of GLatLng points.
		Within this object the track can be manipulated, points can be added, distances are calculated, the route 
		can be displayed on the map and finally the track can ben exported as route or track (= back to .gpx-format)
		
		This object is used to manually create a route on a map.
	*/
		this.addPoint = addPoint; //function to add a point to the array
		this.display = display; //display the track
		this.calcTotalDistance = calcTotalDistance;
		this.calcTimeAndSpeed = calcTimeAndSpeed;
		this.exportPoints = exportPoints;
		
		var trackArray = new Array();
		var totalDistance = 0;
				
		function addPoint(point) {
			if (trackArray.length>0) {
				var pointOud = trackArray[trackArray.length-1].location;
				var distance = point.distanceFrom(pointOud)/1000;
				totalDistance = totalDistance + distance;
				distance = distance.toFixed(3)
			}
			myPoint = new routePoint(point);
			trackArray.push(myPoint);
			return distance;
		}
		
		function display(onMap) {
			for (i=0;i < trackArray.length;i++) {
				onMap.showMarker(trackArray[i].location,i)
			}
			onMap.plotPoly(trackArray,0); 
		}
		
	
		function calcTotalDistance() {
			return totalDistance.toFixed(3);
		}
		
		function calcTimeAndSpeed(depTime,arrTime,speed,toCalc) {
			if (toCalc == "speed") {
				var depTimeObj = timeToDateobj(depTime);
				var arrTimeObj = timeToDateobj(arrTime);
				var timeDiff = arrTimeObj.getTime()-depTimeObj.getTime();
				var calcSpeed_ms = totalDistance*1000000/timeDiff;
				setTimeInfo(depTimeObj,calcSpeed_ms);
				return (calcSpeed_ms*3.6).toFixed(2);
			} else {
				var timeDiff = totalDistance*3600000/speed;
				//var result = new Date();
				if (toCalc=="dep") {
					var arrTimeObj = timeToDateobj(arrTime);				
					var depTimeObj = new Date(arrTimeObj.getTime()-timeDiff);
					result = depTimeObj;
				} else {
					var depTimeObj = timeToDateobj(depTime);
					var arrTimeObj = new Date(depTimeObj.getTime()+timeDiff);
					result = arrTimeObj;
				}
				resultArr = new Array(result.getFullYear(),(result.getMonth()+1),result.getDate(),
							result.getHours(),result.getMinutes(),result.getSeconds())
				for (n=1;n < 6;n++) {
					if (resultArr[n]<10) {
						resultArr[n] = "0" + resultArr[n];
					} else {
						resultArr[n] = resultArr[n].toString();
					}
				}
				
				resultStr = resultArr[0] + "-" + resultArr[1] + "-" + resultArr[2] +
							"/" + resultArr[3] + ":" + resultArr[4];
				setTimeInfo(depTimeObj,(speed/3.6));
				return resultStr;
				//(arrTimeObj.getYear() 
			}
		}
		
		//time calculation per point comes here
		function setTimeInfo(startTime,speed) {
			var tlr=1;
			var timeOld = new Date(startTime);
			var timeNew = new Date();
			var pointOld = trackArray[0].location;
			trackArray[0].time = startTime;

			for (tlr=1;tlr < trackArray.length;tlr++) {
				var pointNew = trackArray[tlr].location;

				timeNew.setTime(timeOld.getTime() + (pointNew.distanceFrom(pointOld)/speed)*1000);
				trackArray[tlr].time = new Date(timeNew);
				timeOld = timeNew;
				pointOld = pointNew;
			}	
		}
		
		function exportPoints(format) {
		    var export_string = ''; 
		    if (format=='route') {
				export_string = export_string + "<?xml version=\"1.0\"?>\n<gpx>\n";
				export_string = export_string + "<rte>\n";
		    }
			
	    	if (format=='track') {
				export_string = export_string + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n";
				export_string = export_string + "<gpx xmlns=\"http://www.topografix.com/GPX/1/1\" creator=\"MapSource 6.9.1\" version=\"1.1\"\n";
				export_string = export_string + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n";

	    		export_string = export_string + "<trk>\n<name>Trackgenerator</name>\n<trkseg>\n";
			}
			
	   		if (format=='csv') {
				//csv header
				export_string = export_string + "latitude, longitude\n";
	    	}
    		for (i2 = 0; i2 < trackArray.length; i2++) {
				var lon = trackArray[i2].location.lng();
				var lat = trackArray[i2].location.lat();

				timeArr = new Array(trackArray[i2].time.getFullYear(),(trackArray[i2].time.getMonth()+1),
							trackArray[i2].time.getDate(),
							trackArray[i2].time.getHours(),trackArray[i2].time.getMinutes(),trackArray[i2].time.getSeconds())
				for (n=1;n < 6;n++) {
					if (timeArr[n]<10) {
						timeArr[n] = "0" + timeArr[n];
					} else {
						timeArr[n] = timeArr[n].toString();
					}
				}
				var timeString = '<time>' + timeArr[0] + '-' + timeArr[1] + '-' + timeArr[2] 
					+ 'T' + timeArr[3] + ':' + timeArr[4] + ':' + timeArr[5] + 'Z</time>'; 
				if (format=='route') {
					export_string = export_string + '<rtept lat="' + lat + '" lon="' + lon + '"> <name>pt_' + i + "</name></rtept>\n";
				}
				
				if (format=='track') {
					export_string = export_string + '<trkpt lat="' + lat + '" lon="' + lon + '">' + timeString + '</trkpt>\n';
				}
				
				if (format=='csv') {
					export_string = export_string +  lat + ", " + lon + "\n";
				}
	    	}

		    // footers
		   	if (format=='route') {
				export_string = export_string + "</rte></gpx>";
	    	}
				
	    	if (format=='track') {
				export_string = export_string + "</trkseg>\n</trk>\n</gpx>";
	    	}
		    // write into document    
	  		//document.getElementById("output").value=export_string;
			return export_string;
		}

		function timeToDateobj(timeString) {
			var dateTime = timeString.split("/");
			var myDate = dateTime[0].split("-");
			var myTime = dateTime[1].split(":");
			var dateObj = new Date(myDate[0],myDate[1]-1,myDate[2],myTime[0],myTime[1],00);
			return dateObj;
		}
	}
	
	function GoogleMap (mapDiv,onMapclickDo,onMapMoveEndDo) {
	/*	This object represents a GoogleMap that is to be drawn onto the website
		You can draw the map itself, draw lines on it, set markers etc.*/
		this.mapDiv = mapDiv; //the div in which the map is to be placed
		this.onMapclickDo = onMapclickDo; //the function that has to be called when the map is clicked
		this.onMapMoveEndDo = onMapMoveEndDo;//the function that has to be called when the map is dragged or rezoomed
		this.DisPlay = DisPlay;
		this.DisPlayBox = DisPlayBox;
		this.showKML = showKML;
		this.GenerateControls = GenerateControls;
		this.getZoomLevel = getZoomLevel;
		this.plotPoly = plotPoly;
		this.showMarker = showMarker;
		//this.tohere = tohere;
		//this.fromhere = fromhere;
	
		// arrays to hold copies of the markers and html used by the get directions info window
		// because the function closure trick doesnt work there
		
		var map = new GMap2(document.getElementById(mapDiv), {draggableCursor: 'crosshair', draggingCursor: 'pointer'});
		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
		// this section doesn't work properly yet :(
		
		var baseIcon = new GIcon();
		baseIcon.shadow = "shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);

		/*var baseIcon = new GIcon();
		baseIcon.shadow = "../_IMG/background.png";
		baseIcon.iconSize = new GSize(50, 50);
		baseIcon.shadowSize = new GSize(90, 60);
		baseIcon.iconAnchor = new GPoint(0, 55);
		baseIcon.infoWindowAnchor = new GPoint(0, 0);
		baseIcon.infoShadowAnchor = new GPoint(30, 10);*/
		
		GEvent.addListener(map, 'click', 
			function(overlay, point) {
		    	if (point) {
					//i cannot stand the ridiculous accuracy in geocoding that is returned
					//therefore I make my own point
					var nwPoint = new GLatLng(point.lat().toFixed(5),point.lng().toFixed(5));
					eval(onMapclickDo + "(overlay,nwPoint)");
		    	} 
			}
	    );   // end of GEvent.addListener

		GEvent.addListener(map, 'moveend', 
			function() {
				if (!onMapMoveEndDo=='') {
					var center = map.getCenter();
					eval(onMapMoveEndDo + "(" + center.lat().toFixed(5) + ',' + center.lng().toFixed(5) + ',' + 
							map.getZoom() + ")");
				}
			}
	    );   // end of GEvent.addListener


		function GenerateControls() {
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			map.addControl(new GScaleControl());
			//the next line needs to have an map allready showing. if not put here however it gives not the correct maptype
			map.addControl(new GOverviewMapControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10, 10)));
			map.enableDoubleClickZoom(); //doubleclick is zooming in
		}
		
		function DisPlay(centerPos,Zoom,MapType) {
			myCenterLat = centerPos.lat();
			if (!MapType) {
				MapType = "G_SATELLITE_MAP";
			} else {
				MapType = "G_" + MapType.toUpperCase() + "_MAP"}
			map.setCenter(centerPos, Zoom,eval(MapType));
			//next line has to be here because first a map center should be known.
		//var ovControl = new GOverviewMapControl();
		// ======== get a reference to the GMap2 ===========
      	//var ovMap = ovControl.getOverviewMap();
			//map.addControl(ovControl,new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10, 10))); 
      		//  ======== change the overview map type AFTER the overview finisges initializing =====
			// Source: http://www.econym.demon.co.uk/googlemaps/basic13.htm
      		//setTimeout("ovMap.setMapType(G_SATELLITE_MAP);",1);		
		}

		function DisPlayBox(bounds,MapType) {
												  
			if (!MapType) {
				MapType = "G_SATELLITE_MAP";
			} else {
				MapType = "G_" + MapType.toUpperCase() + "_MAP";
			}
			//altijd eerst basiskaart tekenen
			map.setCenter(new GLatLng(0,0), 2,eval(MapType));
			//dan grenzen bepalen
			map.setCenter(bounds.getCenter());
			map.setZoom(map.getBoundsZoomLevel(bounds));
		}

		function showKML(kmlNaam) {
			var geoXml = new GGeoXml(kmlNaam);
			map.addOverlay(geoXml);
		}
		
		function getZoomLevel(bounds) {
			var Zoomlevel = map.getBoundsZoomLevel(bounds);
			return Zoomlevel;
		}
		
		function plotPoly (Points,trkNumber) {
			var colors = new Array("#FF0000","#00FF00","#FFFF00","#00FFFF","#FF00FF")
			var plotPoints = new Array();
			color=colors[trkNumber%colors.length];
			//Points consist of an array with location, elevation and time. We only need the location
			for (k=0;k < Points.length;k++) {
				plotPoints[k] = Points[k].location;
			}
			map.addOverlay(new GPolyline(plotPoints, color, 2, 0.75));
		}
		
		function showMarker(point,info,icon) {
			//var icon = new GIcon(baseIcon);
  			//icon.image = "http://static.flickr.com/"+iconID+"_s.jpg";
			//var marker = new GMarker(point);
			var myIcon = new GIcon(baseIcon);
			if (icon=='route'){
			//	The info window version with the "to here" form open
				myIcon.image = "./marker_route.png";
				to_htmls[routePnt] = '<div id="infotitle">Routebeschrijving:</div><br /><b>Naar hier</b> - <a href="javascript:fromhere(' + routePnt + ')">vanaf hier</a>' +
			 		'<br />Adres vertrekpunt:<br />vul in: straatnaam + woonplaats <br /> of nl+spatie+cijfers postcode (nl 3063)<form action="http://maps.google.nl/maps" method="get" target="_blank">' +
			 		'<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
			 		'<INPUT value="Geef routebeschrijving" TYPE="SUBMIT">' +
			 		'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
			 		//"(" + info + ")" + 
			 		'"/>';
					// The info window version with the "to here" form open
				from_htmls[routePnt] =  '<div id="infotitle">Routebeschrijving:</div><br /><a href="javascript:tohere(' + routePnt + ')">vanaf hier</a> - <b>naar hier</b>' +
			 		'<br />Adres bestemming:<br />vul in: straatnaam + woonplaats <br /> of nl+spatie+cijfers postcode (nl 3063)<form action="http://maps.google.nl/maps" method="get"" target="_blank">' +
			 		'<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
			 		'<INPUT value="Geef routebeschrijving" TYPE="SUBMIT">' +
			 		'<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
			 		//"(" + info + ")" + 
			 		'"/>';
			// The inactive version of the direction info
				info = '<div id="infotitle">Routebeschrijving:</div><br /><a href="javascript:tohere('+i+')">Naar hier</a> - <a href="javascript:fromhere('+routePnt+')">vanaf hier</a>';
			} else {
				if (icon=='foto') {
					myIcon.image = "./marker_foto.png";
				} else {
					myIcon.image = "./marker_info.png";
				}
			}
			var marker = new GMarker(point,myIcon);
			writeDebug("marker # " + routePnt + " at: " + point + " met info: " + info);
			
			GEvent.addListener(marker, "click", function() {
          		marker.openInfoWindowHtml(info);
       		});
			// save the info we need to use later for the side_bar
        	gmarkers[routePnt] = marker;
        	htmls[routePnt] = info;
			routePnt++;

			map.addOverlay(marker);
		}
		
		/*function fromhere(i) {
			gmarkers[i].openInfoWindowHtml(from_htmls[i]);
		}*/

	}
		// functions that open the directions forms
		// I can't get these functions working inside the Google Maps object
		function tohere(routePnt) {
			gmarkers[routePnt].openInfoWindowHtml(to_htmls[routePnt]);
		}
		function fromhere(routePnt) {
			gmarkers[routePnt].openInfoWindowHtml(from_htmls[routePnt]);
		}	

