var locpath ;
var locdomain ;

var map ;
//var centreLat = -33.8 ;
//var centreLng = 19.5 ;
//var startZoom = 9 ;

var trails ;
var I = -1 ;
var trailbackup ;
var next_i ;

var editmode = false ;

var iconTransMarker = new GIcon();
iconTransMarker.image = "http://"+location.host+"/img/marker60.png";
iconTransMarker.shadow = "http://"+location.host+"/img/shadow50.png"
iconTransMarker.iconSize = new GSize(20, 34);
iconTransMarker.shadowSize = new GSize(37, 34);
iconTransMarker.iconAnchor = new GPoint(9, 34);
iconTransMarker.infoWindowAnchor = new GPoint(9, 2);
iconTransMarker.infoShadowAnchor = new GPoint(18, 25);

var iconHighMarker = new GIcon();
iconHighMarker.image = "http://"+location.host+"/img/marker.png";
iconHighMarker.shadow = "http://"+location.host+"/img/shadow50.png"
iconHighMarker.iconSize = new GSize(20, 34);
iconHighMarker.shadowSize = new GSize(37, 34);
iconHighMarker.iconAnchor = new GPoint(9, 34);
iconHighMarker.infoWindowAnchor = new GPoint(9, 2);
iconHighMarker.infoShadowAnchor = new GPoint(18, 25);

//create the ToolTip overlay object
function ToolTip(marker,html,width) {
  this.html_ = html;
  this.width_ = (width ? width + 'px' : 'auto');
  this.marker_ = marker;
} 
 
ToolTip.prototype = new GOverlay();
 
ToolTip.prototype.initialize = function(map) {
  var div = document.createElement("div");
  div.style.display = 'none';
  map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
 
  this.map_ = map;
  this.container_ = div;
}
 
ToolTip.prototype.remove = function() {
  this.container_.parentNode.removeChild(this.container_);
}
 
ToolTip.prototype.copy = function() {
  return new ToolTip(this.html_);
}
 
ToolTip.prototype.redraw = function(force) {
  if (!force) return;
 
  var pixelLocation =   this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
  this.container_.innerHTML = this.html_;
  this.container_.style.position = 'absolute';
  this.container_.style.left = pixelLocation.x + "px";
  this.container_.style.top = pixelLocation.y + "px";
  this.container_.style.width = this.width_;
  this.container_.style.font = 'bold 10px/10px verdana, arial, sans';
  this.container_.style.border = '1px solid black';
  this.container_.style.background = 'yellow';
  this.container_.style.padding = '4px';
 
  //one line to desired width
  this.container_.style.whiteSpace = 'nowrap';
  if(this.width_ != 'auto') this.container_.style.overflow = 'hidden';
  this.container_.style.display = 'block';
}
 
GMarker.prototype.ToolTipInstance = null;
 
GMarker.prototype.openToolTip = function(content) {
  //don't show the tool tip if there is acustom info window
  if(this.ToolTipInstance === null) {
    this.ToolTipInstance = new ToolTip(this,content) ;
    map.addOverlay(this.ToolTipInstance);
  }
}
 
GMarker.prototype.closeToolTip = function() {
  if(this.ToolTipInstance !== null) {
    map.removeOverlay(this.ToolTipInstance);
    this.ToolTipInstance = null;
  }
}

function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function cloneTrail(what) {
    for (var i in what) {
			  if ( i == 'marker') continue ; // skip marker in clone
			  if ( what[i].splice ) { // maintain arrays
			    this[i] = [] ;
          for (var j in (what[i]) ) {
            this[i][j] = new cloneTrail((what[i])[j]); 
          }
        } else if (typeof what[i] == 'object') {
            this[i] = new cloneTrail(what[i]);
        }
        else
            this[i] = what[i];
    }
}

// from gmail
function AdjustRows(a){
	if(!a){return}
	var b=a.value.split("\n"), c=0; //,c=T?1:0;
	c+=b.length;
	var d=a.cols;
	if(d<=20){d=40}
	for(var e=0;e<b.length;e++){
		if(b[e].length>=d){
			c+=Math.ceil(b[e].length/d)
		}
	}
	c=Math.max(c,1);
	if(c!=a.rows){
		a.rows=c-1;
		//Aj()
	}
}

function changeClass (element, from, to) {
	element.className = element.className.replace(from,to); 
	return false ;
}




