function initRoute() {
obj =  { "id": null,
											"description": "",
											"underground": "",
											"distance": 0,
											"elevation": 0,
											"postalcode": "",
											"region": "",
											"placename": "",
											"countrycode": "",
											"rank": 0,
											"rank_counter": 0,
											"fk_photo_id": 0,
											"route": "",
											"private": "N",
											"waypoints" : [],
											"fk_client_id": 0,
											"author_name" : "",
											"avg_altitude": 0
										};
	return obj;
}

function initWaypoint() {
  obj =  {
					"id":null,
					"idx":0,
					"comment":"",
					"fk_photo_id":0,
					"latitude":0,
					"longitude":0,
					"gtopo30" : 0
			};
	return obj;
}

function setInner(id,strTo, ttl) {
	if ($(id)) {
	$(id).innerHTML = strTo;
	if (ttl > 0) {
				setTimeout('clearInner(\"'+id+'\")',ttl);
	}
	}
	else {
				alert(id);
		}
}

function clearInner(id,strTo) {
	$(id).innerHTML = '';
	$(id).style.display= 'none';
}

function minimizeFooter() {
	$('footer').style.display = 'none';
}

function toggleView () {
			if (rrMAPVIEW == SMALL) {
							$('toggleViewLink').src = '../themes/asics20/media/routes/icon_minimize.gif';
							rrMAPVIEW = WIDE;
			}
			else {
							$('toggleViewLink').src = '../themes/asics20/media/routes/icon_maximize.gif';
							rrMAPVIEW = SMALL;
			}

			resizeMap();
}

function act_myRoutes(type) {
			
			rrMODUS = MY;
			rrROUTEVIEW  = OVERVIEW;

			recording = false;
			calc.hideCalculatorDiv_();

			globalFilter.type = 'fk_client_id';
			if (type=='fav') 
				globalFilter.waarde = 'myFavourites';
			else
				globalFilter.waarde = 'myRoutes';

			doAjaxZoek();

			$('zoekFrm').innerHTML = '';
			$('myRoute').className = "active";
			$('makeRoute').className = "";
			$('findRoute').className = "";
     	$('importRoute').className = "";

			$('createRouteLink').className = '';
			$('allRoutes').className = "";
			
			if (globalFilter.waarde=='myFavourites')
					melding("Your favourite routes are in the opened summary");
			else
					melding("Your own routes are in the opened summary");

			klapInUitFunctie('uit');
		  toolbar.setToolbar_();	
			hPlot = null;
			if (newr) newr.Init();
			
	}

function act_makeRoute() {
			clearSideBar();

			klapInUitFunctie('in');
			calc.hideCalculatorDiv_();
			$('createRouteLink').style.display = 'inline';
			$('saveRouteLink').style.display = 'inline';
			$('printLink').style.display = 'none';

			$('myRoute').className = "";
			$('makeRoute').className = "active";
			$('findRoute').className = "";
			$('allRoutes').className = "";
     	$('importRoute').className = "";
			rrMODUS = MAKE;
			$('zoekFrm').innerHTML = getZoekForm();

			melding("Search for your location and click on the Draw icon on the top left of the screen");
			hPlot = null;
			if (newr) newr.Init();
		  toolbar.setToolbar_();	
}

function act_importRoute() {
      $('createRouteLink').className = '';
      clearSideBar();
      klapInUitFunctie('in');
      recording = false;
      try {
        calc.hideCalculatorDiv_();
        $('createRouteLink').style.display = 'none';
        $('saveRouteLink').style.display = 'none';
        melding('Select a file with GPS data and its format (optional)');
        $('myRoute').className = "";
        $('makeRoute').className = "";
        $('importRoute').className = "active";
        $('findRoute').className = "";
        $('allRoutes').className = "";
      } catch (e) {
          echo ("error catched in act_zoekRoute");
      }
      rrMODUS = FIND;
      rrROUTEVIEW  = OVERVIEW;
      $('zoekFrm').innerHTML = getImportForm();
      toolbar.setToolbar_();
}

function importRoute_done(routeId) {
      rrMODUS = MY;
      rrROUTEVIEW  = OVERVIEW;

      recording = false;
      calc.hideCalculatorDiv_();

      globalFilter.type = 'fk_client_id';
      globalFilter.waarde = 'myRoutes';

      doAjaxZoekAndClick(routeId);

      $('zoekFrm').innerHTML = '';
      $('myRoute').className = "active";
      $('makeRoute').className = "";
      $('importRoute').className = "";
      $('findRoute').className = "";

      $('createRouteLink').className = '';
      $('allRoutes').className = "";

      /*
      if (globalFilter.waarde=='myFavourites')
          melding('Your favourite routes are in the opened summary');
      else
          melding('Your own routes are in the opened summary');
      */

      klapInUitFunctie('in');
      toolbar.setToolbar_();
}

function act_zoekRoute() {
			$('createRouteLink').className = '';
			if (globalFilter.waarde == 'myRoutes' || globalFilter.waarde == 'myFavourites') {
				globalFilter.waarde = '';
				globalFilter.type = null;
			}

			$('myRoute').className = "";
			$('makeRoute').className = "";
			$('findRoute').className = "active";
			$('allRoutes').className = "";
     	$('importRoute').className = "";
			clearSideBar();
			klapInUitFunctie('in');
			recording = false;
			try {
					calc.hideCalculatorDiv_();
					$('createRouteLink').style.display = 'none';
					$('saveRouteLink').style.display = 'none';
					$('trashIconLink').style.display = 'none';
					$('canceDrawLink').style.display = 'none';
					$('printLink').style.display = 'inline';

					melding('Enter name, town, province or distance in the search field to find a route');
					document.zoekForm.search.focus();
			}
			catch (e) {
					echo ("error catched in act_zoekRoute");
			}
			rrMODUS = FIND;
			rrROUTEVIEW  = OVERVIEW;
			$('zoekFrm').innerHTML = getZoekForm();
		  toolbar.setToolbar_();	
			hPlot = null;
			if (newr) newr.Init();
}

function act_allRoutes() {

			sortBy = 'date_creation';
			sortDir = 'DESC';
			$('createRouteLink').className = '';
			if (globalFilter.waarde == 'myRoutes' || globalFilter.waarde == 'myFavourites') {
				globalFilter.waarde = '';
				globalFilter.type = null;
			}

			$('printLink').style.display = 'inline';

			clearSideBar();
			klapInUitFunctie('uit');
			recording = false;
			$('myRoute').className = "";
			$('makeRoute').className = "";
			$('findRoute').className = "";
			$('allRoutes').className = "active";
     	$('importRoute').className = "";

			rrMODUS = ALL;
			rrROUTEVIEW  = OVERVIEW;
			$('zoekFrm').innerHTML = '';
		  toolbar.setToolbar_();	
			melding("Click again on \"Last added\" to zoom out and see more added routes");
			resetMap();
			hPlot = null;
			if (newr) newr.Init();
}

function clearSideBar() {
				var element = document.getElementById("routeResults");
							while (element.firstChild) {
  								element.removeChild(element.firstChild);
							}
				if (document.getElementById("calculator")){
							var element = document.getElementById("calculator");
							element.style.visibility = 'hidden';
				}
				if (document.getElementById("myTabs")){
							var element = document.getElementById("myTabs");
							while (element.firstChild) {
									element.removeChild(element.firstChild);
							}
				}
}

function RouteTabs() {}

RouteTabs.prototype = new GControl();
RouteTabs.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var tabsDiv = document.createElement("div");
  tabsDiv.id = 'tabsDiv';
  this.setStyle_(tabsDiv);

	var listContainer = document.createElement("ul");

  var myRoute = document.createElement("li");
  myRoute.innerHTML = "<a href='javascript:act_myRoutes()' >My routes</a>";
	myRoute.id = 'myRoute';

  var makeRoute = document.createElement("li");
  makeRoute.innerHTML = "<a href='javascript:act_makeRoute()'>Draw a route</a>";
	makeRoute.id = 'makeRoute';

	var importRoute = document.createElement("li");
  importRoute.innerHTML = "<a href='javascript:act_importRoute()'>Import a route</a>".replace(/{TXT_\d+ (.*)}/, '$1');
  importRoute.id = 'importRoute';

  var findRoute = document.createElement("li");
	findRoute.id = 'findRoute';
  findRoute.innerHTML = "<a href='javascript:act_zoekRoute()' >Search for a route</a>";

  var allRoutes = document.createElement("li");
	allRoutes.id = 'allRoutes';
  allRoutes.innerHTML = "<a href='javascript:act_allRoutes()' >Last added</a>";


	listContainer.appendChild(myRoute);
	listContainer.appendChild(makeRoute);
  listContainer.appendChild(importRoute);
	listContainer.appendChild(findRoute);
	listContainer.appendChild(allRoutes);

	tabsDiv.appendChild(listContainer);

  container.appendChild(tabsDiv);
  map.getContainer().appendChild(container);
  return container;
}

RouteTabs.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, -19));
}

// Sets the proper CSS for the given button element.
RouteTabs.prototype.setStyle_ = function(myDiv) {
  var w =  map.getSize().width;
  myDiv.style.width =  "600px";
}


function RouteToolbar() {
	var container='toolsDiv';
}

RouteToolbar.prototype = new GControl(false, true);
RouteToolbar.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var toolsDiv = document.createElement("div");
  toolsDiv.id = 'toolsDiv';
  this.setStyle_(toolsDiv);
  container.appendChild(toolsDiv);

	var toolsWrapper = this.getToolbar_();

	toolsDiv.appendChild(toolsWrapper);
	var searchSpan = document.createElement("span");
	searchSpan.id = 'zoekFrm';
	searchSpan.style.height = '20px';
	searchSpan.innerHTML = getZoekForm();
	toolsDiv.appendChild(searchSpan);
	
  map.getContainer().appendChild(container);

	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(180,0));
	pos.apply($('zoekFrm'));

  return container;
}

RouteToolbar.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 1));
}

// Sets the proper CSS for the given button element.
RouteToolbar.prototype.setStyle_ = function(myDiv) {
  myDiv.style.width =  "600px";
}

RouteToolbar.prototype.getToolbar_ = function() {
	var toolsWrapper = document.createElement("span");
			toolsWrapper.id = 'toolsWrapper';

	var createRouteLink = document.createElement("img");
	createRouteLink.id = "createRouteLink";
	createRouteLink.src = '../themes/asics20/media/routes/icon_newroute.gif';
	createRouteLink.alt = 'Start';
	createRouteLink.title = 'Start a drawing session';
	createRouteLink.align = "absbottom";
	createRouteLink.className = "";
	createRouteLink.onclick = function() {
			beginRecordingAdvanced();
			this.className="sticky";
			calc.showCalculatorDiv_();
	}
	toolsWrapper.appendChild(createRouteLink);

	var saveRouteLink = document.createElement("img");
	saveRouteLink.id = "saveRouteLink";
	saveRouteLink.src = '../themes/asics20/media/routes/icon_save.gif';
	saveRouteLink.align = "absbottom";
	saveRouteLink.alt = 'Save';
	saveRouteLink.title = 'Save a drawn route';
	saveRouteLink.onclick = saveCurrentRoute;
	toolsWrapper.appendChild(saveRouteLink);

/*
	var homeLink = document.createElement("img");
	homeLink.id = "homeLink";
	homeLink.src = '../themes/asics20/media/routes/icon_home.gif';
	homeLink.align = "absbottom";
	homeLink.alt = 'Reset';
	homeLink.title = 'Return to overview of routes';
	homeLink.onclick = resetMap;
	toolsWrapper.appendChild(homeLink);
*/
	
	var toggleViewLink = document.createElement("img");
	toggleViewLink.id = "toggleViewLink";
	toggleViewLink.src = '../themes/asics20/media/routes/icon_maximize.gif';
	toggleViewLink.alt = "Switch ";
	toggleViewLink.title = "Switch between wide and small screen";
	toggleViewLink.align = "absbottom";
	toolsWrapper.appendChild(toggleViewLink);

  GEvent.addDomListener(toggleViewLink, "click", function() {
			toggleView();
			klapInUitFunctie('in');
	});

	var trashIconLink = document.createElement("img");
	trashIconLink.id = 'trashIconLink';
	trashIconLink.src = imagePath + 'deletewaypoint.gif';
	trashIconLink.alt = "Remove last waypoint";
	trashIconLink.title = "Remove last waypoint";
	trashIconLink.onclick = function () { newr.DeleteLastPoint(); if (hPlot) {hPlot.deleteLastPoint(); hPlot.insertGraph();} } ; 
	trashIconLink.style.width = "20px"; 
	trashIconLink.style.height = "20px" ; 
	trashIconLink.align = "absbottom";
	toolsWrapper.appendChild( trashIconLink );

	var cancelDrawLink = document.createElement("img");
	cancelDrawLink.id = 'cancelDrawLink';
	cancelDrawLink.src = imagePath + 'stopdrawing.gif';
	cancelDrawLink.alt = 'Cancel drawing session';
	cancelDrawLink.title = 'Cancel drawing session';
	cancelDrawLink.onclick = function () { if (confirm("Are you sure you want to stop ?")) {
																						var sURL = unescape(window.location.pathname);
																						window.location.href = sURL;		
																						return true;
																					}
																				  else return false;
																				} ; 
	cancelDrawLink.align = "absbottom";
	toolsWrapper.appendChild( cancelDrawLink );


/*
	var helpLink = document.createElement("img");
	helpLink.id = "helpLink";
	helpLink.src = '../themes/asics20/media/routes/icon_help.gif';
	helpLink.align = "absbottom";
	helpLink.alt = 'Help';
	helpLink.title = 'Need help?';
	helpLink.onclick = showHelp;

	toolsWrapper.appendChild(helpLink);
*/

	var printLink = document.createElement("img");
	printLink.id = "printLink";
	printLink.src = '../themes/asics20/media/routes/icon_print.gif';
	printLink.align = "absbottom";
	printLink.alt = 'Print';
	printLink.title = 'Print route map';
	printLink.onclick = myPrint;

	toolsWrapper.appendChild(printLink);

	var favLink = document.createElement("img");
	favLink.id = "favLink";
	favLink.src = '../themes/asics20/media/routes/icon_favorite.gif';
	favLink.align = "absbottom";
	favLink.alt = 'Favourites';
	favLink.title = 'Add this route to your favorites';
	favLink.onclick = function () {ratingComponent.setStars(3); melding('This route has been added to your favorites.')} ;
	favLink.style.display = 'none' ;

	toolsWrapper.appendChild(favLink);

	var speedLink = document.createElement("img");
	speedLink.id = "speedLink";
	speedLink.src = '../themes/asics20/media/routes/icon_speed.gif';
	speedLink.align = "absbottom";
	speedLink.alt = 'Change your average speed';
	speedLink.title = 'Change your average speed';
	speedLink.onclick = function () 
	{ 
			if (calc.style.visibility == 'visible')
					calc.hideCalculatorDiv_(); 
			else
			{
					melding("The length of your route so far and your completion time are at the bottom of the screen.");
					calc.showCalculatorDiv_(); 
			}
	}

	speedLink.style.display = 'inline' ;

	toolsWrapper.appendChild(speedLink);
	return toolsWrapper;
}

