var map;
//var geocoder;
//var address;
var contextmenu;

var points = new Array();
var geepoints = new Array();
var llpoints = new Array();
var polyline;

var lwidth = 2;
var lcolor = "#0000FF";
var lopac = 0.5;
var tcolor;

var clat=22.380555501421533;
var clng=114.14794921875;
var zoom=12;
var stype=1;
var isCaveSatMap=0; // custom map checking

var _globals = new Array();
var winW;
var winH;
var map_width;
var map_height;

_globals['show_flickr']=0;
_globals['full_screen']=1;
_globals['play']=1;
_globals['selected_walker']='';
_globals['status']='';
_globals['realtime_mode']=0;
_globals['arrow_interval']=2;
_globals['event_started']=0;
_globals['play_direction']=0; 
_globals['play_stop']=0;
_globals['user_flickr']='';
_globals['user_picasa']='';
_globals['user_picasa_album']='';
_globals['photo_counter']=0;
_globals['last_photo']='';
_globals['selected_photo']='';
_globals['qstart_time']='';
_globals['qend_time']='';

var TrackXMLDoc = new Array();
var FlickrXMLDoc = new Array();


function get_window_size(){
	winW = (window.innerWidth) ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : document.body.offsetWidth;
	winH = (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.offsetHeight;

	map_width= (winW-250) + "px";	
	map_height= (winH) + "px";
	
	alert("Width:"+winW+","+"Height:"+winH);
	alert("MapWidth:"+map_width+","+"MapHeight:"+map_height);	
	alert("Thumbnail:"+document.getElementById("flickr_windows").style.top);

}


function setThisMapType(){
	if (stype==0){
	  map.setMapType(G_NORMAL_MAP);
	  return G_NORMAL_MAP;
	}	  
	if (stype==1){
	  map.setMapType(G_SATELLITE_MAP);
	  return G_SATELLITE_MAP;
	}  
	if (stype==2){
	  map.setMapType(G_HYBRID_MAP);	
	  return G_HYBRID_MAP;
	}  
}

function positionOverview(x,y) {
	var omap=document.getElementById("map_overview");
	omap.style.left = x+"px";
	omap.style.top = y+"px";
	
	// == restyling ==
	omap.firstChild.style.border = "1px solid gray";
	
	omap.firstChild.firstChild.style.left="4px";
	omap.firstChild.firstChild.style.top="4px";
	omap.firstChild.firstChild.style.width="190px";
	omap.firstChild.firstChild.style.height="190px";
}
	  
function openwin(url) {
window.open(url,'','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
}

function where_are_you(){
	//alert("where_are_you")
	gmarkers[-1].set_center();
}

function set_center(){
	var center = map.getCenter();
	clat = map.getCenter().lat();
	clng = map.getCenter().lng();	
	//alert(map.getCenter());
}

function goto_latlon(key){
	//alert(key);
	gmarkers[key].latlng = new GLatLng(document.getElementById("gotolat").value,document.getElementById("gotolon").value);
	gmarkers[key].remove_marker();
	gmarkers[key].create_marker();
	gmarkers[key].ondragstart();
	gmarkers[key].ondragend();
}
function getCurrentMapTypeNumber(){
  var type=-1;
  for(var ix=0;ix<map.getMapTypes().length;ix++){
    if(map.getMapTypes()[ix]==map.getCurrentMapType())
      type=ix;
  }
  return type;
} 

function updateEventNo(EventNo){
	gmarkers[-1].eventno=EventNo;
}

function save_markers(){
	var str ='';
	var str2 = '';
		
	stype=getCurrentMapTypeNumber();
	zoom=map.getZoom();
	set_center();
	
	str='<markers>\n';
	
	str = str +'   <map lat="' + clat + '" lng="' + clng +'" zoom="' + zoom+'" stype="' + stype + '" />\n';

	for ( var i in gmarkers )
	{
		if (i == -1){ // walker
			str2 = str2 +'   <walker name="'+ userid + '" lat="' + gmarkers[i].get_lat() + '" lng="' + gmarkers[i].get_lng() +'" title="' + gmarkers[i].title +'" eventno="' + gmarkers[i].eventno +'" html="' + gmarkers[i].html +  '" label="' + gmarkers[i].key + '" icon="' + gmarkers[i].icon + '" image="' + gmarkers[i].image +'" image_width="' + gmarkers[i].image_width +'" image_height="' + gmarkers[i].image_height + '" />\n';		
		}else{ // markers
			str = str +'   <marker name="'+ userid + '" lat="' + gmarkers[i].get_lat() + '" lng="' + gmarkers[i].get_lng() +'" title="' + gmarkers[i].title +'" html="' + gmarkers[i].html +  '" label="' + gmarkers[i].key + '" icon="' + gmarkers[i].icon + '" image="' + gmarkers[i].image +'" image_width="' + gmarkers[i].image_width +'" image_height="' + gmarkers[i].image_height + '" />\n';			
		}
			
	}	
	
	for (var i=0;i<geepoints.length;i++){
//		str = str +'   <point lat="' + geepoints[i].lat() + '" lng="' + geepoints[i].lng() +'" html="' + i +  '" label="' + i + '" />\n';
		str = str +'   <point lat="' + geepoints[i].lat() + '" lng="' + geepoints[i].lng() +'" html="' + i +  '" label="0" />\n';
		//alert(geepoints.lat());
	}	
	//if(parser.trackcolour){		
	//	str = str +'   <line width="' + lwidth + '" color="' + lcolor +'" opac="' + lopac +'" tcolor="' + parser.trackcolour + '" />\n';			
	//}else{
		str = str +'   <line width="' + lwidth + '" color="' + lcolor +'" opac="' + lopac +'" tcolor="#000fff" />\n';			
	//}
	
	document.getElementById("xml").value=str +  '</markers>\n';	
	document.getElementById("walkerxml").value=str2 + '\n';
	//alert(document.getElementById("xml").value);
	//alert(document.getElementById("walkerxml").value);
	var have_grp_edit_right = document.getElementById("have_grp_edit_right").value;
	if (have_grp_edit_right==1){
		document.form_editor.sDate.value=document.getElementById("sDate").value;
		document.form_editor.eDate.value=document.getElementById("eDate").value;
		document.form_editor.shour.value=document.getElementById("shour").value;
		document.form_editor.smin.value=document.getElementById("smin").value;
		document.form_editor.ehour.value=document.getElementById("ehour").value;
		document.form_editor.emin.value=document.getElementById("emin").value;
		document.form_editor.location.value=document.getElementById("location").value;
		document.form_editor.UserEventNo.value=document.getElementById("UserEventNo").value;
		document.form_editor.EventGroupType.value=document.getElementById("EventGroupType").value;
		document.form_editor.name.value=document.getElementById("name").value;
		document.form_editor.Country.value=document.getElementById("Country").value;
		var oEditor = FCKeditorAPI.GetInstance('FCKeditor1') ;	
		document.form_editor.FCKeditor1.value=oEditor.GetHTML();
		document.form_editor.Device.value=document.getElementById("Device").value;
		document.form_editor.EventNature.value=document.getElementById("EventNature").value;
		document.form_editor.FlickrAccount.value=document.getElementById("FlickrAccount").value;
		document.form_editor.PicasaAccount.value=document.getElementById("PicasaAccount").value;
		document.form_editor.PicasaAlbum.value=document.getElementById("PicasaAlbum").value;		
		document.form_editor.TimeOffset.value=document.getElementById("TimeOffset").value;				
		
//alert(document.form_editor.FCKeditor1.value);
	}else{
		document.form_editor.UserEventNo.value=document.getElementById("UserEventNo").value;
		document.form_editor.Device.value=document.getElementById("Device").value;
	}
	document.form_editor.submit();
}	


function drawline(){
	if (polyline)
		map.removeOverlay(polyline);
	polyline = new GPolyline(geepoints, lcolor, lwidth, lopac);
	map.addOverlay(polyline);
}

function del_lastpoint(){
	//alert(p);
	if (p>0){
		map.removeOverlay(polyline);
		p = p - 1;
		geepoints.splice(p,1);
		points.splice(p,1);
		llpoints.splice(p,1);
		polyline = new GPolyline(geepoints, lcolor, lwidth, lopac);
		map.addOverlay(polyline);
	}else{
		alert('No points drawn');
	}
}

function delpoints(){
	var name=confirm("Delete all points?");
	if (name==true){
		p = 0;
		geepoints.length = 0;
		points.length = 0;
		llpoints.length = 0;
		map.removeOverlay(polyline);
		alert("All points deleted");
	}else{
		alert("Delete cancelled");
	}
}

function closeline(){
	if (p == 0){
		alert('No line drawn');
	}
	else if (geepoints[p-1] == geepoints[0]){
		  alert('Line already closed');
	}
	else
	{
	  map.removeOverlay(polyline);
	  geepoints[p] = geepoints[0];
	  points[p] = points[0];
	  llpoints[p] = llpoints[0];
	  p=p+1;
	  polyline = new GPolyline(geepoints, lcolor, lwidth, lopac);
	  map.addOverlay(polyline);
	//  alert("Line closed");
	}
}

function change_line(){
	
	lwidth = document.getElementById("linewidth").value;
	lcolor = document.getElementById("linecolor").value
	lopac = document.getElementById("lineopac").value
	map.removeOverlay(polyline);
	polyline = new GPolyline(geepoints, lcolor, lwidth, lopac);
	map.addOverlay(polyline);
	//alert("Line properties changed");
}

// === The basis of the arrow icon information ===
var arrowIcon = new GIcon();
arrowIcon.iconSize = new GSize(22,22);
arrowIcon.shadowSize = new GSize(1,1);
arrowIcon.iconAnchor = new GPoint(12,12);
arrowIcon.infoWindowAnchor = new GPoint(0,0);

// === Returns the bearing in degrees between two points. ===
// North = 0, East = 90, South = 180, West = 270.
var degreesPerRadian = 180.0 / Math.PI;
function bearing( from, to ) {
	// See T. Vincenty, Survey Review, 23, No 176, p 88-93,1975.
	// Convert to radians.
	var lat1 = from.latRadians();
	var lon1 = from.lngRadians();
	var lat2 = to.latRadians();
	var lon2 = to.lngRadians();
	
	// Compute the angle.
	var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
	if ( angle < 0.0 )
	angle  += Math.PI * 2.0;
	
	// And convert result to degrees.
	angle = angle * degreesPerRadian;
	angle = angle.toFixed(1);
	
	return angle;
}

// === A function to create the arrow head at the end of the polyline ===
function arrowHead(index,points,walkerid) {
	//try {		
		//alert(name);
		// == obtain the bearing between the last two points
		var p1=points[points.length-1];	
		var p2=points[points.length-2];

		if ((p1 && p2) && (p1!=p2)){
			var dir = bearing(p2,p1);
			dir = Math.round(dir) * 1;

			if (walkers[walkerid].arrow_path){
				//arrowIcon.image = "http://www.webtracker.hk/webtracks/images/"+walkers[walkerid].arrow_path+"/arrow_"+dir+".png";
				arrowIcon.image = "http://www.webtracker.hk/webtracks/images/icons/dir/1/arrow_"+dir+".png";
			}else{
				arrowIcon.image = "http://www.webtracker.hk/webtracks/images/icons/dir/1/arrow_"+dir+".png";
			}
			

			var s= walkers[walkerid].desc;
			var whtml= '<center>'+walkers[walkerid].html+ '</center><div style="font-size: 10px;" > '+"<br>"+"Last seen at: <br>"+formatTime(getDateTime(walkers[walkerid].time,'gpx'),diff);
			//whtml += '<br><br> Total Distance: '+convertx(return_a(s[13]),"dis","meter");
			whtml += '<br> Speed: '+convertx(return_a(s[2]),"speed","kmh");
			whtml += '<br> Altitude: '+return_a(s[0])+'M';					
			//whtml += '<br> Battery: '+ return_a(s[14])	+'%';
			whtml +='  <table>';
			whtml +='  <tr>';
			whtml +='    <td colspan="2"><div align="left" style="font-size:10px"><a href="javascript:show_arrow('+walkerid+','+(index-1)+')">  &lt;&lt;  &nbsp;&nbsp;</a><a href="javascript:close_info_windows();" > (Close) </a><a href="javascript:show_arrow('+walkerid+','+(index+1)+')">&nbsp;&nbsp;  &gt;&gt;  </a></div></td>';
			whtml +='  </tr>';			
			whtml +='  </table>';			 
			whtml += '</div>';	
			/*
			var marker = new GMarker(p1, arrowIcon);
			//GEvent.bind(this.marker, "mouseover", this, this.onclick);		
			GEvent.addListener(marker, "mouseover", function() {
			  marker.openInfoWindowHtml(whtml);
			});		
			map.addOverlay(marker);
			*/
			opts = {
				"index" : points.length-1,
				"icon" : arrowIcon,
				"point" :  p1,		
				"html" :  whtml					
			};	
			
			walkers[walkerid].arrows[index] = new Arrow(opts);
			walkers[walkerid].arrows[index].create_marker();
		}
	//}catch(e){
		//;;
	//}			
}

function show_arrow(walkerid,i){	
	walkers[walkerid].arrows[i].openInfoWindow();
//	var select_cell = "vhistory_"+i;
//	alert(document.getElementById("'+select_cell+'"));
//	document.getElementById(select_cell).style.background = "rgb(255,0,0)";	
	
}

// === A function to put arrow heads at intermediate points
function midArrows(points) {
	//alert(points)
	//alert(points.length)
	for (var i=1; i < points.length-1; i++) {  
	  var p1=points[i-1];
	  var p2=points[i+1];
	  var dir = bearing(p1,p2);
	  alert(p1);
	  // == round it to a multiple of 3 and cast out 120s
	  var dir = Math.round(dir/3) * 3;
	  while (dir >= 120) {dir -= 120;}
	  // == use the corresponding triangle marker 
	  arrowIcon.image = "http://www.google.com/intl/en_ALL/mapfiles/dir_"+dir+".png";
	  map.addOverlay(new GMarker(points[i], arrowIcon));
	}
}

function convertx(val,type,metrics){

	if (val=="")val=0;
	
	if (type =="dis"){ // distance 
		if (metrics=="meter") // meter
			if (val < 1){
				val = val*1000;
				return Math.round(val) + 'm';
			}else{                                
				return roundx(val,3) + 'km'  ;
			}
		if (metrics=="mile") // mile
			return roundx(val*0.6213711922,3)+ "mil";
	}
	
	if (type == "alt"){//  alt
		if (metrics=="alt_meter") // meter                           
			return roundx(val,3) + 'm';        
		if (metrics=="alt_ft") // fleet
			return roundx(val*3.280839895,3)+ "ft";
	}
	
	if (type == "speed"){ // speed
		if (metrics=="kt") // kt
			return val + "kt";        
		if (metrics=="mph") // mph
			return roundx(val*0.6213711922,1) + "mph";
		if (metrics=="kmh") // km/h
			return val + " km/h";
	}
	
	if (type == "pos") // position		
		return 	"";
}

function roundx(x,decimal){
	
	//return Math.round(x*(10^decimal))/(10^decimal);
	return Math.round(x*100)/100;	
}

function close_info_windows	(){
	map.closeInfoWindow();
}

function return_a(val){
	if (val) return val;
	else return '0';
}

function change_screen() {
	var message=document.getElementById("change_screen").innerHTML;
//	if (message == "Normal Screen") {
	if (_globals['full_screen']==0)	{
		set_normal_screen();		
		document.getElementById("change_screen").innerHTML = "Full Screen";
		_globals['full_screen']=1;		
		document.getElementById("context_full_screen").innerHTML = "&nbsp;&nbsp;Full Screen&nbsp;&nbsp;";
		
		//document.getElementById("screen").style.left = "768px";
		//document.getElementById("screen").style.top = "215px";
		document.getElementById("display").style.width = map_width;
		document.getElementById("display").style.height = map_height;
		// I.E need to hidden the select box, Firefox don't need this one.	
		document.getElementById("select_timezone").style.visibility  = "visible";	
		//document.getElementById("display").style.position = "absolute";
		//document.getElementById("display").style.left = "159px";
		//document.getElementById("display").style.top = "160px";
		//document.getElementById("coords").style.left = "768px";
		//document.getElementById("coords").style.top = "180px";
	    document.getElementById("flickr_windows").style.top  = "450x";
		window.location = "#start_here";
	}else{
		document.getElementById("screen").style.left = "850px";
		//document.getElementById("screen").style.top = map_height;		
		document.getElementById("change_screen").innerHTML = "Normal Screen";
		_globals['full_screen']=0;				
		document.getElementById("context_full_screen").innerHTML = "&nbsp;&nbsp;Normal Screen&nbsp;&nbsp;";		

		document.getElementById("display").style.height = "100%";
		document.getElementById("display").style.width = "100%";
		document.getElementById("display").style.left = "1px";
		document.getElementById("display").style.top = "1px";
		//eval('document.all.'+What+'.style.visibility ="'+ Value
		// I.E need to hidden the select box, Firefox don't need this one.				   
		document.getElementById("select_timezone").style.visibility  = "hidden";
		//document.getElementById("coords").style.left = "768px";
		//document.getElementById("coords").style.top = "32px";
		//document.getElementById("map").style.height = "100%";
		//document.getElementById("map").style.width = "100%";
		//document.getElementById("map").style.position = "absolute";	
	    document.getElementById("flickr_windows").style.top  = "500x";
		window.location = "#";
	}
		 close_contextmenu();			
}

function toggleBox(szDivID, iState) // 1 visible, 0 hidden
{
    if(document.layers)	   //NN4+
    {
       document.layers[szDivID].visibility = iState ? "show" : "hide";
    }
    else if(document.getElementById)	  //gecko(NN6) + IE 5+
    {
        var obj = document.getElementById(szDivID);
        obj.style.visibility = iState ? "visible" : "hidden";
    }
    else if(document.all)	// IE 4
    {
        document.all[szDivID].style.visibility = iState ? "visible" : "hidden";
    }
}

function view_date(which) {
	var etb = document.getElementById("flickr_windows");
	var winW = (window.innerWidth) ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : document.body.offsetWidth;
	var winH = (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.offsetHeight;

	if (etb.style.height=="") {
		//etb.style.top = "340px";
		//etb.style.height = ((winH - 350) > 90) ? (winH - 350) + "px" : "90px";
		//etb.style.width = ((winW - 31) > 100) ? (winW - 31 + "px" : "100px";
		etb.style.width = map_width;
		window.location = "#" + which;
	}
	window.location = "#" + which;
}


function set_normal_screen(page)
{
	//alert("set_normal_screen()");
	
	//alert(document.getElementById("map_here").value);
	var map_here = getAnchorPosition("map_here");  
	//alert(map_here.x);
    //alert(map_here.y);
	document.getElementById("display").style.left=map_here.x +'px';
	document.getElementById("display").style.top=map_here.y+10 +'px';  
 
	//document.getElementById("coords").style.left = map_here.x-100 +'px';
	//document.getElementById("coords").style.top = map_here.y-100 +'px';   
	if (page ==	"edit"){
		document.getElementById("screen").style.left=map_here.x+500 +'px';
		document.getElementById("screen").style.top=map_here.y-185 +'px'; 
	}else{
		document.getElementById("screen").style.left=map_here.x+500 +'px';		
		document.getElementById("screen").style.top=map_here.y-130 +'px'; 	
		document.getElementById("monitor").style.left=map_here.x-320 +'px'; 						
	}
	
	if (_globals['realtime_mode']==1){
		document.getElementById("display").style.left=map_here.x+150 +'px';   		
		document.getElementById("screen").style.left=map_here.x+500-150 +'px'; 		
		document.getElementById("monitor").style.left=map_here.x-320 +'px'; 				
	}
}

function show_div(layer,html)
{
	document.getElementById(layer).left = '250px';
	document.getElementById(layer).top = '100px';
	document.getElementById(layer).style.width = "500px";
	//document.getElementById(layer).style.height = "200px";
	document.getElementById(layer).style.position = "absolute";
	html +=  '<br><center><a href="javascript:hidden_div(\'' + layer + '\');" >(Close) </a></center>\n';		
	document.getElementById(layer).innerHTML=html;
//	document.getElementById(layer).visibility = "visible";
	toggleBox(layer,1);
}

function hidden_div(layer)
{
	//alert(document.getElementById(layer).visibility);
	//document.getElementById("lap_window").style.position = "";	
	//document.getElementById("lap_window").visibility = "hidden";
	toggleBox(layer,0);	
}

// this function is from www.geocoder.us
function calcDist(lon1,lat1,lon2,lat2) 
{
   var r = 3963.0;
   var multiplier = 1; 
   return 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));
}
// random get color
function get_color(i){
/*	
	var i = Math.round(100*Math.random())
	if (i >0 && i <=10){
		return '#FF0000'
	}else if (i >10 && i <=20){
		return '#000000'
	}else if (i >20 && i <=20){
		return '#333333'
	}else if (i >30 && i <=40){
		return '#0000FF'
	}else if (i >40 && i <=50){
		return '#990000'
	}else if (i >50 && i <=60){
		return '#993399'
	}else if (i >60 && i <=70){
		return '#CC0000'
	}else if (i >70 && i <=80){
		return '#6600CC'
	}else if (i >80 && i <=90){
		return '#666600'
	}else if (i >90 && i <=100){
		return '#0033FF'
	}else{
		return '#000000'
	}
*/
	if (i ==0){
		return '#000099';		
	}else if (i==1){
		//return '#FF0000';		
		return '#000000';
	}else if (i==2){
		return '#333333';
	}else if (i==3){
		return '#0000FF';
	}else if (i==4){
		return '#990000';
	}else if (i==5){
		return '#993399';
	}else if (i==6){
		return '#CC0000';
	}else if (i==7){
		return '#6600CC';
	}else if (i==8){
		return '#666600';
	}else if (i==9){
		return '#0033FF';
	}else{
		return '#000000'
	}	
}


function zoom_in(lat,lon){
	map.setZoom(map.getZoom()+1);
	//map.setCenter(new GLatLng(lat, lon), zoom);  
}

function zoom_out(lat,lon){
	map.setZoom(map.getZoom()-1);
	//map.setCenter(new GLatLng(lat, lon), zoom);  
}

function set_contextmenu(){
      // === create the context menu div ===
      //contextmenu = document.createElement("div");
	  contextmenu = document.getElementById("contextmenu")	  
      contextmenu.style.visibility="hidden";
      contextmenu.style.background="#ffffff";
      contextmenu.style.border="1px solid #8888FF";

      contextmenu.innerHTML = '<a href="javascript:zoomIn()"><div class="context">&nbsp;&nbsp;Zoom in&nbsp;&nbsp;</div></a>'
                            + '<a href="javascript:zoomOut()"><div class="context">&nbsp;&nbsp;Zoom out&nbsp;&nbsp;</div></a>'
							+ '<a href="javascript:change_screen()"><div class="context" id="context_full_screen">&nbsp;&nbsp;Full Screen&nbsp;&nbsp;</div></a>'
                            + '<a href="javascript:play()"><div class="context" id="context_play" >&nbsp;&nbsp;Pause&nbsp;&nbsp;</div></a>'							
                            + '<a href="javascript:play_direction()"><div class="context" id="context_play_direction" >&nbsp;&nbsp;Backward&nbsp;&nbsp;</div></a>'				
                            + '<a href="javascript:play_stop()"><div class="context" id="context_play_stop" >&nbsp;&nbsp;Stop&nbsp;&nbsp;</div></a>'											
							
                            + '<a href="javascript:WhereAreYou()"><div class="context">&nbsp;&nbsp;Where are you?&nbsp;&nbsp;</div></a>'
                            + '<a href="javascript:ShowPhotosWindows()"><div class="context" id="context_show_thumb">&nbsp;&nbsp;Hide Thumbnails&nbsp;&nbsp;</div></a>'
//                            + '<a href="javascript:close_contextmenu()"><div class="context" id="context_show_tracks">&nbsp;&nbsp;Show Tracks&nbsp;&nbsp;</div></a>'
                            + '<a href="javascript:readLaps(\''+_globals['selected_walker']+'\',1)"><div class="context">&nbsp;&nbsp;Show Laps&nbsp;&nbsp;</div></a>'
//                            + '<a href="javascript:getStatus(1002)"><div class="context">&nbsp;&nbsp;Get status&nbsp;&nbsp;</div></a>'							
                            + '<a href="javascript:close_contextmenu()"><div class="context">&nbsp;&nbsp;Close&nbsp;&nbsp;</div></a>';
							

   //   map.getContainer().appendChild(contextmenu);
	  
		

      // === listen for singlerightclick ===
      GEvent.addListener(map,"singlerightclick",function(pixel,tile) {
        // store the "pixel" info in case we need it later
        // adjust the context menu location if near an egde
        // create a GControlPosition
        // apply it to the context menu, and make the context menu visible
        clickedPixel = pixel;
        var x=pixel.x;
        var y=pixel.y;
        if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
        if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
        var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
        pos.apply(contextmenu);
        contextmenu.style.visibility = "visible";
      });
}	  
function close_contextmenu(){
	contextmenu.style.visibility="hidden";
}

function zoomIn(){

	map.zoomIn();
	close_contextmenu();
}

function zoomOut(){

	map.zoomOut();
	close_contextmenu();
}
function WhereAreYou(){

	get_walker(_globals['selected_walker']);
	close_contextmenu();
}
function ShowPhotosWindows(){
	if (_globals['show_flickr']==1){
		document.getElementById("context_show_thumb").innerHTML = "&nbsp;&nbsp;Hide Thumbnails&nbsp;&nbsp;";			
		document.getElementById("flickr_windows").style.visibility  = "visible"; 
		_globals['show_flickr']=0;		
	}else{	
		document.getElementById("context_show_thumb").innerHTML = "&nbsp;&nbsp;Show Thumbnails&nbsp;&nbsp;";				
		document.getElementById("flickr_windows").style.visibility  = "hidden";  
		_globals['show_flickr']=1;				
	}
	close_contextmenu();	
}
function play(){
	
	for (var k in walkers){	
		if (walkers[k].i >= walkers[k].trackpoints.length)
			walkers[k].i=0;
	}		
		
	if (_globals['play']==1){
		//clearTimeout();	
		document.getElementById("context_play").innerHTML = "&nbsp;&nbsp;Play&nbsp;&nbsp;";		
		_globals['play']=0;
		_globals['status']="&nbsp;Paused";
		document.getElementById("m_status").innerHTML =_globals['status'];		
		document.getElementById('play_button').src = "/webtracks/images/play_button2.png";	
		
	}else{
		_globals['play']=1;	
		_globals['play_stop']=0;		
		_globals['status']="&nbsp;Playing";		
		document.getElementById("context_play").innerHTML = "&nbsp;&nbsp;Pause&nbsp;&nbsp;";
		document.getElementById('play_button').src = "/webtracks/images/play_button1.png";			
		UpdateMap(1,_globals['selected_walker']);		
	}
	close_contextmenu();
}
function play_direction(dir){
	
	for (var k in walkers){	
		if (walkers[k].i >= walkers[k].trackpoints.length)
			walkers[k].i=walkers[k].i-rate;
	}				
		
	if (dir==1)_globals['play_direction']=0;
	if (dir==0)_globals['play_direction']=1;	
	if (_globals['play_direction']==1){
		//clearTimeout();
		document.getElementById("context_play_direction").innerHTML = "&nbsp;&nbsp;Backward&nbsp;&nbsp;";				
		_globals['play_direction']=0;
		//_globals['status']="&nbsp;Paused";
		//document.getElementById("m_status").innerHTML =_globals['status'];		
	}else{
		_globals['play_direction']=1;		
		//_globals['status']="&nbsp;Playing";		
		document.getElementById("context_play_direction").innerHTML = "&nbsp;&nbsp;Forward&nbsp;&nbsp;";				
		//UpdateMap(1,_globals['selected_walker']);		
	}
	
	_globals['play']=1;	
	_globals['play_stop']=0;		
	_globals['status']="&nbsp;Playing";		
	document.getElementById("context_play").innerHTML = "&nbsp;&nbsp;Pause&nbsp;&nbsp;";
	document.getElementById('play_button').src = "/webtracks/images/play_button1.png";			
	UpdateMap(1,_globals['selected_walker']);		
	
	close_contextmenu();
}
function play_stop(){
		document.getElementById("context_play_stop").innerHTML = "&nbsp;&nbsp;Stop&nbsp;&nbsp;";				
		_globals['play_stop']=1;
		_globals['play']=0	
		UpdateMap(1,_globals['selected_walker']);		
		close_contextmenu();		
}
function LoadGPXFileIntoGoogleMap(filename,id)
{
  //alert("Please click here to load the map")
  // Remove any existing overlays from the map.
  //map.clearOverlays();
  document.getElementById("onload_windows").style.visibility  = "visible";			  
  
  var request = GXmlHttp.create();
  request.open("GET", filename, true);
  request.onreadystatechange = function()
  {
    if (request.readyState == 4)
    {
			  
	  TrackXMLDoc = request.responseXML;
      parser = new GPXParser(TrackXMLDoc,map,id);
	  //alert("get it")
      parser.SetTrackColour(walkers[id].color);		// Set the track line colour
      parser.SetTrackWidth(3);			// Set the track line width

      //parser.SetMinTrackPointDelta(0.000);		// Set the minimum distance between track points
      //parser.CenterAndZoom(TrackXMLDoc, G_SATELLITE_MAP);	// Center and Zoom the map over all the points.
	  //alert(parser.GetGPXCreator());
	  //if (_globals['realtime_mode']==0){
	  //var newdiv = document.createElement('div');
	  //newdiv.setAttribute('id','loading_windows');
	  //newdiv.innerHTML = 'Loading the Tracking. Please wait';		  
	  //document.getElementById("loading_windows").style.visibility  = "visable";   
	  parser.AddTrackpointsToMap();			// Add the trackpoints
	 //document.getElementById("loading_windows").style.visibility  = "hidden";   
	  if (parser.havepoints>0){  
		parser.CenterAndZoom(TrackXMLDoc, setThisMapType());	// Center and Zoom the map over all the points.	  
		if (isCaveSatMap) map.setMapType(caveSatMap);		// set to custom map
	  }else{
		map.setCenter(new GLatLng(clat, clng), zoom);  		  
	  }

	  if (tcolor ) parser.ChangeTrackColor(tcolor);
	  
      //parser.AddWaypointsToMap();			// Add the waypoints
	//setTimeout('close_marker_html()',2000)	  
	document.getElementById("onload_windows").style.visibility  = "hidden";	
  	}
  }
  request.send(null);
}

function RemoveTrackLines(text){
	//alert(text);
	parser.RemovePointsFromMap();
}

function change_walker_color(name){
	parser.ChangeTrackColor();	
}

/*
Function to find the x position of the top left corner of
a given object
*/
function findPosX(obj) {
var curleft = 0;
if (obj.offsetParent) {
while (obj.offsetParent) {
curleft += obj.offsetLeft;
obj = obj.offsetParent;
}
}
else if (obj.x)
curleft += obj.x;
return curleft;
}

/*
Function to find the y position of the top left corner of
a given object
*/
function findPosY(obj) {
var curtop = 0;
if (obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
}
else if (obj.y)
curtop += obj.y;
return curtop;
}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function URLDecode(psEncodeString)
{
  // Create a regular expression to search all +s in the string
  var lsRegExp = /\+/g;
  // Return the decoded string
  return unescape(String(psEncodeString).replace(lsRegExp, " "));
}

/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object   the table row
 * @param   string   the action calling this script (over, out or click)
 * @param   string   the default background color
 * @param   string   the color to use for mouseover
 * @param   string   the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor = theMarkColor;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()) {
        if (theAction == 'out') {
            newColor = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor = theMarkColor;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor = (thePointerColor != '')
                     ? thePointerColor
                     : theDefaultColor;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function