function getTrailData(i, edit) {
	if ( i == -1 ) return false ;
	next_i = i ;
	var trail = trails[i] ;
  var getVars = "?trailid=" + trail.trailid ;
  
  var request = GXmlHttp.create() ;
  request.open('GET', "http://"+location.host+"/v0.2/traildata.php"+getVars, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
			if ( i != next_i ) return false ;
      var jscript = request.responseText ;
			var newtrail ;
			//alert(jscript) ;
      eval(jscript) ; // populate newtrail variable
			// update trails variable
		  trails[i] = newtrail ;
			// remove markers from [old]trail
			for (j in trail.entrypoints) {
				var marker = trail.entrypoints[j].marker ;
				if ( ! marker ) continue ;
				marker.closeToolTip();
				map.removeOverlay(marker) ;
				trail.entrypoints[j].marker = null ;
				//addHighlightedMarker(trail, j) ;
			}
			trail = null ;
			// add new markers
			for (j in newtrail.entrypoints) {
			  addHighlightedMarker(i, j) ;
			}
			I = i ;
			
			// update screen data
      loadTrailData() ;
			trailbackup = new cloneTrail(trails[I]) ;
      
			if ( edit ) {
				btnEditClick () ;
      }
			document.getElementById("link").href = "http://www.wikitrails.co.za/mtb/trail/"+newtrail.trailid ;
			// remove 'Loading' message
	    changeClass(document.body,'loading', 'standby' ) ;
			  
    }
  } 
	// add 'Loading' message
	changeClass(document.body,'standby', 'loading' ) ;
	
  request.send(null) ;
  return false ;
}

function getNewLocation () {
	var c = map.fromLatLngToDivPixel(map.getCenter());
	var c2 = new GPoint(c.x+Math.round(40*Math.random()-20),c.y+Math.round(40*Math.random()-20)) ;
	return map.fromDivPixelToLatLng(c2); 
}