RouteToolbar.prototype.setToolbar_ = function() {

	var cr = document.getElementById("createRouteLink");
	var sv = document.getElementById("saveRouteLink");
	var sl = document.getElementById("speedLink");
	var fl = document.getElementById("favLink");

	var tr = document.getElementById("trashIconLink");
	var ca = document.getElementById("cancelDrawLink");
	 

	if (rrMODUS == MAKE) {
			cr.style.display = 'inline';
			sv.style.display = 'inline';

			tr.style.display = 'none';
			ca.style.display = 'none';
	}
	else {
			cr.style.display = 'none';
			sv.style.display = 'none';
			tr.style.display = 'none';
			ca.style.display = 'none';
	}

	if (fl)
		fl.style.display = 'none';

	if (sl)
	{
		sl.style.display = 'inline';
	}
}
/* 
*/

RouteToolbar.prototype.hideToolbar_ = function() {
	document.getElementById('toolsDiv').style.display = 'none';
	document.getElementById('tabsDiv').style.display = 'none';
}

function RouteStatus() {}

RouteStatus.prototype = new GControl();
RouteStatus.prototype.initialize = function(map) {

	var container = document.createElement("div");
  var statusDraw = document.createElement("div");
  statusDraw.id = 'statusDraw';
  statusDraw.style.display = 'none';
  statusDraw.style.width = '100%';
// {statusDraw}

	container.appendChild(statusDraw);
  map.getContainer().appendChild(container);

	melding ('Choose location, manage routes, draw, measure your route, search for routes, share and rate');
  return statusDraw;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
RouteStatus.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 34));
}


// is eigenlijk de in - en uitschuifbare sidebar rechts met routeoverzichten en route detailinfo
function RouteControls() {
}

	
	RouteControls.prototype = new GControl();
	RouteControls.prototype.initialize = function(map) {

	var container = document.createElement("div");

	var controlsDiv = document.createElement("div");
	controlsDiv.id = 'sidebar';
	this.setButtonStyle_(controlsDiv);
	container.appendChild(controlsDiv);

		// tabel met waypoints en afstanden
	var routeResults = document.createElement("div");
	routeResults.id = 'routeResults';
	routeResults.style.position = 'relative';
	routeResults.style.top = '15px';
	routeResults.style.height = '99%';
	controlsDiv.appendChild(routeResults);


	var klapInUit = document.createElement("img");
	klapInUit.src = imagePath + "closediv.gif";
	klapInUit.title = "Click here to open the summary" ;
	klapInUit.id = 'klapInUit';

	/*klapInUit.onclick = klapInUitFunctie; */
  GEvent.addDomListener(klapInUit, "click", klapInUitFunctie);
	controlsDiv.appendChild(klapInUit);

	map.getContainer().appendChild(container);
	return container;
}

RouteControls.prototype.getDefaultPosition = function() {
  			return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0,34));
}


RouteControls.prototype.setButtonStyle_ = function(button) {
  var h =  map.getSize().height ;
  button.style.height =   h+'px';
  button.style.width = "400px";
}


/* Calculator */
function calculatorControl() {
}

calculatorControl.prototype = new GControl();
calculatorControl.prototype.initialize = function(map) {

	var container = document.createElement("div");
	var calculator = document.createElement("div");
	this.setCalculatorDiv_(calculator);
	this.setStyle_(calculator);
	container.appendChild(calculator);
	map.getContainer().appendChild(container);
	return container;
}

calculatorControl.prototype.getDefaultPosition = function() {
  			return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0,0));
}

calculatorControl.prototype.setStyle_ = function(div) {
  div.style.height = "30px";
	div.style.border = "1px solid";
  var w =  map.getSize().width;
  div.style.width =  (w-300)+"px";
}


calculatorControl.prototype.setCalculatorDiv_ = function (thisDiv) {

	thisDiv.id = "calculator";
	thisDiv.style.visibility = "hidden";

	var hdr = document.createElement('strong');
	hdr.appendChild(document.createTextNode("Calculator: "));
	hdr.appendChild(document.createElement('br'));
  thisDiv.appendChild(hdr);
	
  thisDiv.appendChild(document.createTextNode("distance "));
  var distElm = document.createElement("span");
  distElm.id = "currentDist";
  distElm.appendChild(document.createTextNode("0"));
  thisDiv.appendChild(distElm);

  thisDiv.appendChild(document.createTextNode(" Speed "));


	var down= document.createElement("a");
	down.appendChild(document.createTextNode(" <<"));
	down.title='reduce speed';
	down.href= 'javascript:modifySpeed(-1)';
	thisDiv.appendChild(down);

  var spdElm = document.createElement("span");
  spdElm.id = "currentSpeed";
  spdElm.appendChild(document.createTextNode("0"));
  thisDiv.appendChild(spdElm);

	var up= document.createElement("a");
	up.appendChild(document.createTextNode(">> "));
	up.title='increase speed';
	up.href= 'javascript:modifySpeed(1)';
	thisDiv.appendChild(up);

  var tmElm = document.createElement("span");
  tmElm.id = "currentTime";

  tmElm.appendChild(document.createTextNode("00:00:00"));

  thisDiv.appendChild(tmElm);

  var hImg = document.createElement("img");
  hImg.id = "heightImage";
	hImg.style.display= "none";
  thisDiv.appendChild(hImg);

}

calculatorControl.prototype.showCalculatorDiv_ = function () {
		if ($('calculator'))
			$('calculator').style.visibility = 'visible';
		else 
			alert('calculator');
}

calculatorControl.prototype.hideCalculatorDiv_ = function () {
		$('calculator').style.visibility = 'hidden';
}
/* Einde calculatorcontrol */

/* RouteInfo */
function RouteInfo() {
}

RouteInfo.prototype = new GControl();
RouteInfo.prototype.initialize = function(map) {

	var container = document.createElement("div");
	var routeinfo = document.createElement("div");
	this.setRouteInfoDiv_(routeinfo);
	this.setStyle_(routeinfo);
	container.appendChild(routeinfo);
	map.getContainer().appendChild(container);
	return container;
}

RouteInfo.prototype.getDefaultPosition = function() {
  			return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(441,100));
}

RouteInfo.prototype.setStyle_ = function(div) {
  div.style.height = "350px";
  div.style.width =  "1px";
}

RouteInfo.prototype.setRouteInfoDiv_ = function (thisDiv) {

	thisDiv.id = "routeinfo";
	thisDiv.style.visibility = "hidden";

  thisDiv.style.height = "350px";
  thisDiv.style.width =  "1px";
	thisDiv.style.margin= "0px";
	thisDiv.style.padding= "0px";
}

RouteInfo.prototype.showRouteInfoDiv_ = function () {

		map.closeInfoWindow();

		if ($('routeinfo')) {
			$('routeinfo').style.visibility = 'visible';
  		$('routeinfo').style.overflow  = "auto";
  		$('routeinfo').style.height = "350px";
  		$('routeinfo').style.width =  "300px";
			$('routeinfo').style.padding= "0px 20px";
		}
		else 
			alert('routeinfo');
}

RouteInfo.prototype.hideRouteInfoDiv_ = function () {
	$('routeinfo').style.visibility = 'hidden';
  $('routeinfo').style.height = "350px";
  $('routeinfo').style.width =  "1px";
  $('routeinfo').style.overflow  = "hidden";
}

RouteInfo.prototype.writeRouteInfo_ = function (id) {

		var thisDiv = $('routeinfo');
		var currentRoute;

		for (i=0 ; i< routesFound.length; i++) {
				if (routesFound[i].id == id) {
						currentRoute = routesFound[i];

					var wrap = document.createElement('div');
					var hdr = document.createElement('h2');
					hdr.appendChild(document.createTextNode("Route information"));
  				wrap.appendChild(hdr);

					var info = document.createElement('span');
					var html ="";
					html += "<img onclick='javascript:ri.hideRouteInfoDiv_();' style='border: 0px none ; margin: 0px; padding: 0px; position: absolute; left: 299px; top: 11px; width: 12px; height: 12px; -moz-user-select: none; cursor: pointer; z-index: 10000;'src='http://www.google.com/intl/en_ALL/mapfiles/iw_close.gif'/>";

						if (currentRoute.fk_photo_id > 0) 
							html += "<center><img onclick='javascript:showPhoto(" + currentRoute.fk_photo_id+");'src='thumb.php?id=" + currentRoute.fk_photo_id + "' title='thumbnail route' /></center>" ;

					html +=	"<ul>";
					html += "<li>Name: "+cStr(currentRoute.description) + "</li>";
					html += "<li>Post code: "+cStr(currentRoute.postalcode )+ "</li>";
					html += "<li>Owner: "+cStr(currentRoute.author_name) + "</li>";
					html += "<li>Area: "+cStr(currentRoute.region) + "</li>";
					html += "<li>Place: "+cStr(currentRoute.placename) + "</li>";
					html += "<li>Terrain: "+cStr(currentRoute.underground) + "</li>";
					html += "<li>Surrounding area: "+cStr(currentRoute.environment) + "";
					//currentRoute.distance = (currentUnit == "km</li>" ? fix(currentRoute.distance,1) : fix((currentRoute.distance*MILESASKM),1));
					html += "<li>distance: "+currentRoute.distance + " km</li>";
					html += "<li>Country code: "+cStr(currentRoute.countrycode) + "</li>";
					var oordeel = isNaN(Math.round(currentRoute.rate/currentRoute.rate_counter))?"Not assessed":Math.round(currentRoute.rate/currentRoute.rate_counter);
					html += "<li>Average rating: " + oordeel + "</li>";
					html += "</ul>";

					info.innerHTML = html;
  				wrap.appendChild(info);
					thisDiv.appendChild(wrap);
				}
		}

}

RouteInfo.prototype.clearRouteInfo_ = function () {

	var info = $('routeinfo');
	while (info.firstChild) {
			info.removeChild(info.firstChild);
	}

}
/* Einde RouteInfo */

function createIconHTML (href,onClick,title,imgSrc) {
	var commonText = "<a href='"+href+"' onclick='"+onClick+"'><img src='"+imgSrc+"' title='"+title+"'></a>&nbsp;";
	commonText += "<a href='"+href+"' onclick='"+onClick+"' title='"+title+"'>"+title+"</a>";
	return commonText;
}

function createIconDOM (href,clck,title,imgSrc,linkid,linkClass) {
	var iconLink = document.createElement("span");
	iconLink.id = linkid;
	iconLink.height = '25px';
	if (linkClass) {
		iconLink.className = linkClass;
	}

	var beginRecordingIcon = document.createElement("img");
	beginRecordingIcon.src = imgSrc;
	beginRecordingIcon.align = "absbottom";
	iconLink.appendChild(beginRecordingIcon);
	
	GEvent.addDomListener(iconLink, "click", clck); 
	return iconLink;
}
function toggleUnits() {
	currentUnit = currentUnit == "miles" ? "km" : "miles";
	setUnitCookie();
	altUnit = currentUnit == "miles" ? "km" : "miles";
	currentSpeed = altUnit == "miles" ? currentSpeed * MILESASKM : currentSpeed / MILESASKM;
	setSpeedCookie();
	minutesPerUnit = 60 / currentSpeed;
	drawRoute(route);
	return false;
}