function loadTrailData () {
  changeClass ( document.body, 'editmode', 'normalmode' ) ;
  document.getElementById("traildata").className = "show" ;
  
  var entrypointselement ;
  // normalmode
  //document.getElementById("lbltrailname").innerHTML = trails[I].trailname ;
  entrypointselement = document.getElementById("normentrypoints") ;
  // remove entry items
  while (entrypointselement.firstChild) { entrypointselement.removeChild (entrypointselement.firstChild) ; }
  for (j in trails[I].entrypoints) {
    var listItem = document.createElement('li') ;
    listItem.innerHTML = trails[I].entrypoints[j].entryname+' ('+formatLatLng(trails[I].entrypoints[j].lat, trails[I].entrypoints[j].lng)+')';
    entrypointselement.appendChild(listItem) ;
  }
  // other members
  for (member in trails[I]) {
    var element = document.getElementById('lbl'+member) ;
    if ( element ) {
      element.innerHTML = trails[I][member].replace(/\n/g,"<br />");
    }
  }
	// facilities
var reception = ['Unknown','No','Poor','Intermittent','Good'] ;
var facilitylist = Array () ;
if ( trails[I].water ) facilitylist.push('Water available') ;
if ( trails[I].parking ) facilitylist.push('Secure parking') ;
if ( trails[I].toilets ) facilitylist.push('Toilets') ;
if ( trails[I].showers ) facilitylist.push('Showers') ;
if ( trails[I].shop ) facilitylist.push('Kiosk/shop') ;
if ( trails[I].restaurant ) facilitylist.push('Restaurant') ;
if ( trails[I].picnic ) facilitylist.push('Picnic') ;
if ( trails[I].braai ) facilitylist.push('Braai facilities') ; 
if ( trails[I].visitorscentre ) facilitylist.push('Visitors centre') ;
if ( trails[I].bikehire ) facilitylist.push('Bike Hire') ;

if (trails[I].cellphone>0) {facilitylist.push(reception[trails[I].cellphone]+' cellphone reception') ;}
if (trails[I].facilities!='') {facilitylist.push(trails[I].facilities) ;}
var facility = facilitylist.join(', ') ;
document.getElementById('lblfacilities').innerHTML = facility;

	

	// permitcost
	var cost = trails[I].cost ;
	if ( cost < 0 ) cost = 'Unknown'
	else if ( cost == 0 ) cost = 'Free'
	else cost = 'R'+cost ;
	document.getElementById("lblcost").innerHTML = cost ;
	// ...


  /*
  'signage': '',
  'security': '',
  'maps': '',
  'gettingthere': '',
  'otheractivities': '',
  'contactdetails': '',
  
  'water': false,
  'toilets': false,
  'parking': false,
  'showers': false,
  'shop': false,
  'restaurant': false,
  'picnic': false,
  'visitorscentre': false,
  'braai': false,
  'bikehire': false,
  'cellphone': true,
  'facilities': '',
  
  
  'cost': '',
  'concessions': '',
  'comments': ''
  */
  
  // edit mode
	// permitcost
	//document.getElementById("edtcost").value = trails[I].cost ;
  // other members
  for (member in trails[I]) {
    var element = document.getElementById('edt'+member) ;
    if ( element ) {
      element.value = trails[I][member] ;
    }
    var element = document.getElementById('chk'+member) ;
    if ( element ) {
      element.checked = trails[I][member] ;
    }
  }
  
  entrypointselement = document.getElementById("editentrypoints") ;
  // remove entry items
  while (entrypointselement.firstChild) { entrypointselement.removeChild (entrypointselement.firstChild) ; }
  for (j in trails[I].entrypoints) {
    var listItem = document.createElement('li') ;
    addEntryPointLI(listItem, j) ;
    entrypointselement.appendChild(listItem) ;
  }
	
  // create 'add entry point' button
  var listItem = document.createElement('input') ;
	listItem.type = 'button' ;
  listItem.value = 'Add entry point' ;
	listItem.onclick = function() {
    // add point to selected trail
		var pointscount = trails[I].entrypoints.length ;
		//var centre = map.getCenter () ;
		var newLocation = getNewLocation () ;
		trails[I].entrypoints[pointscount] = {
		  'id': -1, 'name': 'New entry point', 'lat': newLocation.lat(), 'lng': newLocation.lng() 
		} ;
		// add Actual Marker
		addHighlightedMarker (I, pointscount) ;
		
    var li = document.createElement('li') ;
    addEntryPointLI(li, pointscount) ;
    entrypointselement.insertBefore(li, listItem) ;			
	}	
	entrypointselement.appendChild(listItem) ;
  
	
  // Routes
  
	var elementRoute = document.getElementById("Routes") ;
  while (elementRoute.firstChild) { elementRoute.removeChild (elementRoute.firstChild) ; }
	
	var scale = ['Unknown','Easy','Easy/Intermediate','Intermediate','Intermediate/Advanced','Advanced','Advanced/Extreme','Extreme'];

  for (k in trails[I].routes) {
		var route = trails[I].routes[k] ;

    var li = document.createElement('li') ;
    li.id = 'normroute'+k ;
    //li.className = '' ;
		var tmp = '<span class="editbtn">[<a id="btnEditRoute<x>"href="#">edit route</a>]</span><table><tr><td class="firstcolumn"><h3>Name</h3></td><td><span id="lblroutename<x>"></span></td></tr><tr><td><h3>Distance</h3></td><td><span id="lblroutedist<x>"></span></td></tr><tr><td><h3>Technical</h3></td><td><span id="lblroutetechnical<x>"></span></td></tr><tr><td><h3>Endurance</h3></td><td><span id="lblrouteendurance<x>"></span></td></tr><tr><td><h3>Singletrack</h3></td><td><span id="lblroutesingletrack<x>"></span></td></tr><tr><td><h3>Terrain</h3></td><td><span id="lblrouteterrain<x>"></span></td></tr><tr><td><h3>Description</h3></td><td><span id="lblroutedesc<x>"></span></td></tr></table>' ;
		li.innerHTML = tmp.replace(/<x>/g,k) ;		
	  elementRoute.appendChild(li) ;
		
    document.getElementById('btnEditRoute'+k).onclick = btnEdtRouteOnClick(k) ;
    
		document.getElementById('lblroutename'+k).innerHTML = route.name ;
		document.getElementById('lblrouteterrain'+k).innerHTML = route.terrain.replace(/\n/g,"<br />") ;
		document.getElementById('lblroutedesc'+k).innerHTML = route.description.replace(/\n/g,"<br />") ;
  	// routedist
	  var dist = route.distance ; 
		if ( dist < 0 ) dist = 'Unknown' 
		else dist = dist+'km' ;
		document.getElementById('lblroutedist'+k).innerHTML = dist ;
  	// singletrack
	  var track = route.singletrack ; 
		if ( track < 0 ) track = 'Unknown' 
		else track = track+'%' ;
		document.getElementById('lblroutesingletrack'+k).innerHTML = track ;
		document.getElementById('lblroutetechnical'+k).innerHTML = scale[route.technical] ;
		document.getElementById('lblrouteendurance'+k).innerHTML = scale[route.endurance] ;
		
    li = document.createElement('li') ;
    li.id = 'editroute'+k ;
    li.className = 'hide' ;
		tmp = '<table><tr><td class="firstcolumn"><h3>Name</h3></td><td><input id="edtroutename<x>"type="text"/></td></tr><tr><td><h3>Distance</h3></td><td><input id="edtroutedist<x>"type="text"/>km</td></tr><tr><td><h3>Technical</h3></td><td><select id="edtroutetechnical<x>"><option value="0">Unknown</option><option value="1">Easy</option><option value="2">Easy/Intermediate</option><option value="3">Intermediate</option><option value="4">Intermediate/Advanced</option><option value="5">Advanced</option><option value="6">Advanced/Extreme</option><option value="7">Extreme</option></select></td></tr><tr><td><h3>Endurance</h3></td><td><select id="edtrouteendurance<x>"><option value="0">Unknown</option><option value="1">Easy</option><option value="2">Easy/Intermediate</option><option value="3">Intermediate</option><option value="4">Intermediate/Advanced</option><option value="5">Advanced</option><option value="6">Advanced/Extreme</option><option value="7">Extreme</option></select></td></tr><tr><td><h3>Singletrack</h3></td><td><input id="edtroutesingletrack<x>"type="text"/>%</td></tr><tr><td><h3>Terrain</h3></td><td><textarea rows="5"cols="80"id="edtrouteterrain<x>"></textarea></td></tr><tr><td><h3>Description</h3></td><td><textarea rows="5"cols="80"id="edtroutedesc<x>"></textarea></td></tr></table><span>Content that violates any<a href="http://en.wikipedia.org/wiki/Wikipedia:Copyrights">copyright</a>will be deleted.You agree to put your changes into the public domain.<br/>Do not copy text from other websites without permission.It will be deleted.<br/></span><input id="btnSaveRoute<x>"type="button"value="Save Changes"/><input id="btnCancelRoute<x>"type="button"value="Cancel Changes"/><input id="btnRemoveRoute<x>"type="button"value="Remove Route"/>' ;
		li.innerHTML = tmp.replace(/<x>/g,k) ;		
	  elementRoute.appendChild(li) ;
		
		document.getElementById('edtroutename'+k).value = route.name ;
		document.getElementById('edtrouteterrain'+k).value = route.terrain ;
		document.getElementById('edtroutedesc'+k).value = route.description ;
		document.getElementById('edtroutedist'+k).value = route.distance ;
		document.getElementById('edtroutesingletrack'+k).value = route.singletrack ;
		document.getElementById('edtroutetechnical'+k).value = route.technical ;
		document.getElementById('edtrouteendurance'+k).value = route.endurance ;
    
    document.getElementById('btnSaveRoute'+k).onclick = btnSaveRouteOnClick(k) ;
    document.getElementById('btnCancelRoute'+k).onclick = btnCancelClick ;
    document.getElementById('btnRemoveRoute'+k).onclick = btnRemoveRouteOnClick(k) ;
		

  }  

}

function btnEdtRouteOnClick(k) {
  return function () { return btnEditRouteClick(k) ; }
}

function btnEditRouteClick (k) {
  btnCancelClick () ; 
  //alert(k) ;
  document.getElementById('normroute'+k).className = 'hide' ;
  document.getElementById('editroute'+k).className = '' ;
  
  return false ;
}
function btnSaveRouteOnClick(k) {
  return function () { return btnSaveRouteClick(k) ; }
}
function btnSaveRouteClick (k) {
  var route = trails[I].routes[k] ;
  var getVars = "?routeid=" + route.id ;
 
  var val ;
  
  val = document.getElementById('edtroutename'+k).value ;
  if ( val != route.name ) { getVars += "&name=" + val ;}
	val = escape(document.getElementById('edtrouteterrain'+k).value) ;
  if ( val != route.terrain ) { getVars += "&terrain=" + val ;}
	val = escape(document.getElementById('edtroutedesc'+k).value) ;
  if ( val != route.description ) { getVars += "&description=" + val ;}
	val = document.getElementById('edtroutedist'+k).value ;
  if ( val != route.distance ) { getVars += "&distance=" + val ;}
	val = document.getElementById('edtroutesingletrack'+k).value ;
  if ( val != route.singletrack ) { getVars += "&singletrack=" + val ;}
	val = document.getElementById('edtroutetechnical'+k).value ;
  if ( val != route.technical ) { getVars += "&technical=" + val ;}
	val = document.getElementById('edtrouteendurance'+k).value ;  
  if ( val != route.endurance ) { getVars += "&endurance=" + val ;}
  
  var request = GXmlHttp.create() ;
  request.open('GET', "http://"+location.host+"/v0.2/storeroutedata.php"+getVars, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      if ( request.responseText == 'success' ) {
				btnCancelClick() ;
        getTrailData(I) ; 
      } else {
        alert('Error: '+request.responseText) ;
      }
    }
  }
  request.send(null) ;
  return false ;
}