function modifySpeed(step) {
	try {
		currentSpeed = currentSpeed + step;
		minutesPerUnit = 60/currentSpeed;
		setSpeedCookie();
		drawRoute(route);
	} catch (e) {
		alert("Invalid speed");
	}
}

function modifyWeight() {
	var newWeight = prompt("Enter your weight in pounds");
	try {
		parseFloat(newWeight);
		currentWeight = newWeight;
		setWeightCookie();
		if (currentUnit == "miles") {
			$('currentCal').innerHTML = fix((routeDistance*MILESASKM) * (currentWeight/2.2) * 1.036,1);
		} else {
			$('currentCal').innerHTML = fix(routeDistance * (currentWeight/2.2) * 1.036,1);
		}
		$('currentWeight').innerHTML = "based on " + currentWeight + " pound person";
		return false;
	} catch (e) {
		alert("The weight you entered was not valid, reverting to " + currentWeight + " pounds");
		return false;
	}
	return false;
}
function emailMe() {
	return false;
}
function mapLocByFraction (lat_factor,lng_factor) {
	var bnds = map.getBounds();
	var latlng = 
		new GLatLng(
			lat_factor != undefined ? bnds.getNorthEast().lat() - ((bnds.getNorthEast().lat()-bnds.getSouthWest().lat())*(lat_factor)) : map.getCenter().lat(),
			lng_factor != undefined ? bnds.getNorthEast().lng() - ((bnds.getNorthEast().lng()-bnds.getSouthWest().lng())*(lng_factor)) : map.getCenter().lng()
			);
	return latlng;
}
function addAddress() {
	return false;
}
function showAddressResults (request) {
}

function launchComment(id) { 
} 

function setWeightCookie() {
	createCookie("userWeight",currentWeight,100);
}

function getWeightCookie() {
	var userWeight = readCookie("userWeight");
	if(userWeight){
		try {
			parseFloat(userWeight);
			currentWeight = userWeight;
			return currentWeight;
		} catch (e) {
			currentWeight = 190;
			setWeightCookie();
			return currentWeight;
		}
	} 
}

function setLatCookie() {
	createCookie("lat",map.getCenter().lat(),100);
}
function setLongCookie() {
	createCookie("lg",map.getCenter().lng(),100);
}
function setZoomCookie() {
	createCookie("zmlevel",17-map.getZoom(),100);
}
function setMapMode() {
	switch (map.getCurrentMapType().getName()) {
			case 'Map' : createCookie("mode","normal",100);break;
			case 'Satellite' : createCookie("mode","satellite",100);break;
			case 'Hybrid' : createCookie("mode","hybrid",100);break;
			default : break;
		}
}
function getLatCookie() {
	var userLat = readCookie("lat");
	if(userLat){
		try {
			currentLat = parseFloat(userLat);
			return currentLat;
		} catch (e) {
			currentLat = '';
			setLatCookie();
			return currentLat;
		}
	}
}
function getLngCookie() {
	var userLng = readCookie("lg");
	if(userLng){
		try {
			currentLng = parseFloat(userLng);
			return currentLng;
		} catch (e) {
			currentLng = '';
			setLngCookie();
			return currentLng;
		}
	}
}
function getZmCookie() {
	var userZm = readCookie("zmlevel");
	if(userZm){
		try {
			currentZm = parseFloat(userZm);
			return currentZm;
		} catch (e) {
			currentZm = '';
			setZoomCookie();
			return currentZm;
		}
	}
}
function setUnitCookie() {
	createCookie("userUnit",currentUnit,100);
}
function getUnitCookie() {
	var userUnit = readCookie("userUnit");
	if(userUnit){
		try {
			currentUnit = userUnit;
			altUnit = currentUnit == "miles" ? "km" : "miles";
			return currentUnit;
		} catch (e) {
			currentUnit = "miles";
			setUnitCookie();
			return currentUnit;
		}
	}
}
function setSpeedCookie() {
	createCookie("userSpeed",currentSpeed,100);
}
function getSpeedCookie() {
	var userSpeed = readCookie("userSpeed");
	if(userSpeed){
		try {
			parseFloat(userSpeed);
			currentSpeed = userSpeed;
			minutesPerUnit = 60 / currentSpeed;
			return currentSpeed;
		} catch (e) {
			currentSpeed = 3.0;
			minutesPerUnit = 60 / currentSpeed;
			setSpeedCookie();
			return currentSpeed;
		}
	}
}

/* Cookie Functions courtesy of Quirksmode
	http://www.quirksmode.org/js/cookies.html
*/
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
/* 
*/
function showRouteList () {
	toggleSubTabs('routesSubNav','tab_routes_list','routes');
}

function toggleTabs(tabName) {
	if (lastTab) {
		lastTab.className = 'hiddenTab';
		lastTabLabel = $(lastTab.id+'_nav');
	} else {
		$('home').className = 'hiddenTab';
		lastTabLabel = $('home_nav');
	}
	if (lastTabLabel) {
		lastTabLabel.className = 'tablabel';
	}
	var urchinURL = "/toggleTabs/"+tabName;
	urchinTracker(urchinURL);
	lastTab = $(tabName);
	lastTab.className = 'visibleTab';
	lastTabLabel = $(lastTab.id+'_nav');
	if (lastTabLabel) {
		lastTabLabel.className = 'tablabelHi';
	}
	return false;
}

/* 
*/
function beginRecording() {

	recording = true;
	map.clearOverlays();
	route = [];
	elev8n = [];
	routeDistance = 0;
	currentRouteId = null;
	$('createRouteLink').className = 'sticky';

/*
	var cancelButton = $('cancelRouteLink');
	cancelButton.className = 'controlEnabled';
*/

	melding('Click on the map for the starting point of your route');
	setInner('routeResults','');
	return false;
}

function beginRecordingAdvanced() {

	var tr = document.getElementById("trashIconLink");
	var ca = document.getElementById("cancelDrawLink");
	var zfrm = document.getElementById("zoekFrm");

	tr.style.display = 'inline';
	ca.style.display = 'inline';
	zfrm.style.display = 'none';

	recording = true;
	map.clearOverlays();
	route = [];
	elev8n = [];
	routeDistance = 0;
	currentRouteId = null;

	$('createRouteLink').className = 'sticky';

	if ( ! newr ){
				newr = new RouteDraw( map, document.createElement( 'div' ) );
	}

	hPlot = null;
	newr.Start();

	currentRouteId = null;
	currentRoute = null;
	currentRoute = initRoute();
	currentWaypoint = null;
	currentWaypoint = initWaypoint();

	melding('Click on the map for the starting point of your route');
	setInner('routeResults','');
	return false;

}

function startRoute(point) {
	route.push(point);
	currentRouteId = null;
	currentRoute = null;
	currentRoute = initRoute();
	currentWaypoint = null;
	currentWaypoint = initWaypoint();

	drawRoute(route);
}

function claimRoute(rid) {
}
function displayClaimResult(http) {
;
}

function setRouteOwner(http) {
;
}

function showRoute(http,rid) {
    var xmlDoc = http.responseXML;
    var markers = xmlDoc.documentElement.getElementsByTagName("marker");
	var newRoute = [];
    for (var i = 0; i < markers.length; i++) {
      var point = new GPoint(parseFloat(markers[i].getAttribute("lng")),
                             parseFloat(markers[i].getAttribute("lat")));

			
			/********  TODO elevation
      var loadElev8n = markers[i].getAttribute("elev8n");
      if (loadElev8n) {elev8n.push(loadElev8n);} else {
      	doLookupElevation(point.x,point.y);
      }
			***************/

      newRoute.push(point);
    }
	route=newRoute;
	map.clearOverlays();
	// Ik wil niet dat ie constant gecentreerd wordt en de modus naar 14 wordt gezet
	//map.setCenter(new GLatLng(route[0].y,route[0].x), 14);
	currentRouteId = rid;
	drawRoute(newRoute);
    return false;
}

function cStr(val) {
	return (typeof(val)=='string' || typeof(val)=='number')?val:'';
}

function doAjaxGetOptions() {
	if (!fOptionsSet) ajaxCall("getOptions.php?" ,responseOptions,1,0);
	switchForm(0);
}

function klapInUitFunctie(vlag) {
		if (sidebarMODUS==WIDE){
							var do_it = true;							
							if (vlag=='uit') {
										do_it=false;	
							}
							if (do_it) {
											var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(-427,0));
											pos.apply(document.getElementById("sidebar"));
											$('klapInUit').src = imagePath + "opendiv.gif";
											$('klapInUit').title = "Click here to open the summary" ;
											sidebarMODUS = SMALL;
							}
		}
		else {
							var do_it = true;							
							if (vlag=='in') {
										do_it=false;	
							}
							if (do_it) {
											var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0,0));
											pos.apply(document.getElementById("sidebar"));
											$('klapInUit').src = imagePath + "closediv.gif";
											$('klapInUit').title = "Click here to close the summary" ;
											sidebarMODUS = WIDE;
							}
		}
}

function doAjaxZoek() {
		var routeListURL = "getRoutes.php?1=1&noBounds&sortBy=" + sortBy + "&sortDir="+ sortDir +"&q=" + (globalSearchString==null?"":globalSearchString) + "&filtertype=" + (globalFilter.type==null?"":globalFilter.type) + "&filter="+(globalFilter.type==null?"":globalFilter.waarde);

		klapInUitFunctie('uit');
		changeBodyClass('standby', 'loading');
		ajaxCall(routeListURL,processRouteList,1,0,false);
}

function doAjaxZoekAndClick(routeId) {
    var routeListURL = "getRoutes.php?1=1&noBounds&sortBy=" + sortBy + "&sortDir="+ sortDir +"&q=" + (globalSearchString==null?"":globalSearchString) + "&filtertype=" + (globalFilter.type==null?"":globalFilter.type) + "&filter="+(globalFilter.type==null?"":globalFilter.waarde);

    klapInUitFunctie('uit');
    changeBodyClass('standy', 'loading');
    ajaxCall(routeListURL,function (req) { processRouteList(req,false); clickRoute(routeId); },1,0);
}

function clickRoute(rid) {
  var routeListitem = $('route'+rid);
  routeListitem.onclick();
}

function responseOptions(request) {
			obj = xml2json.parser(request.responseText);
			if (obj.response.type=='success')	 {
					respObj =  obj.response.options;

					fRegion= respObj.region.option;
					fPlacename= respObj.placename.option;
					fCountrycode= respObj.countrycode.option;
					fUnderground= respObj.underground.option;
					fEnvironment= respObj.environment.option;
					fPostalcode= respObj.postalcode.option;

					fOptionsSet = true;
			}
			else {
					alert (obj.response.message);
			}
			changeBodyClass('loading', 'standby');
}

function switchForm(flag, reset) {
	if (flag==1)
		setInner('zoekFrm', getZoekForm()); 
	else {
		if (globalFilter.type = 'fk_client_id') {
				globalFilter.type = null;
				globalFilter.waarde = "";
		}
		setInner('zoekFrm', getFilterForm()); 
	}
}

function getZoekForm() {

		var html;
		if (rrMODUS==FIND || rrMODUS==ALL) {
//				html = "<span style='float: left; position: relative; top: 12px;'>Search for route&nbsp;</span>";

				html = "<form name='zoekForm' method='post' action='javascript:globalSearchString=document.zoekForm.search.value;doAjaxZoek()'>";

				html += "<span style='float: left; display: block; padding-top: 2px;'>Search for route&nbsp;</span>";

				html += "<input style='width: 200px;margin-top: 3px;' name='search' onfocus='this.select();' value='Route name, distance, description, region'id='searchInput' />";
		}
		else {
				html = "<span style='float: left; position: relative; top: 3px;'>Search for location&nbsp;</span><form name='zoekForm' method='post' action='javascript:findLocation()'>";
				html += "<input style='width: 200px;' name='search' onfocus='this.select();' value='[address], city, country' id='searchInput' />";
		}
		html += "<input class='gosave' type='submit' value='Start searching'/>";
		html  += "</form>";

		/* html += "or Filter&nbsp;<a class='go' href='javascript:doAjaxGetOptions();' title='Filter'  />&nbsp;</a>"; */
return html
}

function getImportForm() {

  var html;
  html = '<iframe src="importRoute.php" width="600" height="26" frameborder="0"></iframe>';
  return html
}

function changeFilter(waarde, idx) {

		if (globalFilter.type==null) {
					globalFilter.type= waarde;
					globalFilter.label = aFilter[idx-1];
					setInner('zoekFrm', getFilterForm()); 
		} else {
					globalFilter.waarde = waarde;
					setRouteListTitle();
					doAjaxZoek();
		}
}

function setRouteListTitle() {
				/*
				var zoekEnFilter = "Routes";
				var en="<br />";
				if (globalFilter.waarde != null) {
					if (globalFilter.waarde == 'myRoutes' || globalFilter.waarde == 'myFavourites') zoekEnFilter += " ";
					en = "";
				}
				if (globalSearchString != null) {
					zoekEnFilter += en + " with '"+ globalSearchString+ "'";
				}
				setInner ('tableTitle', zoekEnFilter);
				*/
				setInner ('tableTitle', '');

}
	