function btnRemoveRouteOnClick(k) {
  return function () { return btnRemoveRouteClick(k) ; }
}
function btnRemoveRouteClick (k) {
	// ask are you sure
	if ( ! confirm("Are you sure you want to remove this route?") ) return false ;
	// remove route
  var getVars = "?routeid=" + trails[I].routes[k].id ;
  
  var request = GXmlHttp.create() ;
  request.open('GET', "http://"+location.host+"/v0.2/delroute.php"+getVars, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
			if ( request.responseText == 'success' ) {
				// remove trail from trailbackup variable
        //var oldtrail = trails[I] ;
				trailbackup.routes.splice(k,1) ;
				btnCancelClick () ;
			}
    }
  }
  request.send(null) ;
	return false ;
}

function setBlankTrailData () {
	
	I = -1 ;
  editmode = false ;
  document.getElementById("traildata").className = "hide" ;
  
  document.getElementById("lbltrailname").innerHTML = 'No trail selected' ;
	
  var entrypointselement = document.getElementById("normentrypoints") ;	
  while (entrypointselement.firstChild) {
    entrypointselement.removeChild (entrypointselement.firstChild) ;	
	}
	
  changeClass ( document.body, 'editmode', 'normalmode' ) ;	
}


function getMapData(initialid) {
  var request = GXmlHttp.create() ;
  request.open('GET', "http://"+location.host+"/v0.2/mapdata.php", true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var initiali = -1 ;
      var jscript = request.responseText ;
      eval(jscript) ; // populate the trails variable
      
      for(i in trails) {
				var trail = trails[i] ;
				for (j in trail.entrypoints) {
					addTransparentMarker(i, j) ;
				}
        if ( trail.trailid == initialid ) {
          initiali = i ;
        }
      }		
      if ( initiali > -1){
        GEvent.trigger(trails[initiali].entrypoints[0].marker,'click') ;
      }	
    }
  } ;
  request.send(null) ;
  return false ;
}

function setMarkersTransparent () {
  i = I ;
  if ( i == -1) return true ;
  //for(i in trails) {
		var trail = trails[i] ;
		for (j in trail.entrypoints) {
		  if ( ! trail.entrypoints[j].marker ) continue ;
	    if ( trail.entrypoints[j].marker.getIcon() == iconTransMarker ) continue ;
	
			trail.entrypoints[j].marker.closeToolTip();
			map.removeOverlay(trail.entrypoints[j].marker) ;
			trail.entrypoints[j].marker = null ;
			addTransparentMarker(i,j) ;
		}
  //}				
  return true ;
} ;

function addTransparentMarker(i, j) {
	var entrypoint = trails[i].entrypoints[j] ;
  var point = new GLatLng(entrypoint.lat, entrypoint.lng) ;
  entrypoint.marker = new GMarker(point, iconTransMarker) ;
	  
  GEvent.addListener(entrypoint.marker,'mouseover',function() {
    entrypoint.marker.openToolTip(trails[i].trailname+' - '+entrypoint.entryname);
  }) ;
  GEvent.addListener(entrypoint.marker,'mouseout',function() {
    entrypoint.marker.closeToolTip();
  }) ;
  GEvent.addListener(entrypoint.marker,'click',function() {
    btnCancelClick () ;
		setMarkersTransparent () ;
		//getTrailData(I, false, true) ;
		
    getTrailData(i);
		/*
		entrypoint.marker.closeToolTip();
		map.removeOverlay(entrypoint.marker) ;
		entrypoint.marker = null ;
		addHighlightedMarker(i, j) ;
		*/
    if ( map.getZoom()<9 ) map.setZoom(9) ;
	  map.panTo(point) ;
	  //alert(point.toUrlValue())
  });

  map.addOverlay(entrypoint.marker) ;
	
	return false ;
}

function addHighlightedMarker (i, j, drag) {
	var trail = trails[i] ;
	var entrypoint = trail.entrypoints[j] ;
  var point = new GLatLng(entrypoint.lat, entrypoint.lng) ;
  entrypoint.marker = new GMarker(point, {icon: iconHighMarker, draggable: drag}) ;
	  
  GEvent.addListener(entrypoint.marker,'mouseover',function() {
    entrypoint.marker.openToolTip(trail.trailname+' - '+entrypoint.entryname);
  }) ;
  GEvent.addListener(entrypoint.marker,'mouseout',function() {
    entrypoint.marker.closeToolTip();
  }) ;
  GEvent.addListener(entrypoint.marker,'drag',function() {
		entrypoint.marker.closeToolTip();
		var point = entrypoint.marker.getPoint () ;
		document.getElementById("entrypoint_lat_"+j).value = point.lat() ;
		document.getElementById("entrypoint_lng_"+j).value = point.lng() ;
  }) ;
	
  map.addOverlay(entrypoint.marker) ;

}





function btnEditClick () {
  //trailbackup = new cloneTrail(trails[I]) ;
  changeClass(document.body,'normalmode','editmode') ;
  editmode = true ;
  return false ;
}

function btnCancelClick() {
  if (!trailbackup) return false ;
  //if ( !editmode ) return false ;
  // revert trails[I] to trailbackup
  var oldtrail = trails[I] ;
  trails[I] = trailbackup ;
  
	// remove markers from oldtrail
	for (j in oldtrail.entrypoints) {
  	var marker = oldtrail.entrypoints[j].marker ;
		if ( ! marker ) continue ;
		marker.closeToolTip();
		map.removeOverlay(marker) ;
		oldtrail.entrypoints[j].marker = null ;
	}
  oldtrail = null ;
	// add new markers
	for (j in trailbackup.entrypoints) {
	  addHighlightedMarker(I, j) ;
	}
	editmode = false ;		
	// update screen data
  loadTrailData() ;
	
  return false ;
}

function btnSaveClick() {
  // verify input data
	var cost = document.getElementById('edtcost').value ;	
	if (!isFinite(cost)) {
		alert('Cost must be a number');
		return false ;
	}

  var getVars = "?trailid=" + trails[I].trailid ;
  // entrypoints
  var entrypointselement = document.getElementById("entrypoints") ;
  getVars += "&entrypointcount=" + trails[I].entrypoints.length ;
	for (j in trails[I].entrypoints) {
		var entrypoint = trails[I].entrypoints[j] ;
  	var editpoint = false ; 
		var addpoint = (entrypoint.id == -1) ;
		
		var delpoint = document.getElementById('entrypoint_del_'+j).checked ;
		if ( delpoint ) {
	    getVars += "&entrypointid"+j+"=" + entrypoint.id ;
	    getVars += "&entrypointdel"+j+"=true" ;
			continue ;
		}

  	var entryname = document.getElementById('entrypoint_name_'+j).value
	  if (( entryname != entrypoint.entryname )||(addpoint)) {
      getVars += "&entrypointname"+j+"=" + entryname ;
	    editpoint = true ;
	  }
  	var pointlat = document.getElementById('entrypoint_lat_'+j).value
	  if (( pointlat != entrypoint.lat )||(addpoint)) {
      getVars += "&entrypointlat"+j+"=" + pointlat ;
	    editpoint = true ;
	  }
  	var pointlng = document.getElementById('entrypoint_lng_'+j).value
	  if (( pointlng != entrypoint.lng )||(addpoint)) {
      getVars += "&entrypointlng"+j+"=" + pointlng ;
	    editpoint = true ;
	  }
	  if ( editpoint ) {
	    getVars += "&entrypointid"+j+"=" + entrypoint.id ;
	  }
  }
  // other members
  for (member in trails[I]) {
    var element = document.getElementById('edt'+member) ;
    if ( element ) {
			var val = escape(element.value) ;
      if ( val != escape(trails[I][member]) ) {
        getVars += "&"+member+"=" + val ;
      }
    }
      
  }
	// checkbox members
  for (member in trails[I]) {
    var element = document.getElementById('chk'+member) ;
    if ( element ) {
			var val = element.checked ;
      if ( val != trails[I][member] ) {
        getVars += "&"+member+"=" + val ;
      }
    }
  }

  /*
  'signage': '',
  'facilities': '',
  'security': '',
  'maps': '',
  'gettingthere': '',
  'otheractivities': '',
  'contactdetails': '',
  'water': false,
  'toilets': false,
  'parking': false,
  'showers': false,
  'shop': false,
  'restaurant': false,
  'picnic': false,
  'visitorscentre': false,
  'braai': false,
  'bikehire': false,
  'cellphone': true,
  'cost': '',
  'concessions': '',
  'comments': ''
  */

  // end getVars
  //var getVars = "?trailid=" + trailid + "&trailname=" + trailname ;
  
  var request = GXmlHttp.create() ;
  request.open('GET', "http://"+location.host+"/v0.2/storetraildata.php"+getVars, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      if ( request.responseText == 'success' ) {
				btnCancelClick() ;
        getTrailData(I) ; 
      } else {
        alert('Error: '+request.responseText) ;
      }
    }
  }
  request.send(null) ;
  return false ;  
}