function getFilterForm() {
		var html = "<form method='post' action='javascript:empty();'>";
		html += "<label>Filter&nbsp;"+ globalFilter.label+ "</label><select onchange='javascript:changeFilter(this.value, this.selectedIndex);' name='filterBy'>"+getOptionList() + "</select>";
		html += "or search&nbsp;<a class='goback' href='javascript:switchForm(1)' title='Search'  />";
		html  += "</form>";
return html;
}

function getOptionList () {

		var aDistance = new Array( '<5', '5-8', '8-12', '12-18', '>18');
		var sOptionList ="<option value=''>Choose from list</option>";
		
		if (globalFilter.type==null) {
				for (i=0; i< aFilter.length; i++ ) {
					sOptionList += "<option value='"+aFilterKey[i]+"'>"+aFilter[i]+"</option>";
				}
		} else {
				switch (globalFilter.type) {
					case 'rate': 
						for (i=0; i< 5; i++ ) {
							sOptionList += "<option value='"+(i+1)+"'>"+ (i+1) +"</option>";
						}
						break;
					case 'distance': 
						for (i=0; i< aDistance.length; i++ ) {
							sOptionList += "<option value='"+aDistance[i]+"'>"+aDistance[i]+"</option>";
						}
					break;
					case 'underground': 
						for (i=0; i< fUnderground.length; i++ ) {
							sOptionList += "<option value='"+cStr(fUnderground[i])+"'>"+cStr(fUnderground[i])+"</option>";
						}
					break;
					case 'environment': 
						for (i=0; i< fEnvironment.length; i++ ) {
							sOptionList += "<option value='"+cStr(fEnvironment[i])+"'>"+cStr(fEnvironment[i])+"</option>";
						}
					break;
					case 'postalcode': 
						for (i=0; i< fPostalcode.length; i++ ) {
							sOptionList += "<option value='"+cStr(fPostalcode[i])+"'>"+cStr(fPostalcode[i])+"</option>";
						}
					break;
					case 'region': 
						for (i=0; i< fRegion.length; i++ ) {
							sOptionList += "<option value='"+cStr(fRegion[i])+"'>"+cStr(fRegion[i])+"</option>";
						}
					break;
					case 'placename': 
						for (i=0; i< fPlacename.length; i++ ) {
							sOptionList += "<option value='"+cStr(fPlacename[i])+"'>"+cStr(fPlacename[i])+"</option>";
						}
					break;
					case 'countrycode': 
						for (i=0; i< fCountrycode.length; i++ ) {
							sOptionList += "<option value='"+cStr(fCountrycode[i])+"'>"+cStr(fCountrycode[i])+"</option>";
						}
					break;
					/*
					case 'fk_client_id': 
							globalFilter.waarde = 'myRoutes';
							setRouteListTitle();
							doAjaxZoek();

					break;
					*/
					default:
					break;
				}
		}
			
		return sOptionList;
}

function processRouteList(request, add_markers) {

	obj = xml2json.parser(request.responseText );

	changeBodyClass('loading', 'standby');
	var routeListDiv = $('routeResults');
	routeListDiv.innerHTML = "";

	if (obj.response.type=='success')	 {
		routesFound=obj.response.markers.route;
		client_id = obj.response.client_id;
		try {
		 var bla = routesFound[0].id;
		}
		catch (e) {
					routesFound = new Array();
					routesFound.push(obj.response.markers.route);
		}
		for (i=0 ; i< routesFound.length; i++) {
				;
				//routesFound[i].rate = ((routesFound[i].rate_counter>0  && routesFound[i].rate >0)?Math.round(routesFound[i].rate/routesFound[i].rate_counter):0);
		}
	}
	else {
		melding ('No routes found');
		//routeListDiv.innerHTML = "no routes found";
		routesFound = [];
	}

	var routeListDiv = $('routeResults');
	routeListDiv.innerHTML = "";

if (rrMODUS==MY) {
  var myRoutesTabs = document.createElement('div');
	myRoutesTabs.id = 'myTabs';
	myRoutesTabs.className = 'tabs';
	var ul = document.createElement('ul');
	myRoutesTabs.appendChild(ul);
	var a = new Array('my','fav');
	var l = new Array('My routes','My favourites');
	for (y=0 ; y<2 ; y++) {
					if (!globalFilter.waarde) globalFilter.waarde = 'myRoutes';
					var il = document.createElement('li');
					if (y==0 && globalFilter.waarde == 'myRoutes')
							il.className = 'active';
					if (y==1 && globalFilter.waarde == 'myFavourites')
							il.className = 'active';

					var anc = document.createElement('a');
					anc.href='javascript:act_myRoutes("'+ a[y] + '")';
					var txt = document.createTextNode(l[y]);
					anc.appendChild(txt);
					il.appendChild(anc);
					ul.appendChild(il);
	}
	routeListDiv.appendChild(myRoutesTabs);
} 
else {
	if (HAS_PARTNERFINDER) {
					if (map.getZoom() < 12) { removePartnerseekerMarkers(); melding ("Zoom again to see potential training partners"); }
					if (map.getZoom() >=12 && map.getZoom() <= 14 ) loadPartnerseekers();
					if (map.getZoom() > 14 ) removePartnerseekerMarkers();
	}

	if (document.getElementById('myTabs')) {
					var t = document.getElementById('myTabs');
					routeListDiv.removeChild(t);
	}
}


	//routeListDiv.appendChild(searchDiv);

	var routeListTable = createRouteListTable('zoekTabelDiv', routesFound , add_markers?false:true);
	routeListDiv.appendChild(routeListTable);
	setRouteListTitle();

	// en nu pas de markers erin
	//if (add_markers) 
	if (true) {
					for (var i=0; i < routesFound.length ; i++) {
							var point = new GPoint(parseFloat(routesFound[i].route_waypoint.longitude), parseFloat(routesFound[i].route_waypoint.latitude));
							var routeId = routesFound[i].id;
							var html ="<div id=\"route_info_" + routeId + "\" style='width:300px;'><h3>Route information</h3>";

							html += "<strong>"+ routesFound[i].description +"</strong><br />";
							if ( routesFound[i].fk_photo_id > 0 ) 
							html += "<img style='float: left; padding : 0.2em; margin-left: 5px;' height='50px' onclick='javascript:showPhoto(" + routesFound[i].fk_photo_id+");'src='thumb.php?id=" + routesFound[i].fk_photo_id + "' title='thumbnail route' />" ;

							html += "<br style='clear: both' />Added by: " + routesFound[i].author_name;

							html += "<img style='float: left; padding : 0.2em; margin-left: 5px;' height='50px' src='../home/preferences.php?avatar&id=" + routesFound[i].fk_client_id + "&ajax=1' />";

							html += "<br style='clear : both' />distance: "+ fix(routesFound[i].distance,2) +" km&nbsp;";
							html += "<br />Place: "+ cStr(routesFound[i].placename) + "";
							html += "<br />Terrain: " + cStr(routesFound[i].underground)+"";
							html += "<br />Surrounding area: " + cStr(routesFound[i].environment)+"";
							html += "<br />Public URL: <br /><input size='200px' onclick='javascript:this.select();' type='text' readonly='1' value='"+ SITEURL +  "routes/route.php?route_id=" + routeId + "' /><br />";

							if (routesFound[i].fk_client_id == client_id) {
								html += "<br /><a href='javascript:doAjaxLoadRoute(\"" +routeId+ "\");' title='Change route'>View or change your route</a>";
	              html += "<br /><a href='javascript:showDownloadDialog(\"" +routeId+ "\");' title='Download route'>Download this route</a>";
								html += "<br /><a href='javascript:doAjaxDeleteRoute(\"" +routeId+ "\");' title='Delete route'>Delete this route</a>";
							}
							else {
								html += "<br /><a href='javascript:doAjaxLoadRoute(\"" +routeId+ "\");' title='View route'>View this route</a>";
	              html += "<br /><a href='javascript:showDownloadDialog(\"" +routeId+ "\");' title='Download route'>Download this route</a>";
							}
							html += "</div>";

							html += "<div id=\"route_download_" + routeId + "\" style='width:300px; display: none;'><h3>Download route</h3>";
              html += "<iframe src=\"exportRoute.php?route_id=" + routeId + "\" width=\"300\" height=\"100\" frameborder=\"0\"></iframe>";
              html += "</div>";

							var marker = createRouteMarker(point,html,iconroute,routeId);
							map.addOverlay(marker);
						}
		}
	
		$('favLink').style.display = 'none';
		$('speedLink').style.display = 'none';
		changeBodyClass('loading', 'standby');

}

function showDownloadDialog(routeId) {
  $('route_info_'+routeId).style.display = 'none';
  $('route_download_'+routeId).style.display = 'block';
}

function showInfoDialog(routeId) {
  $('route_download_'+routeId).style.display = 'none';
  $('route_info_'+routeId).style.display = 'block';
}

function loadRoutes() {
	var boundsSW = map.getBounds().getSouthWest();
	var boundsNE = map.getBounds().getNorthEast();
	changeBodyClass('standby', 'loading');

	if (!isNaN(boundsSW.lng()) && !isNaN(boundsSW.lat()) && !isNaN(boundsNE.lng()) && !isNaN(boundsNE.lat())) {
		var routeListURL = "getRoutes.php?lowerLongitude="+boundsSW.lng()+"&upperLongitude="+boundsNE.lng()+ "&lowerLatitude="+boundsSW.lat()+"&upperLatitude="+boundsNE.lat()+ "&sortBy=" + sortBy + "&sortDir="+ sortDir;
;
		ajaxCall(routeListURL,processRouteList,1,0, true);
	} else {
		alert('Google Maps error; please try again later');
	}
	return false;
}

function loadPartnerseekers() {
	var boundsSW = map.getBounds().getSouthWest();
	var boundsNE = map.getBounds().getNorthEast();
	changeBodyClass('standby', 'loading');

	if (!isNaN(boundsSW.lng()) && !isNaN(boundsSW.lat()) && !isNaN(boundsNE.lng()) && !isNaN(boundsNE.lat())) {
		var pfURL = "getPartnerseekers.php?lowerLongitude="+boundsSW.lng()+"&upperLongitude="+boundsNE.lng()+ "&lowerLatitude="+boundsSW.lat()+"&upperLatitude="+boundsNE.lat();
;
		ajaxCall(pfURL,processPartnerseekers,1,0, true);
	} else {
		alert('Google Maps error; please try again later');
	}
	return false;
}

function processPartnerseekers(req) {
		eval ('var respObjSeekers='+ req.responseText);
		try {
						if ( respObjSeekers.length > 0 ) 
						{
							var i=0;
							while ( i < respObjSeekers.length ) 
							{
								if (!checkPfmarkers( respObjSeekers [ i ].client_id ) ) 
								{
												var point =  getNewPoint(respObjSeekers[ i ].latitude, respObjSeekers [ i ].longitude);
												var contactHtml = "<h3 >Let's train together ?</h3>";
												contactHtml += "" + respObjSeekers[ i ].profile ; 
												contactHtml += "<br /><p>search : " + respObjSeekers[ i ].gender;
												contactHtml += "<br />" + respObjSeekers[ i ].sport;
												contactHtml += "<br />" + respObjSeekers[ i ].speed;
												contactHtml += "<br />" + respObjSeekers[ i ].message + "</p>";
												contactHtml += "<br /><a href='javascript:mailPartner(" + respObjSeekers [ i ].client_id + ")'>Do contact</a>" ;
												contactHtml += "<br /><a href='../community/partnerfinder.php' target='_new' >Put yourself on the map for a training partner</a><br />&nbsp;" ;
												contactHtml += "<br />More training partners on this location:<span id='pf'></span><br />&nbsp;" ;

												pfMarkers.push( { marker : createPfMarker ( point, contactHtml ), client_id : respObjSeekers [ i ].client_id , samePoints : []}  ) ;
												idxMrk = pfMarkers.length - 1;
												map.addOverlay( pfMarkers[ idxMrk ].marker );
								}
								i++;
							}
							/*samePointPfmarkers(); */
							if (i==0) melding("No training partners found");
						}
		}
		catch (e) {
				melding (e + " in processPartnerseekers()");
		}
}

function createPfMarker ( point, contactHtml ) { 
				var mrkr = new GMarker( point  , {icon : pfIcon , draggable: true });
				GEvent.addListener(mrkr, 'click', function() { 
											mrkr.openInfoWindowHtml(contactHtml);	
											/* setTimeout( function () { checksamePoints(mrkr.getPoint()) }, 10); */
				} );

				GEvent.addListener(mrkr, 'infowindowopen', function() { 
							checkSamePoints(mrkr.getPoint());	
				} );

			return mrkr;
} 

function getNewPoint(lat, lng) {

	var already_has_marker = false;

	var p = new GLatLng( lat, lng );
	var i = 0;
  while ( i <  pfMarkers.length ) 
	{
			if ( p.equals(pfMarkers[ i ].marker.getPoint()) )		
				 already_has_marker = true;
			i++;
	}
	
	/*
	if (already_has_marker)
	{
		lat = parseFloat(lat) + 0.002;
		lng = parseFloat(lng) + 0.002;
		return getNewPoint(lat,lng); 
	}
	else
	*/
		return p;
}

function checkPfmarkers(cl_id) {
		var i = 0;
		while ( i <  pfMarkers.length ) {
				if ( pfMarkers [ i ].client_id == cl_id )
						return true;
				i++;
		}
		return false;
}

function checkSamePoints(p) {
				var i = x = 0;
				var sp = document.getElementById('pf');
				var isfirst = true;
				while ( i <  pfMarkers.length ) 
				{
							if (  pfMarkers[ i ].marker.getPoint().equals( p ) )
							{
											if (isfirst) {
													x = 0;
													isfirst = false;
											}
											var atje = document.createElement("a");
											atje.innerHTML = "&nbsp;" + x ;
											atje.href = "javascript:openMarkerWindow(" + i + ")";
											sp.appendChild(atje);
											x++;
							}
							i++;
				}
			
}

function openMarkerWindow(toonDeze) {
				GEvent.trigger(pfMarkers[ toonDeze ].marker, "click");
}

function samePointPfmarkers() {
		var i = 0;
		while ( i <  pfMarkers.length ) 
		{
				var ii = 0;
				while ( ii <  pfMarkers.length ) 
				{
							if (i != ii && pfMarkers[ i ].marker.getPoint().equals( pfMarkers[ ii ].marker.getPoint() ) )
							{
									pfMarkers[ i ].samePoints.push(ii);
							}
					ii++;
				}
				i++;
		}
}

function removePartnerseekerMarkers() {
		var i = 0;
		while ( i <  pfMarkers.length ) {
			map.removeOverlay( pfMarkers [ i ].marker );
			i++;
		}
		pfMarkers = [];
}

function saveCurrentRoute() {
	if (newr)
	{
					var waypoints = newr.GetWaypoints() ;
					route = [];
				  elev8n = [];
					var prevAlt = 0;
					if ( newr && waypoints.length > 0 ) {
							for (i in waypoints)
							{
								route.push ( { x: waypoints[i].lng , y : waypoints[i].lat } );
								if ( waypoints[i].height == undefined )
										elev8n.push ({ 'gtopo30': prevAlt });
								else {
										elev8n.push ({ 'gtopo30': waypoints[ i ].height })
										prevAlt = waypoints[ i ].height;
								}
							}
							try {
											currentRoute.description = newr.FirstPoint.StartInfo.Place;
											currentRoute.postalcode = newr.FirstPoint.StartInfo.Zipcode;
											currentRoute.placename = newr.FirstPoint.StartInfo.Place;
											currentRoute.region = newr.FirstPoint.StartInfo.Region;
											currentRoute.countrycode = newr.FirstPoint.StartInfo.CountryCode;
							}
							catch(e) {
											currentRoute.description = currentRoute.postalcode = currentRoute.placename = currentRoute.region = currentRoute.countrycode = "";
							}

							routeDistance  = newr.GetDistance()/1000;
					}
	}

	if (currentRoute.id || route.length != 0) {
		saveRoute(currentRoute.id);
	} else {
		alert('You must be working with a route to save it');
	}

}

function empty () {
;
}

function getSelectList(type, value) {
var aGround = new Array ('asphalt','grass','gravel','mixture','sand');
var aEnv = new Array ('town','country','woodland','dunes','mountains','hilly');

if (type=='underground')
	var aOptions = aGround;
else
	var aOptions = aEnv;

var html = "<select name='" + type + "' >";
		for (i=0 ; i< aOptions.length ; i++) {
			if (aOptions[i]==value) 
					selected = "selected='selected'";
			else 
					selected = "";
			html += "<option value='"+aOptions[i]+"' "+selected+">"+aOptions[i]+"</option>";
		}
		html += "</select>";
	return html;
}

function getRouteForm(rid) {

  checkStreetview();
	if (rid == null || (currentRoute.fk_client_id == client_id && rid >0)) { 

  var html =	"<h2>Route information</h2>";
	if (rid ) {
				;
	}
	else {
				html += "<br /><p><a class='go' href='javascript:document.frmRoute.submit();' >Add</a></p>";
	}

	html +=  getHtmlRouteExtras ();

	currentRoute.toString();
	html += "<form name='frmRoute' action='saveRoute.php' method='post' enctype='multipart/form-data' >";
	if (currentRoute.fk_photo_id > 0) 
			html += "<center><img onclick='javascript:showPhoto(" + currentRoute.fk_photo_id+");'src='thumb.php?id=" + currentRoute.fk_photo_id + "' title='thumbnail route' /></center>" ;

	html += "<fieldset >";
	html += "<label for='description' >Name</label><input type='text' name='description' value='"+currentRoute.description.htmlSpecialChars()+"' />";
	html += "<label for='postalcode' >Post code</label><input type='text' name='postalcode' value='"+currentRoute.postalcode +"' />";
	html += "<label for='placename' >Town/city</label><input type='text' name='placename' value='"+currentRoute.placename.htmlSpecialChars()+"' />";
	html += "<label for='region' >Area</label><input type='text' name='region' value='"+currentRoute.region.htmlSpecialChars()+"' />";

	html += "<label for='underground' >Terrain</label>" + getSelectList('underground',currentRoute.underground);
	html += "<label for='environment' >Surrounding area</label>" + getSelectList('environment',currentRoute.environment);

	currentRoute.distance = (currentUnit == "km" ? fix(routeDistance,1) : fix((routeDistance*MILESASKM),1));

	html += "<label for='distance' >distance</label><input type='text' disabled='disabled' value='"+currentRoute.distance+"' />";
	html += "<label for='countrycode' >Country code</label><input type='text' name='countrycode' size='2' value='"+currentRoute.countrycode.htmlSpecialChars()+"' />";
	html += "<label for='file' >upload a photo</label><input class='breed' type='file' name='photo' value='upload a photo' />";

	html += "<label>Public</label><input class='chk' type='radio' name='private' value='N' "+ (currentRoute.private == "N" ? "checked='checked'": "")+" />";
	html += "<br /><label>Private</label><input class='chk' type='radio' name='private' value='J' "+ (currentRoute.private == "J" ? "checked='checked'": "")+"/>";
	if (rid) {
		html += "<input type='hidden' name='id' value='"+rid+"'>";
	}
	html += "<input type='hidden' name='miles' value='"+(currentUnit == "miles" ? fix(routeDistance,1) : fix((routeDistance/MILESASKM),1))+"'>";
	html += "<input type='hidden' name='distance' value='"+(currentUnit == "km" ? fix(routeDistance,1) : fix((routeDistance*MILESASKM),1))+"'>";
	var qryString = "";
	for (var i=0;i <= route.length-1;i++) {
		qryString += route[i].x + "," + route[i].y + ",";
	}
	html += "<input type='hidden' name='route' value='"+qryString+"'>";

	var alti = 0;
	for (var i=0;i <= route.length-1;i++) {
		if (elev8n.length > 0 ) {
			if ( elev8n[i].gtopo30 == undefined ) 
					alti = 0;
			else
					alti = 	elev8n[i].gtopo30;
		}
		else
			alti = 0;
			
			html += "<input type='hidden' name='elev8n[]' value='"+ alti +"'>";
	}

	html += "</fieldset>";
	html += "</form>";
	if (rid ) {
		html += "<br /><p><a class='go' href='javascript:document.frmRoute.submit();'>Change</a></p>";
	}
	else {
				html += "<br /><p><a class='go' href='javascript:document.frmRoute.submit();' >Add</a></p>";
	}
	}
	else {
	var html =	"<h2>Route information</h2>";
	if (currentRoute.fk_photo_id > 0) 
			html += "<center><img onclick='javascript:showPhoto(" + currentRoute.fk_photo_id+");'src='thumb.php?id=" + currentRoute.fk_photo_id + "' title='thumbnail route' /></center>" ;

	html +=  getHtmlRouteExtras ();

	html += "<ul>";
	html += "<li>Name: "+cStr(currentRoute.description) + "</li>";
	html += "<li>Post code: "+cStr(currentRoute.postalcode) + "</li>";
	html += "<li>Owner: "+currentRoute.author_name + "</li>";
	html += "<li>Area: "+cStr(currentRoute.region) + "</li>";
	html += "<li>Place: "+cStr(currentRoute.placename) + "</li>";
	html += "<li>Terrain: "+currentRoute.underground + "</li>";
	html += "<li>Surrounding area: "+currentRoute.environment + "";
	//currentRoute.distance = (currentUnit == "km</li>" ? fix(currentRoute.distance,1) : fix((currentRoute.distance*MILESASKM),1));
	html += "<li>distance: "+currentRoute.distance + "</li>";
	html += "<li>Country code: "+cStr(currentRoute.countrycode) + "</li>";
  var oordeel = isNaN(Math.round(currentRoute.rate/currentRoute.rate_counter))?"Not assessed":Math.round(currentRoute.rate/currentRoute.rate_counter);
	html += "<li>Rating: "+ oordeel + "</li>";
	html += "<li>Public URL: <br />"+ SITEURL +  "routes/route.php?route_id=" + currentRoute.id + "</li>";
	html += "</ul>";
	}
	return html;
}

function getWaypointResponse (request,marker) {
			obj = xml2json.parser(request.responseText);
		
			if (obj.response.type=='success')	 {
					respObj =  obj.response.waypoint;
					currentWaypoint.id = respObj.id;
					currentWaypoint.latitude = respObj.latitude;
					currentWaypoint.longitude = respObj.longitude;
					currentWaypoint.comment = cStr(respObj.comment);
					currentWaypoint.fk_photo_id = respObj.fk_photo_id;
					currentWaypoint.idx = respObj.idx;
  				html = getWaypointForm() ;
					marker.openInfoWindowHtml (html);
					hideStatusDraw();
			}
			else {
					alert (obj.response.message);
			}

}

function getWaypointForm() {

	if (currentRoute.id > 0 && currentRoute.fk_client_id == client_id) {
	var html = "<h2>";
	html += "Comment on this waypoint.";
	html += "</h2>";
	html += "<form name='frmWaypoint' action='saveWaypoint.php' method='post' enctype='multipart/form-data'>";


	if (currentWaypoint.fk_photo_id > 0) 
			html += "<center><img onclick='javascript:showPhoto(" + currentWaypoint.fk_photo_id+");' src='thumb.php?id=" + currentWaypoint.fk_photo_id + "' title='thumbnail route' /></center>" ;
	html += "<fieldset style='width: 440px;' >";
	html += "<label for='comment' >Comment</label><textarea name='comment'  onfocus='this.select()'>" + currentWaypoint.comment +"</textarea>";
	html += "<label for='photo' >Graphic</label><input type='file' class='breed' name='photo' value='foto' />" ;


	html += "<input type='hidden' name='route_id' value='"+currentRoute.id+"'>";
	html += "<input type='hidden' name='id' value='"+currentWaypoint.id+"'>";
	html += "<input type='hidden' name='idx' value='"+currentWaypoint.idx+"'>";
	html += "</fieldset>";
	html += "</form>";
	html += "<br /><a href='javascript:document.frmWaypoint.submit();' class='gosave' >Save</a>";
	} 
	else {
	var html = "<h2>Waypoint information</h2>";
	if (currentWaypoint.fk_photo_id > 0) 
			html += "<center><img onclick='javascript:showPhoto(" + currentWaypoint.fk_photo_id+");' src='thumb.php?id=" + currentWaypoint.fk_photo_id + "' title='thumbnail route' /></center>" ;
	html += ""+ currentWaypoint.comment +"";
	}
	return html;
}

function showPhoto(id) {
			html = "<img width='350' src='photo.php?id=" + id + "' title='route foto' />" ;
			map.openInfoWindowHtml (mapLocByFraction(2/3,0.5), html);
			return false;
}

function saveRoute(rid) {
	var html =  getRouteForm(rid);

	ajaxCall("getClientID.php?1=1",responseClientID,1,0);
	map.openInfoWindowHtml (mapLocByFraction(2/3,0.5), html);
	return false;
}

function doAjaxDeleteRoute (id) {
	ajaxCall("deleteRoute.php?id=" + id,responseDeleteRoute,1,0);
}

function doAjaxCallRating() {
  url = "";
	if (document.forms.ratingForm) {
					obj = document.forms.ratingForm;
					with (obj) {
									for (i=0 ; i< elements.length ; i++) {
											url += "&" + elements[i].name + "=" + encodeURIComponent(elements[i].value);
									}
					}
	}

	ajaxCall("rating.php?route_id=" + currentRoute.id + url, function(req) { getRatingDiv().innerHTML=req.responseText; } ,1,0);
	$('favLink').style.display = 'none';
}

function replaceDivContents(xmlHttpRequest, dstDivId)
{
 //var dstDiv = document.getElementById(dstDivId);
 setInner(dstDivId, xmlHttpRequest.responseText);
}

function responseDeleteRoute(request) {
			var obj = xml2json.parser(request.responseText );
		
							if (obj.response.type=='success')	 {
									respObj =  obj.response.route;
									currentRoute.id = respObj.id;
									resetMap();
									alert ('Route deleted');
							}
							else {
									alert (obj.response.message);
							}
}

function doAjaxLoadRoute (id) {
	changeBodyClass('standby', 'loading');
	ajaxCall("loadRoute.php?id=" + id, responseLoadRoute,1,0);
}

function responseClientID (request) {

			var obj = xml2json.parser(request.responseText );

      if (obj.response == undefined )
					return;

			if ( obj.response.type=='success')	 {
						// dit is de ingelogde gebruiker
						client_id = obj.response.client_id;
						echo (client_id);
			}
			else
			{
					toolbar.hideToolbar_(toolbar.container);
					client_id = -1;
			}
}