function formatLatLng (lat, lng) {
  lat = (lat>0)?lat+' N':-lat+' S' ;
  lng = (lng>0)?lng+' E':-lng+' W' ;

  return lat+', '+lng ;
}

function addEntryPointLI (listItem, j){
	
  var pointname = document.createElement('input') ;
  pointname.id = 'entrypoint_name_'+ j ; pointname.name = pointname.id ;
  pointname.value = trails[I].entrypoints[j].entryname ; 
  var lat = document.createElement('input') ;
	  lat.id = 'entrypoint_lat_'+j ; lat.name = lat.id ;
	  lat.value = trails[I].entrypoints[j].lat ;
	  var lng = document.createElement('input') ;
	  lng.id = 'entrypoint_lng_'+j ; lng.name = lng.id ;
	  lng.value = trails[I].entrypoints[j].lng ;
    var editonmap = document.createElement('input') ;
		editonmap.id = 'entrypoint_edit_'+j ; editonmap.name = editonmap.id ;
		//editonmap.name = 'entrypoint_edit_'+j ;
		editonmap.type = 'checkbox' ;
		//editonmap.innerText = 'edit on map' ;
		editonmap.onclick = function () {
			lat.readOnly = ( editonmap.checked ) ;
			lng.readOnly = lat.readOnly ;
  	  
      trails[I].entrypoints[j].marker.closeToolTip();
  	  map.removeOverlay(trails[I].entrypoints[j].marker) ;
	    trails[I].entrypoints[j].marker = null ;
	    addHighlightedMarker(I,j, ( editonmap.checked )) ;	
      
			return true ; 
		} ;	
		
  var del = document.createElement('input') ;
	del.id = 'entrypoint_del_'+j ; del.name = del.id ;
	del.type = 'checkbox' ;
	del.onclick = function () {
		pointname.disabled = ( del.checked ) ;
		lat.disabled = pointname.disabled ;
		lng.disabled = pointname.disabled ;
		editonmap.disabled = pointname.disabled ;
		
		if ( del.checked ) {
			// remove marker
			trail = trails[I] ;	
			trail.entrypoints[j].marker.closeToolTip();
			map.removeOverlay(trail.entrypoints[j].marker) ;
			trail.entrypoints[j].marker = null ;			
		} else {
			// add marker
			addHighlightedMarker(I,j,( editonmap.checked )) ;	
		}
		return true ; 
	} ;				
			 
      listItem.appendChild(del);
      listItem.appendChild(pointname);
      listItem.appendChild(lat);
      listItem.appendChild(lng);
			listItem.appendChild(editonmap) ;
			listItem.appendChild(document.createTextNode('edit on map')) ;
      	
}

function btnAddRouteClick () {
  var getVars = "?trailid=" + trails[I].trailid ;
  
  var request = GXmlHttp.create() ;
  request.open('GET', "http://"+location.host+"/v0.2/addroute.php"+getVars, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
			var xmlDoc = request.responseXML ;
			var responseNode = xmlDoc.documentElement ;
			var responseType = responseNode.getAttribute("type");
			var content = responseNode.firstChild.nodeValue ;
			
			if(responseType!='success') {
				alert("Error: "+content) ;
			} else {
        //var newroute ;
        //eval(content) ;
   			//alert ('success: '+content) ;
				//var k = trails[I].routes.length ;
				//trails[I].routes[k] = newroute ;
				
        // add route to display
				// ...
        getTrailData(I) ;
			}
    }
  }
  request.send(null) ;
  return false ;  
}