function responseLoadRoute(request) {
			obj = xml2json.parser(request.responseText );
		
			changeBodyClass('loading', 'standby');
			if (obj.response.type=='success')	 {
					rrROUTEVIEW=DETAIL;
					respObj =  obj.response.route;
					currentRoute.id = respObj.id;
					currentRoute.description = cStr(respObj.description);
					currentRoute.distance = respObj.distance;
					currentRoute.underground = cStr(respObj.underground);
					currentRoute.environment = cStr(respObj.environment);
					currentRoute.postalcode = cStr(respObj.postalcode);
					currentRoute.placename = cStr(respObj.placename);
					currentRoute.region = cStr(respObj.region);
					currentRoute.countrycode = cStr(respObj.countrycode);
					currentRoute.fk_client_id = respObj.fk_client_id;
					currentRoute.fk_photo_id = respObj.fk_photo_id;
					currentRoute.author_name = cStr(respObj.author_name);
					currentRoute.rate = respObj.rate;
					currentRoute.rate_counter = respObj.rate_counter;
					currentRoute.private = respObj.private;
					currentRoute.avg_altitude = parseInt(respObj.avg_altitude);
	
					route = [];
					elev8n = [];
					var alt = 0;
					with (obj.response.route.waypoints) {
					for (i = 0; i<route_waypoint.length; i++) {
							var point = new GLatLng(route_waypoint[i].latitude,route_waypoint[i].longitude);
							route.push(point);
							route[route.length-1].comment=route_waypoint[i].comment;
							route[route.length-1].fk_photo_id=route_waypoint[i].fk_photo_id;
							route[route.length-1].show=route_waypoint[i].show;
								alt = parseInt(route_waypoint[i].gtopo30);
							if ( isNaN(alt) )
								alt = 0;
							else
								alt = route_waypoint[i].gtopo30;
							elev8n[i] = { "gtopo30": alt , "longitude" : route_waypoint[i].longitude, "latitude" : route_waypoint[i].latitude };
							}
					}

					drawRoute(route);
					$('favLink').style.display = 'inline';
					$('speedLink').style.display = 'none';
					ri.hideRouteInfoDiv_();

					if ( typeof(flickr_TYR.removeMarkers_) !== undefined ) {
								flickr_TYR.removeMarkers_();
								flickr_TYR.wpIdx = 0;
					}
			}
			else {
					echo (obj.response.message);
			}

			loadPhotosWithinMapBounds();

			loadLogbookNotes();
			if (client_id >0) ;
			else toolbar.hideToolbar_();
}

function doAjaxGetLocationInfo(point) {
	url = "getLocationinfo.php?latitude=" + point.lat() + "&longitude=" + point.lng();
	ajaxCall(url,setLocationResponse,1,0);
}

function setLocationResponse(request) {

			obj = xml2json.parser(request.responseText);
			elev8n = [];
			if (obj.response.type=='success')	 {
					respObj =  obj.response.route;
					currentRoute.region = respObj.region;
					currentRoute.placename = respObj.placename;
					currentRoute.countrycode = respObj.countrycode;
					currentRoute.postalcode = respObj.postalcode;
					currentRoute.description = respObj.description;
			}
			else {
					alert (obj.response.message);
			}
}

function doAjaxSave (url) {
  url +=    "?q";
	urluser = "";
  objuser = document.forms.frmRoute;
  with (objuser) {
          for (i=0 ; i< elements.length ; i++) {
              if (elements[i].type!='submit' && elements[i].type!='select-one') {
									eval ("currentRoute." + elements[i].name + "='" + elements[i].value + "'" );
									
							}
              if (elements[i].type=='checkbox') {
                        if (elements[i].checked)
                          urluser += "&" + elements[i].name + "=" + encodeURIComponent(elements[i].value);

              }
              else if (elements[i].type=='select-one') {
                    for (ii=0 ; ii < elements[i].options.length; ii++) {
                        if (elements[i].options[ii].selected) {
                          urluser += "&" + elements[i].name + "=" + elements[i].options[ii].value;
													eval ("currentRoute." + elements[i].name + "='" + elements[i].options[ii].value + "'" );
												}
                    }
                  }
                  else
                      urluser += "&" + elements[i].name + "=" + encodeURIComponent(elements[i].value);
          }
  }
  url = url + urluser;
	ajaxCall(url,saveResponse,1,0);
}

function doAjaxSaveWaypoint (url) {
  url +=    "?q";
	urluser = "";
  objuser = document.forms.frmWaypoint;
  with (objuser) {
          for (i=0 ; i< elements.length ; i++) {
              if (elements[i].type!='submit') {
									eval ("currentRoute." + elements[i].name + "='" + elements[i].value + "'" );
									
							}
              urluser += "&" + elements[i].name + "=" + encodeURIComponent(elements[i].value);
          }
  }
  url = url + urluser;
	ajaxCall(url,saveWaypointResponse,1,0);
}

function saveWaypointResponse(request) {
			map.closeInfoWindow();

			obj = xml2json.parser(request.responseText);
		
			if (obj.response.type=='success')	 {
					respObj =  obj.response.waypoint;
					currentWaypoint.idx = respObj.idx;
					currentWaypoint.comment = respObj.comment;
					currentWaypoint.fk_photo_id = respObj.fk_photo_id;
					var dum = 'waypoint' + currentWaypoint.idx; 
					setInner(dum,currentWaypoint.comment); 
			}
			else {
					alert (obj.response.message);
			}
} 

function saveResponse(request) {
			map.closeInfoWindow();
			obj = xml2json.parser(request.responseText);
		
			if (obj.response.type=='success')	 {
					newRoute =  obj.response.route;
					currentRouteId = newRoute.id;
					currentRouteName = newRoute.description;

					currentRoute.id = newRoute.id;
					currentRoute.description = newRoute.description;
					drawRoute(route);
			}
			else {
					alert (obj.response.message);
			}
} 

function emailRoute(rid) {
	var html = "<h1>TODO</h1>";
	map.openInfoWindowHtml (mapLocByFraction(2/3,0.5), html);
	return false;
}
function removeRoute(rid) {
	if (!confirm('Are you sure you want to delete this route?')) {
		return false;
	}
	var dataUrl = '/functions/act_deleteRoute.cfm?r='+rid;
	urchinTracker('/delRoute.cfm');
	//perform ajax call
	ajaxCall(dataUrl,deleteRoute,1,0,rid);
	return false;
}

function editWaypoint() {

}

function rankStar() {
alert (this.id);
}

function toggleSortDir() {
	sortDir = (sortDir=='ASC'?'DESC':'ASC');
}

function createRouteListTable (tableId,routesFound, onclick_add_marker) {

	var aRouteLayout = {"field": ['description','distance',  'date_creation','environment' , 'underground', 'rate', 'postalcode', 'region', 'placename'],
											"label": ["Name","distance",  "Added","Surrounding area", "Terrain", "Rating", "Post code", "Area", "Town/city"]
									 };

	var always = new Array ('description'); 

	var aShow = aRouteLayout.field.slice (offsetRouteList, offsetRouteList+1);
	var aShowLabel = aRouteLayout.label.slice (offsetRouteList, offsetRouteList+2);

	var newTable = document.createElement('table');
	newTable.className = 'waypointTable';
	var newBody = document.createElement('tBody');

	newTable.appendChild(newBody);
	newTable.id = tableId;
	newTable.border = '0';
	newTable.cellSpacing = '0';
	newTable.width = '100%';

	
	var r = document.createElement('tr');
		r.className = 'waypointRow';
    cn = document.createElement('th');
		cn.className = 'waypointHeaderCell';
		pn = document.createElement('p');
		pn.id = 'tableTitle';
		cn.colSpan="4";
		tn = document.createTextNode('');

		pn.appendChild(tn);	
		cn.appendChild(pn);
		r.appendChild(cn);
		newBody.appendChild(r);

/////eerste kolom is vast de andere zijn flexibel 
	var r2  = document.createElement('tr');
		r2.className = 'waypointRow';
    cn = document.createElement('th'); cn.align="left";
		cn.className = 'waypointHeaderCell';
		cn.style.background = "#8F8F8F";
		cn.colSpan = '2';
    tn = document.createTextNode('Name');

		cn.onclick = function () {
										toggleSortDir();
										sortBy = 'description';
										if ( globalSearchString == null && globalFilter.type == null) 
											loadRoutes();
										else 
											doAjaxZoek();
						}
		cn.onmouseover = function () {
						cn.style.background = "#8F8F8F";
						}
		cn.onmouseout = function () {
						cn.style.background = "#8F8F8F";
						}


		var shiftCol = document.createElement('img');
		shiftCol.align = 'right';
		shiftCol.className = 'rotoggle';

		shiftCol.src = imagePath + 'arrow.r.gif';
		shiftCol.onclick = function () { 
						offsetRouteList = (offsetRouteList < aRouteLayout.field.length-2? ++offsetRouteList: 1); 
						var routeListDiv = $('routeResults');
						routeListDiv.innerHTML = "";

						var routeListTable = createRouteListTable('zoekTabelDiv', routesFound, onclick_add_marker);
						routeListDiv.appendChild(routeListTable);
						setRouteListTitle();
		}
		shiftCol.title = 'Move column fields'; 

		cn.appendChild(shiftCol);

		cn.appendChild(tn);
		r2.appendChild(cn);


		for (x=0 ; x<aShow.length ; x++) {

    				var ca = document.createElement('th'); ca.align="left";
						ca.className = 'waypointHeaderCell';
						ca.style.background = "#8F8F8F";
						ca.id = aShow[x];
						ta = document.createTextNode(aShowLabel[x]);
						ca.onclick = function () {
										toggleSortDir();
										sortBy = this.id;
										if ( globalSearchString == null && globalFilter.type == null) 
												loadRoutes();
										else
												doAjaxZoek();
						}
						ca.onmouseover = function () {
						this.style.background = "#8F8F8F";
						}
						ca.onmouseout = function () {
						this.style.background = "#8f8f8f";
						}

						ca.appendChild(ta);	
						/*
						if (x==aShow.length-1)
							ca.appendChild(shiftCol);
						*/

						r2.appendChild(ca);
		}

	newBody.appendChild(r2);
	
	for (var i=0; i < routesFound.length && (rrMODUS == MY || i < MAX_IN_ROUTELIST) ; i++) {
			var r  = document.createElement('tr');
			r.className = 'waypointRow';
		  r.id = 'route'+ routesFound[i].id;
			r.onmouseover = function() { 
						ri.clearRouteInfo_();
						ri.hideRouteInfoDiv_();

								this.style.background = BGCOLOR_MO; 
								var dum = this.id;
								var route_id =  dum.substring(5) ;
								ri.writeRouteInfo_(route_id);
								ri.showRouteInfoDiv_();

			}
			r.onmouseout = function() { 
						this.style.background = '#ffffff'; 
			}

						var thumbRoute = document.createElement("img");
						thumbRoute.className = 'waypointImg';
						if (routesFound[i].fk_photo_id > 0) {
											thumbRoute.src = "thumb.php?id="+routesFound[i].fk_photo_id;
						} 
						else {
											thumbRoute.src = imagePath + "waypointimg_placeholder.gif";
						}
							
			var ci = document.createElement('td');
			ci.appendChild(thumbRoute);
			r.appendChild(ci);

		  var ca = document.createElement('td'); var ta = document.createTextNode(routesFound[i].description);
					ca.className = 'waypointCell';
					/*
					if (onclick_add_marker) {
						ca.onclick = function() { alert(this.id);}
					}
					*/
					ca.appendChild(ta); 
					r.appendChild(ca);

					for (x=0 ; x<aShow.length ; x++) {

    				var ca = document.createElement('td'); ca.align="left";
						ca.className = 'waypointCell';
						eval ('aValue = routesFound['+i+'].'+ aShow[x]);
						ta = document.createTextNode(cStr(aValue));


						ca.appendChild(ta);	
						r.appendChild(ca);
					}

			/*
		  var cb = document.createElement('td'); var tb = document.createTextNode(routesFound[i].distance);
		  var cc = document.createElement('td'); var tc = document.createTextNode(routesFound[i].underground);

			cb.appendChild(tb); r.appendChild(cb);			
			cc.appendChild(tc); r.appendChild(cc);
			*/
			newBody.appendChild(r);
		}
			return newTable;
}

function getRatingDiv () {
		if (document.getElementById('ratingDiv'))
				return document.getElementById('ratingDiv');
		else {
						var ratingDiv = document.createElement('div');
						ratingDiv.id = 'ratingDiv';
						rn = document.createTextNode('-');
						ratingDiv.appendChild(rn);
			return ratingDiv;
		}
}

function getLogsDiv () {
		if (document.getElementById('logsDiv'))
				return document.getElementById('logsDiv');
		else {
						var logsDiv = document.createElement('div');
						logsDiv.id = 'logsDiv';
						logsDiv.style.display = 'none';
						rn = document.createTextNode('-');
						logsDiv.appendChild(rn);
			return logsDiv;
		}
}

function drawRoute(rt) {
	map.clearOverlays();

	if (!recording) map.setCenter(new GLatLng(rt[0].y, rt[0].x), 14);

	var saveButton = $('saveRouteLink');
	var distThisLeg = 0;
	var totDistance = 0;

	var markerText = "";
	var startOverlay = null;
	var routeListDiv = $('routeResults');
	routeListDiv.innerHTML = "";

	var ratingDiv = getRatingDiv();
	routeListDiv.appendChild(ratingDiv);

	var logsDiv = getLogsDiv();
	routeListDiv.appendChild(logsDiv);

	var brEl = document.createElement('br');
		routeListDiv.appendChild(brEl);
		
	//initialiseren
	if (document.getElementById('resultTabel')) routeListDiv.removeChild('resultTabel');

	var headerTable = document.createElement('table');
  headerTable.className = 'waypointTable';
	var headerBody = document.createElement('tBody');
	headerTable.appendChild(headerBody);
	
	var newTable = document.createElement('table');
  newTable.className = 'waypointTable';
	var newBody = document.createElement('tBody');
	newTable.appendChild(newBody);
	newTable.id = 'resultTabel';
	newTable.border = '0';
	newTable.cellSpacing = '0';
	newTable.width = '100%';

	var r = document.createElement('tr');
		r.className = 'waypointRow';
		ci = document.createElement('th');
    cn = document.createElement('th');
		pn = document.createElement('p');
		pn.id = 'routeName';
		cn.colSpan="2";

		tn = document.createTextNode(currentRoute.description + ' (' + currentRoute.distance + ')');

		var thumbRoute = document.createElement("img");
		thumbRoute.className = 'waypointImg';
		if (currentRoute.fk_photo_id > 0) {
			thumbRoute.src = "thumb.php?id="+currentRoute.fk_photo_id;
		} 
		else {
			thumbRoute.src = imagePath + "waypointimg_placeholder.gif";
		}
		ci.appendChild(thumbRoute);

		pn.appendChild(tn);	
		cn.appendChild(pn);
		r.appendChild(ci);
		r.appendChild(cn);
		headerBody.appendChild(r);

	var r2  = document.createElement('tr');
		r2.className = 'waypointRow';
    tn = document.createTextNode('Waypoint');


    ta = document.createTextNode('Dist.');

    tc = document.createTextNode('Time');
	//create holders
		r  = document.createElement('tr');
		r.className = 'waypointRow';
    cn = document.createElement('th'); cn.align="left";
		cn.colSpan="2";
		cn.className = 'waypointHeaderCell';
		cn.onmouseover= function () { melding ('Waypoint summary')};	

    ca = document.createElement('th'); ca.align="left";
		ca.className = 'waypointHeaderCell';
		ca.onmouseover= function () { melding ("Distance from start to waypoint")};	

    cc = document.createElement('th'); cc.align="left";
		cc.className = 'waypointHeaderCell';
		cc.onmouseover= function () { melding ("Calculating intermediate times with input speed (standard 10km/h)")};	

	//add contents to holders
	cn.appendChild(tn);
	ca.appendChild(ta);	
	cc.appendChild(tc);	

	//add cells to row
	r2.appendChild(cn);
	r2.appendChild(ca);
	r2.appendChild(cc);

	newBody.appendChild(r2);
	
	var mileNum = 1;
	// doorlopen van alle waypoints ; output naar tabel in sidebar en tekenen op kaart
	for (var i=0;i <= rt.length-1;i++) {
		if (i==0) {			
			//do nothing yet
		} else {
			
			distThisLeg = calcDist(rt[i].x,rt[i].y,rt[i-1].x,rt[i-1].y);
			totDistance = distThisLeg + totDistance;

			// Dit is de output naar het overzicht in de side bar
			if (recording || (rt[i].show == '1' || rt.length-1 == i)) {
							//create holders
							var r  = document.createElement('tr');
							r.id = 'waypoint'+i;
							r.className = 'waypointRow';
								var ci = document.createElement('td');
								var cn = document.createElement('td');
								cn.className = 'waypointCell';
										cn.i = 'waypoint' + i;
								var ca = document.createElement('td');
								ca.className = 'waypointCell';
								var cb = document.createElement('td');
								cb.className = 'waypointCell';
								var cc = document.createElement('td');
								cc.className = 'waypointCell';
								//var cd = document.createElement('td');
							//create contents
								pn = document.createElement('p');
								pn.style.margin ='0 0 0 0.5em';
								pn.className = 'waypointCellTxt';
								var thumbWp = document.createElement("img");
								thumbWp.className = 'waypointImg';
								if (rt[i].fk_photo_id > 0) {
											thumbWp.src = "thumb.php?id="+rt[i].fk_photo_id;
									}
									else {
											thumbWp.src = imagePath + "waypointimg_placeholder.gif";
								}
								ci.appendChild(thumbWp);
								//var tn = document.createTextNode(' '+ i + '. ' + cStr(rt[i].comment));
								var tn = document.createTextNode(cStr(rt[i].comment));
								var ta = document.createTextNode(fix(totDistance,2)+ " " + currentUnit);
								var tb = document.createTextNode(getFixTime(totDistance) + "     ");
							//add contents to holders
							pn.appendChild(tn);
							cn.appendChild(pn);
							cb.appendChild(tb);
							ca.appendChild(ta);
							//laatste waypoint mag als de route nog niet is opgeslagen  worden verwijderd
							if (i == rt.length-1 && recording && currentRoute.id==null ) {
									var trashIcon = document.createElement("img");
											trashIcon.src = imagePath + "trash.gif";
											trashIcon.alt= "Delete waypoint";
											trashIcon.title= "Delete waypoint";
											trashIcon.onclick = function () { route.pop(); 
												drawRoute(route); } 
											cb.appendChild(trashIcon);
							}
							//add cells to row
							r.appendChild(ci);
							r.appendChild(cn);
							r.appendChild(ca);
							r.appendChild(cb);			
							newBody.appendChild(r);
			}

			routeListDiv.appendChild(headerTable);
			routeListDiv.appendChild(newTable);

			var commonTitle = fix(totDistance,2) + " " + currentUnit;
			var commonText =  "<p>Time " + getFixTime(totDistance) + " ";
			/*
			if (elev8n[i-1] > 0 || elev8n[i-1] < 0) {
				commonText += "Elevation " + elev8n[i-1] + " feet ";
			}
			*/
			commonText += "</p>"
			if (i == rt.length-1) {
				markerText = "<h3>Finish" + currentRoute.description + "</h3>" + commonText;
				map.addOverlay(createMarker(rt[i],markerText,finishIcon,'waypoint',i, 'waypoint' + i , false, [] ));
			} else {
				if (recording || (rt[i].show == '1' || rt.length-1 == i)) {
					markerText = "<h3>Waypoint" + i + "</h3>" ;
					map.addOverlay(createMarker(rt[i],markerText,base_marker,'waypoint',i, 'waypoint' + i , false, []));
				}
			}	
			
			var vectorX = (rt[i].x - rt[i-1].x) / distThisLeg;
			var vectorY = (rt[i].y - rt[i-1].y) / distThisLeg;
			var stpoint = new GPoint(rt[i-1].x,rt[i-1].y);
			var stDist = totDistance-distThisLeg;
			for (stDist; stDist <= totDistance; ) {
				var distToNextMile = Math.floor(stDist+1.0)-stDist;
				stpoint.x = stpoint.x+(vectorX*distToNextMile);
				stpoint.y = stpoint.y+(vectorY*distToNextMile);
				if (Math.ceil(stDist+0.000001) <= Math.floor(totDistance)) {
					if (mileNum < 30) createMileMarker(stpoint,mileNum);
					mileNum=mileNum+1;
				}
				stDist=stDist+distToNextMile;
				
			}
			var points = [];
			points.push(rt[i]);
			points.push(rt[i-1]);
			points.sort(function(p1,p2) { return p1.x - p2.x });
			map.addOverlay(new GPolyline(points, LINECOLOR,4,0.8));
		}
	// einde loop door alle waypoints
	}
	routeDistance = totDistance;

	var totDist = fix(routeDistance,2);
	/*$('currentDist').innerHTML = totDist + " <a href='' onclick='return toggleUnits()'>" + currentUnit + "</a>"; */
	$('currentDist').innerHTML = totDist + currentUnit;
	$('currentTime').innerHTML = 'End time: ' + getFixTime(totDist) + 'min';
	if (currentUnit == "miles") {
		$('currentSpeed').innerHTML = fix(currentSpeed,1) + " mph";
		//$('currentCal').innerHTML = fix((totDist*MILESASKM) * (currentWeight/2.2) * 1.036,1);
	} else {
		$('currentSpeed').innerHTML = fix(currentSpeed,1) + " km/h ";
		//$('currentCal').innerHTML = fix(totDist * (currentWeight/2.2) * 1.036,1);
	}

	if ( currentRoute.id > 0 )
			markerText = "<h3><img src='" + imagePath + "start.png' title='Start'></h3>" + getRouteForm(currentRoute.id);
	else
			markerText = "<h3><img src='" + imagePath + "start.png' title='Start'></h3> <p>Draw the full route and then save it.</p>"  ;

  var infoTabs = [
			new GInfoWindowTab("Info",markerText, function() { this.selectTab(0); } ),
			new GInfoWindowTab("Responses","<div id='routereactions'></div>", function () { callAjaxReactions(); this.selectTab(1);} )
	];

	startOverlay = createMarker(rt[0],markerText,startIcon, null, null, 'routeName', true , infoTabs );
	map.addOverlay(startOverlay);

	if (currentRoute.id > 0 && currentRoute.fk_client_id == client_id) {
			;
	}

  if (!recording)
	{
		GEvent.trigger(startOverlay, "click");
		doAjaxCallRating();
	}
	
	//toggleSubTabs('routesSubNav','tab_routes_current','routes');
}

function createMileMarker(stpoint, mileNum) {
					var marker = new GMarker(stpoint,mileIcon[mileNum]);
					GEvent.addListener(marker, 'mouseover', function() { melding(mileNum + ' km waypoint')} );
					map.addOverlay(marker);
}

function resetMap() {
		map.clearOverlays();
		route = [];
		setInner('routeResults','');
		map.setCenter(new GLatLng(centerLatitude, centerLongitude), map.getZoom()-2);
}

function cancelRoute() {
	if (confirm("End drawing session without saving?")) {
		map.clearOverlays();
		route = [];
		reinitGMap();
	}
	return false;

}

function setElevation(http,pointNum) {
	try {
		eval( 'elev8n[' + pointNum + '] = ' +  http.responseText ) ;
	}
	catch(e) {
			elev8n[ pointNum ] = { "gtopo30" : 0 };
	}
	return false;
}

function lookupElevation(pointNum) {
	var lng = route[pointNum].x;
	var lat = route[pointNum].y;
	return doLookupElevation(lng,lat,pointNum);
}	

function doLookupElevation(lng,lat,pointNum) {
	var dataUrl = 'getElevation.php?lat='+lat+'&lng='+lng;
	//perform ajax call
	ajaxCall(dataUrl,setElevation,1,0,pointNum);	
	return false;
}	


function RTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0){
	return"";
	}
	var iTemp = v_length -1;
	
	while(iTemp > -1){
	if(VALUE.charAt(iTemp) == w_space){
	}
	else{
	strTemp = VALUE.substring(0,iTemp +1);
	break;
	}
	iTemp = iTemp-1;
	
	} //End While
	return strTemp;

} //End Function

function LTrim(VALUE){
	var w_space = String.fromCharCode(32);
	if(v_length < 1){
	return"";
	}
	var v_length = VALUE.length;
	var strTemp = "";
	
	var iTemp = 0;
	
	while(iTemp < v_length){
	if(VALUE.charAt(iTemp) == w_space){
	}
	else{
	strTemp = VALUE.substring(iTemp,v_length);
	break;
	}
	iTemp = iTemp + 1;
	} //End While
	return strTemp;
} //End Function

function Trim(TRIM_VALUE){
	if(TRIM_VALUE.length < 1){
	return"";
	}
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	if(TRIM_VALUE==""){
	return "";
	}
	else{
	return TRIM_VALUE;
	}
} //End Function

function calcDist(lon1,lat1,lon2,lat2) 
{	
	var r = 3963.0;
	var multiplier = currentUnit == "miles" ? 1 : MILESASKM;
	var dist = multiplier * r * Math.acos(Math.sin(lat1/57.2958) * Math.sin(lat2/57.2958) + Math.cos(lat1/57.2958) * Math.cos(lat2/57.2958) * Math.cos(lon2/57.2958 - lon1/57.2958));
	if ( isNaN(dist) ) 
			return 0;
	else
			return dist;
}

function getFixTime(dist) {
	var minutes = dist * minutesPerUnit;
	var hours = Math.floor(minutes/60);
	var remMins = '' + Math.round(minutes - (hours*60));
	var displayMins = remMins.length == 2 ? remMins : "0"+remMins;
	return hours + ":" + displayMins;
}

function fix(num,dp) {
	return Math.floor(num * Math.pow(10,dp)) / Math.pow(10,dp)
}

function checkLen(obj,msg) {
	if (!obj.value.length || obj.value == msg) {
		obj.className = "dataOmitted";
		obj.value = msg;
	} else {
		obj.className = "dataEntered";
	}
}

function reinitGMap() {
	window.location.href = currentFile+"?longitude="+map.getCenter().lng()+"&latitude="+map.getCenter().lat()+"&zoom="+map.getZoom();
	return false;
}