function btnAddTrailClick () {
  var newLocation = getNewLocation () ;
  var getVars = "?lat=" + newLocation.lat() + "&lng=" + newLocation.lng() ;
  
  var request = GXmlHttp.create() ;
  request.open('GET', "http://"+location.host+"/v0.2/addtrail.php"+getVars, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
			var xmlDoc = request.responseXML ;
			var responseNode = xmlDoc.documentElement ;
			var responseType = responseNode.getAttribute("type");
			var content = responseNode.firstChild.nodeValue ;
			
			if(responseType!='success') {
				alert("Error: "+content) ;
			} else {
				//alert ('success: '+content) ;
				var i = trails.length ;
				trails[i] = { 'trailid': content, 'accesspoints':[] } ;
				setMarkersTransparent () ;
				getTrailData(i, true) ;
			}
    }
  }
  request.send(null) ;
  return false ;  
}

function btnDeleteTrailClick () {
  if (I == -1) {
    alert('I == -1') ;
  }  

	// ask are you sure
	if ( ! confirm("Are you sure you want to delete this trail?") ) return false ;
	// delete trail
  var getVars = "?trailid=" + trails[I].trailid ;
  
  var request = GXmlHttp.create() ;
  request.open('GET', "http://"+location.host+"/v0.2/deltrail.php"+getVars, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
			if ( request.responseText == 'success' ) {
				// remove trail from trails variable
        var oldtrail = trails[I] ;
				trails.splice(I,1) ;
				// remove markers
				for (j in oldtrail.entrypoints) {
					var marker = oldtrail.entrypoints[j].marker ;
					if ( ! marker ) continue ;
					marker.closeToolTip();
					map.removeOverlay(marker) ;
					oldtrail.entrypoints[j].marker = null ;
					//addHighlightedMarker(trail, j) ;
				}
        oldtrail = null ;
			  // load blank trail
				setBlankTrailData () ;
			}
    }
  }
  request.send(null) ;
	return false ;
}

function btnSaveHomeClick (){
  var home = map.getCenter () ;	

//	alert(domain) ;
  setCookie( 'homell', home.toUrlValue(), 90, locpath, locdomain, 0 ) ;	
  setCookie( 'homez', map.getZoom(), 90, locpath, locdomain, 0 ) ;
	
	//alert(home.toUrlValue()+', '+map.getZoom()) ;
	return false ;
}


function init() {
	locpath = document.location.pathname ;
	locpath='/'+locpath.split('/')[1]+'/' ;
//	alert(path) ;
	var domainarray = document.location.host.split('.') ; domainarray[0]=''; 
	locdomain = domainarray.join('.') ;	
	locpath = '/v0.2/' ;
	locdomain = 'www.wikitrails.co.za' ;

  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GSmallMapControl());
    //map.addControl(new GMapTypeControl());

  	var homell = getCookie('homell') ; if ( !homell ) homell = '-29.25,24.9' ;
	  var homez = getCookie('homez') ; if ( !homez ) homez = '5' ;

    homell = homell.split(',') ;
    var location = new GLatLng(homell[0], homell[1]) ;
    map.setCenter(location, parseInt(homez));
  }


  // initialisation
  document.getElementById("btnEdit").onclick = btnEditClick ;
  document.getElementById("wtSave").onclick = btnSaveClick ;
  document.getElementById("wtCancel").onclick = btnCancelClick ;
  document.getElementById("btnDeleteTrail").onclick = btnDeleteTrailClick ;
  document.getElementById("btnAddTrail").onclick = btnAddTrailClick ;
  document.getElementById("btnAddRoute").onclick = btnAddRouteClick ;
	
  document.getElementById("btnSaveHome").onclick = btnSaveHomeClick ;
	
	
	//document.getElementById("idtextarea").onkeyup = "AdjustRows(this)" ;	

  // implementation
	getMapData (initialtrailid) ;

  // trail name
	setBlankTrailData () ;
 
  // remove 'Loading' message
	changeClass(document.body,'loading', 'standby' ) ;


}

window.onload = init ;
window.onunload = GUnload ;