function createMarker(point, mtext, icon, type, idx, domId, isFirst, infoTabs ) {

	var dummy=null;
  var marker = new GMarker(point,icon);
	var html = "<div style='height: 300px; overflow: auto;' >" + mtext + "</div>";

	var openForm = function () {
		currentPoint = marker.getPoint();
		map.setCenter(currentPoint, map.getZoom());
		currentWaypoint.latitude = currentPoint.lat();
		currentWaypoint.longitude = currentPoint.lng();

		if (type=='waypoint') {
			if (!recording)
				ajaxCall('getWaypoint.php?route_id='+currentRoute.id+'&latitude='+ currentPoint.lat() + '&longitude=' + currentPoint.lng()+'&idx='+idx, getWaypointResponse,1,0,marker);
			else 
				melding ("Complete and save your route, and then add any comments to any waypoint.");
		}
		else {
			if ( infoTabs.length >0 )
			{
    		marker.openInfoWindowTabsHtml( infoTabs , { selectedTab : 0 , maxWidth: 300 } );
			}
			else {
    		marker.openInfoWindowHtml( html );
			}
		}
  }
	
	/* als je aan het tekenen bent dan soms geen listener voor de clicks */
	if (isFirst && recording) {
					GEvent.addListener(marker, "click", function () {
								/* alert ('click op startpunt'); */
								GEvent.trigger(map, "click", false, point);
					} );
	}
	else {
					GEvent.addListener(marker, "click", openForm );
					if (domId) {
							var domElement = $(domId);
							if (domElement) {
											domElement.onclick = openForm;	
											domElement.onmouseover = function () { this.style.background = BGCOLOR_MO;}
											domElement.onmouseout = function () { this.style.background = '#ffffff';}
							}
					}
	}

  return marker;
}


function createRouteMarker(point, html, icon, rid) {

  var marker = new GMarker(point,icon);
  var divhtml = "<div style='height: 300px; overflow: auto;'>" + html + "</div>";	

	var focusPoint = function () {
					// om het laden van routes te voorkomen
					rrROUTEVIEW = DETAIL;
					currentPoint = marker.getPoint();
					//if (map.getZoom() > 13) { 
						ri.hideRouteInfoDiv_();
						klapInUitFunctie('in');
						map.setCenter(currentPoint, map.getZoom());
					//} else {
					//	map.setCenter(currentPoint, 17 - 2);
					//}
				  	
					marker.openInfoWindowHtml(divhtml);
  }

  GEvent.addListener(marker, "mouseover", function () { 
			var routeListitem = $('route'+rid);
			if (routeListitem) {
					routeListitem.style.background = BGCOLOR_MO;
			}
	});

  GEvent.addListener(marker, "mouseout", function () { 
			var routeListitem = $('route'+rid);
			if (routeListitem) {
					routeListitem.style.background = "#ffffff";
			}
	});

  GEvent.addListener(marker, "click", focusPoint );
	var routeListitem = $('route'+rid);
	if (routeListitem)
	routeListitem.onclick= focusPoint;

  return marker;
}



function createIconHTML (href,onClick,title,imgSrc) {
	var commonText = "<a href='"+href+"' onclick='"+onClick+"'><img src='"+imgSrc+"' title='"+title+"'></a>&nbsp;";
	commonText += "<a href='"+href+"' onclick='"+onClick+"' title='"+title+"'>"+title+"</a>";
	return commonText;
}

function getURLParam(strParamName) {
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (
aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return strReturn;
}

function changeBodyClass(from, to) {
 document.body.className = document.body.className.replace(from, to);
 return false;
}

function showHelp() {
	alert('to do');
}

function myPrint() {
		setInner ('printroute', $('sidebar').innerHTML);
		window.print();
}

function melding(msg) {

	var melding = document.getElementById("statusDraw");
	while (melding.firstChild) {
			melding.removeChild(melding.firstChild);
	}

	melding.style.display= 'block';
	melding.appendChild(document.createTextNode(msg));	

	setTimeout('clearInner(\"statusDraw\")',20000);
}

function  echo(param) {
					if (DEBUG==1) {
						GLog.write(param);
					}
}

function findLocation()
{
		geocoder.getLocations($('searchInput').value, gaNaarLocatie);
}

function gaNaarLocatie(response) {
 	if (!response || response.Status.code != 200) {
 					melding("Location not found " + ( ( response ) ? "(code " + response.Status.code + ")" : "") );
	}
 	else {
 		 place = response.Placemark[0];
		 point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
		 map.setCenter( point );
		 map.setZoom( 15 );
	}
}

function hideStatusDraw() {
			$('statusDraw').style.display = 'none';
}

var directions;
var geoxml;

function loadPhotosWithinMapBounds() {

	var boundsSW = map.getBounds().getSouthWest();
	var boundsNE = map.getBounds().getNorthEast();

	var west = boundsSW.lng();
	var east = boundsNE.lng();
	var north = boundsNE.lat();
  var south = boundsSW.lat();
  var picsAsKML = "http://picasaweb.google.com/data/feed/base/all?kind=photo&alt=kml&max-results=50&bbox="+west+","+south+","+east+","+north;
	//alert (picsAsKML);
  geoxml = new GGeoXml(picsAsKML);
  geoxml.hidden = true;

  // strip ?alt=kml
  //getJSON(picsAsKML.split("&")[0]);
} 

/**
 * Creates a script tag in the page that loads in the 
 * JSON feed for the specified key/ID. 
 * 
 * wordt niet gebruikt 
 */
function getJSON(picsUrl) {

  // Retrieve the JSON feed.
  var script = document.createElement('script');
  script.setAttribute('src', picsUrl + '&alt=json-in-script&callback=loadpicsJSON');
  script.setAttribute('id', 'jsonScript');
  script.setAttribute('type', 'text/javascript');
  document.documentElement.firstChild.appendChild(script);
}

function loadpicsJSON(json) {
  var waypoints = [];
  for (var i = 0; i < json.feed.entry.length && i < 25; i++) {
    var entry = json.feed.entry[i];i
    if (entry["georss$where"]) {
      var pos = entry["georss$where"]["gml$Point"]["gml$pos"].$t;
      var lat = parseFloat(pos.split(" ")[0]);
      var lng = parseFloat(pos.split(" ")[1]);
      var latlng = new GLatLng(lat, lng);
      waypoints.push(latlng);
    }
  }
  
}

function togglePhotos(id) {
  if (geoxml.hidden) {
		melding("Busy collecting images from Picasa");
    map.addOverlay(geoxml);
    geoxml.hidden = false;
		document.getElementById(id).innerHTML = picasaImg;
  } else {
		melding("Images from Picasa will be removed from the map");
    map.removeOverlay(geoxml);
		document.getElementById(id).innerHTML = picasaImg;
    geoxml.hidden = true;
  }
}

function loadLogbookNotes () {
	  ajaxCall("../home/getLogsFromRoute.php?route_id="+currentRoute.id+'&ajax=1&cache_ttl=3600' ,respLoadLogbookNotes,1,0);
}

function respLoadLogbookNotes(req) {
		var logsDiv = getLogsDiv();
		logsDiv.innerHTML = req.responseText;
		logsDiv.style.display = 'block';
}

function showHeightsgraph() {

		var hP = new heightsPlot();
		var distThisLeg = totDistance = 0;
		var rt = route;
		for (i in elev8n) {
					hP.addHeight( elev8n[i].gtopo30 );	
					if (i>0) {
						distThisLeg = calcDist(elev8n[i].longitude,elev8n[i].latitude, elev8n[i-1].longitude,elev8n[i-1].latitude );
						totDistance += distThisLeg;
					}
					hP.addDistance( fix(distThisLeg,2) );	
		}	

		calc.showCalculatorDiv_();
		hP.insertGraph();
}

function searchFlickr() {
	if (!document.getElementById('flickr_script')) {
					var head = document.getElementsByTagName('head');
					var js = document.createElement('script');
					js.id = 'flickr_script';
					var dt = new Date();
					var dtString = ''+dt.getFullYear()+dt.getMonth()+dt.getDate()+dt.getHours()+dt.getMinutes()+dt.getMilliseconds();
		//check for cookie - if disabled then append request.nocookies
					js.src = scriptPath + 'inc_flickr.js'+  '?dtm='+dtString;
					head[0].appendChild(js);
	}
	else {

			flickr_TYR.gallery.show();
			flickr_TYR.gallery.doSearchFlickr_(1, 0.1, route[0].y , route[0].x );
	}
}

function checkStreetview() {
				melding('Streetview availability check');
        // visuele check of streetview mogelijk is
        svOverlay = new GStreetviewOverlay();
        map.addOverlay(svOverlay);

        var svStartpoint = new GLatLng( route[0].y, route[0].x );
        panoramaOptions = { latlng: svStartpoint };

        panoClient = new GStreetviewClient();
        panoClient.getNearestPanorama(svStartpoint, function (panoData) {
                 panoGlobalData = panoData;
                 if (panoData.code != 200) {
                    //alert ('No streetview info :' + panoData.code);
                    changeStreetviewLink();
                    if (panoData.code == 603) {
                            changeStreetviewLink();
                            alert("Error: Flash doesn't appear to be supported by your browser");
                    }
                    return;
                  }

         });
}

function changeStreetviewLink() {

        if (document.getElementById('linkStreetview')) {
                document.getElementById('linkStreetview').style.display = 'none';
        }
        else {
          setTimeout('changeStreetviewLink()', 2000);
        }

}

function handleNoFlash(errorCode) {
  if (errorCode == 603) {
    alert("Error: Flash doesn't appear to be supported by your browser");
    return;
  }
}

function initStreetview() {
	if (!document.getElementById('streetview_script')) {
					var head = document.getElementsByTagName('head');
					var js = document.createElement('script');
					js.id = 'streetview_script';
					var dt = new Date();
					var dtString = ''+dt.getFullYear()+dt.getMonth()+dt.getDate()+dt.getHours()+dt.getMinutes()+dt.getMilliseconds();
		//check for cookie - if disabled then append request.nocookies
					js.src = scriptPath + 'inc_streetview.js'+  '?dtm='+dtString;
					head[0].appendChild(js);
	}
	tryStreetview(); 
}

function tryStreetview () {
	if (!document.getElementById('streetview_script')) {
			setTimeout('tryStreetview', 3000);
	}
	else {
				if (streetview_TYR == null ) {
								streetview_TYR  = new myStreetview();
								map.addControl( streetview_TYR ) ;
				}
				streetview_TYR.show_();
				streetview_TYR.showStreetview_();
	}
}

function $(id) {return document.getElementById(id)}


function getHtmlRouteExtras () {
var picasaImg = "<img id='linkPicasa' style='cursor : pointer' title='Show Picasa photos' alt='Show Picasa photos' onclick='javascript:togglePhotos(\"linkPicasa\")' src='"+ imagePath +"picasa.gif' />";
var flickrImg = "<img id='linkFlickr' style='cursor : pointer' title='Show flickr images' alt='Show flickr images' onclick='javascript:searchFlickr()' src='"+ imagePath +"icon_flickr.gif' />";
var heightsgraphImg = "<img id='linkHeightsgraph'  style='cursor : pointer' title='Show a heights graph'  alt='Show a heights graph' onclick='javascript:showHeightsgraph()' src='"+ imagePath +"altitude.gif' />";
var streetviewImg = "<img id='linkStreetview'  style='cursor : pointer' title='Google streetview' alt='Google streetview' onclick='javascript:initStreetview()' src='"+ imagePath +"icon_streetview.gif' />";

	var html ='<div id="routeextras">';
	html += picasaImg;
	html += flickrImg;
	if (!isNaN(currentRoute.avg_altitude))
		html += heightsgraphImg;
  html += streetviewImg;
  html += '</div>';

	return html;
}

function callAjaxReactions () {
	try {
			if (!document.getElementById('routereaction_script')) {
									var head = document.getElementsByTagName('head');
									var js = document.createElement('script');
									js.id = 'routereaction_script';
									var dt = new Date();
									var dtString = ''+dt.getFullYear()+dt.getMonth()+dt.getDate()+dt.getHours()+dt.getMinutes()+dt.getMilliseconds();
									js.src = scriptPath + 'inc_routereaction.js'+  '?dtm='+dtString;
									head[0].appendChild(js);
			}
			//if (document.getElementById('routereactions').innerHTML=='') {
			url = "../routes/routereaction.php?ajax=1&action=list&route_id=" + currentRoute.id;
			ajaxCall(url, responseReactions, 1,0);
			//}
			//else 
			//	return;
	} catch(e) {
			alert(e);
	}
}

var rrObj;
function responseReactions(req) {
	try {
			document.getElementById('routereactions').innerHTML = req.responseText;
			rrObj= new routereaction();
			rrObj.setRoute(currentRoute.id);
	}
	catch(e) {
			alert(e);
	}
}

function mailPartner(cl_id) {
            str_url = "../community/partnerfinder_popup.php?cl_id=" + cl_id + "&'.SID.'";
            dialog = window.open(str_url, "dialog",
                                 "location=no,directories=no,status=yes,"
                               + "menubar=no,toolbar=no,scrollbars=yes,"
                               + "resizable=yes,width=569,height=450");
            dialog.focus();
}
