var map = null;
var centerLatitude = -21.3513//-21.18992;
var centerLongitude = 165.463144//165.355; 
var startZoom = 9;
var deselectCurrent = function() {}; // ? 
var historyVisibility = new Array(0);
var currentTime = null; //contient la date-temps initial du serveur
var serverdate;
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var repeater = null;

// SERVER TIME must be adjusted on the perl php script returning server time: obtenir date serveur
// GPS time must be adjusted from UTC to Local Time on the map data 
// ESD (Emergency SIGNAL) ON
// also setup update delay in init function
// activate timer

function ajaxDateServeur(){
	var obtenirURL = 'obtenirdateserveur.php?t=4' + "&dummy=" + new Date().getTime();
		var opt = {
	    method: 'get',
	    onSuccess: function(t) {
	    	var r = eval (t.responseText);
	    },
	    onFailure: function(t) {
	     	alert('Error ' + t.status + ' ** ' + t.statusText);
	    }
	 }
		new Ajax.Request(obtenirURL, opt);
}

ajaxDateServeur();

function initializeCP(cpData){
	var imageSource = "markerIcons/markerinfo.png";
	var icon;	
	icon = new GIcon();
	icon.image = imageSource;
	icon.iconSize = new GSize(20, 34); 
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(10, 33);
	icon.infoWindowAnchor = new GPoint(7, 4);

	var point = new GLatLng(cpData.lat, cpData.lng);
	var marker = new GMarker(point, {title: cpData.cpName, icon:icon});
	
	function focusPoint() {
		marker.openInfoWindowHtml('<font color="#336600" face="Geneva, Arial, Helvetica, sans-serif">' + cpData.cpNo + '. ' + cpData.cpName  + '<br>' + cpData.info + '</font> ');
		map.panTo(point);
		return false;
	}
	GEvent.addListener(marker, 'click', focusPoint);
	map.addOverlay(marker);
}

function initializePoint(pointData) {
	// icon preloading
	/// Icon collection and preloading - ImageSource, preload and icon
	//selecting markers for teams
	var imageSource = "markerIcons/largeTDYellowIcons/marker" + pointData.teamNumber + ".png";

// ************************************** ESD
// comment the following line to remove emergency notification EDS

//if (pointData.e == 1) { //ESD
//			imageSource = "markerIcons/largeTDRedIcons/marker" + pointData.teamNumber + ".png"; //ESD	
//	} //ESD
// ************************************** ESD
			
	// Create numbered icons for each team
	var icon;	
	icon = new GIcon();
	icon.image = imageSource;
	icon.iconSize = new GSize(20, 34); 
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(10, 33);
	icon.infoWindowAnchor = new GPoint(7, 4);
	//end icon preloading	
	var point = new GLatLng(pointData.lat, pointData.lng);
	var marker = new GMarker(point, {title: pointData.teamName, icon:icon});
	var listItem = document.createElement('div');
	listItem.setAttribute("id", 't' + pointData.teamNumber);  //add attribute to each listItem:ie ID= t+teamNumber
	var listItemLink = listItem.appendChild(document.createElement('a'));

	var visible = false;
	var teamHistoryArray = new Array(0);  //matrice pour identifier les objets gmap contenant historiquedata

	listItemLink.href = "#";
	listItemLink.innerHTML = pointData.teamNumber + '. ' + pointData.teamName;

// ************************************** ESD
// Comment the following line to remove emergency notification EDS
//
//		if (pointData.e == 1) { //ESD
//		     listItemLink.style.cssText = 'background: red;';//ESD
//		}//ESD
// **********************************************
	
	var listItemColor = document.createElement('div');
	listItemColor.className = 'boiteCouleur';
	listItemColor.style.cssText= 'background:' + pointData.colorCode + ';';
	

	var focusPoint = function() {
		deselectCurrent();
		listItem.className = 'current';
		deselectCurrent = function() { listItem.className = ''; }
		//marker.openInfoWindowHtml(pointData.teamNumber + '>' + pointData.teamName + '<br>GPS time: ' + pointData.utcTime);
		marker.openInfoWindowHtml('<font color="#0000CC" face="Arial, Helvetica, sans-serif">' + pointData.teamNumber + '>' + pointData.teamName + '<br>GPS time: ' + pointData.utcTime + '<br>Lat: ' + pointData.lat + '<br>Lng: ' + pointData.lng +'</font> ');
		map.panTo(point);
		return false;
	}
	
	var triggerHistory = function () {
		display_team_polylines(pointData.teamNumber, pointData.colorCode,5,0.5);
		}

	function display_team_polylines(number,colorCode,weight,opacity) { //number is teamnumber
				
		if (historyVisibility[number] == true) {
				map.removeOverlay(teamHistoryArray[number]);
				historyVisibility[number] = false;
				listItemColor.innerHTML = '';
		}
		else {
			changeBodyClass('standby', 'loading');
			polylineEncoder = new PolylineEncoder();	// polyline encoder class in polyline.js		
			var url = "histoq.php?info="+number;
			
			GDownloadUrl(url, function(data, responseCode) {
			
				if(responseCode == 200) {		//make sure server is responding allright.
					var xml = GXml.parse(data);
			
					var histoPoints = xml.documentElement.getElementsByTagName("his");
			
					var points = new Array(0);
					for (var j = 0; j < histoPoints.length; j++) {
					points[j] = new GLatLng(parseFloat(histoPoints[j].getAttribute("lat")),
						parseFloat(histoPoints[j].getAttribute("lng")));
			
					}
				teamHistoryArray[number] = polylineEncoder.dpEncodeToGPolyline(points,colorCode,weight,opacity);
				map.addOverlay(teamHistoryArray[number]);			
				historyVisibility[number] = true;
				listItemColor.innerHTML = ' X';
				}
			
			});
		changeBodyClass('loading', 'standby');
		}
	}
	
	var mouseOverBox= function () {
	listItemColor.style.cssText= 'width: 14px; background:' + pointData.colorCode + ';';
	}

	var mouseOutBox= function () {
	listItemColor.style.cssText= 'width: 10px; background:' + pointData.colorCode + ';';
	}
	

	GEvent.addListener(marker, 'click', focusPoint);	
	listItemLink.onclick = focusPoint;

	listItemColor.onclick = triggerHistory;
	listItemColor.onmouseover = mouseOverBox;
	listItemColor.onmouseout = mouseOutBox;


	pointData.show = function() {
		if (!visible) {
			//g
			document.getElementById('sidebar-list').appendChild(listItem);
			document.getElementById('boxsidebar').appendChild(listItemColor); //add boitecouleur
			map.addOverlay(marker);
			visible = true;
		}
	}
	pointData.hide = function() {
		if (visible) {
			document.getElementById('sidebar-list').removeChild(listItem);
			map.removeOverlay(marker);
			visible = false;
		}
	}
	
	pointData.show();

}



function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}

function handleResize() {
	var height = windowHeight() - document.getElementById('toolbar').offsetHeight - 30;
	document.getElementById('map').style.height = height + 'px';
	document.getElementById('sidebar').style.height = height + 'px';
	document.getElementById('boxsidebar').style.height = height + 'px';
}

function changeBodyClass(from, to) {
	document.body.className = document.body.className.replace(from, to);
	return false;
}


function init() {

	var estcelive = false; //live update automatic off au depart
	var displayHelpFlag = false;
	var updateQty = 0; // counter of update quantity
	var autoUpdateDelay = 183;
	var safeUpdate = 100; //max number of update before unchecking update box
	
	document.getElementById('button-sidebar-hide').onclick = function() { return changeBodyClass('sidebar-right', 'nosidebar'); };
	document.getElementById('button-sidebar-show').onclick = function() { return changeBodyClass('nosidebar', 'sidebar-right'); };
	
	handleResize();
	
	map = new GMap2(document.getElementById("map"),{
	                 mapTypes : [G_SATELLITE_MAP, G_HYBRID_MAP, G_NORMAL_MAP, G_PHYSICAL_MAP]
	              });
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	map.enableScrollWheelZoom();

	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom, G_PHYSICAL_MAP);
	
	

	function ajaxRequester(){
		var racerlink = 'map_data.php?a=5' + "&dummy=" + new Date().getTime();
			var opt = {
	    	method: 'get',
	    	onSuccess: function(t) {
		                var r = eval (t.responseText);
						for(var index = 0; index < markers.length; ++index) {
						initializePoint(markers[index]);
						}
						for(var index = 0; index < checkpoints.length; ++index) {
						initializeCP(checkpoints[index]);
						}
	        },
	    	onFailure: function(t) {
	        	alert('Error ' + t.status + ' ** ' + t.statusText);
	    	}
	    }
		new Ajax.Request(racerlink, opt);
	}
	
	
	function effaceDomHtml(){
			
		var sidebarlist = document.createElement('div');
		sidebarlist.setAttribute("id", "sidebar-list");
		var boxsidebar = document.createElement('div');
		boxsidebar.setAttribute("id", "boxsidebar");
		
		$('boxsidebar').remove();
		$('sidebar-list').remove();
		document.getElementById('sidebar').appendChild(sidebarlist);
		document.getElementById('sidebar').appendChild(boxsidebar);
	}
	
	
	function redessine() {
		if (updateQty > safeUpdate) {
			repeater.stop();
			estcelive = false;
			$('boitel').style.cssText= 'background-image: url(paslive.gif);';  			
		}
		updateQty++;
		map.clearOverlays();
		//clear history flags array. everything restart
		historyVisibility = [];
		
		
		effaceDomHtml();
		ajaxRequester();
	}
	
	$('boitel').onclick = liveUpdate;
	$('helpcontrol').onclick = helpDisplay;
	
	function helpDisplay() {
		if (displayHelpFlag == false) {
			$('helpm').innerHTML = '<p><b>HELP</b><br><b>What is Auto-Update?</b><br>If checked, the browser will automatically refresh the team position without the need for refreshing the tracking page<br><br><b>Why some teams are not updating?</b><br>The tracking unit must have a clear view of the sky for triangulation and communication. If a team is in a dense forest or canyon, updates will be delayed. Delay in updates are also expected if teams are taking some rest indoors. It is also possible that antenna or tracking unit is incorrecly installed, team will be notified<br><br><b>How do I check a team specific information?</b><br>-click on team flag or name for team information. click on colored box for team tracking history<br><br><b>How is it working?</b><br>Each team carry an Isatcoms GPS-Iridium tracking unit. The unit send GPS report at predefined interval. It can also send an emergency report if requested by the team. It works anywhere on Earth.<br><br><b>Click on HELP again to close this page</b><p>';
			displayHelpFlag = true;
		}
		else {
			$('helpm').innerHTML = '';
			displayHelpFlag = false;
		}
		
	} 
	
	function liveUpdate() {
		if (estcelive == false) {
			redessine();
			repeater = new PeriodicalExecuter(redessine, autoUpdateDelay);
			estcelive = true;
			$('boitel').style.cssText= 'background-image: url(live.gif);';
		}
		else {
			if (repeater) {
				repeater.stop();
			}
			estcelive = false;
			$('boitel').style.cssText= 'background-image: url(paslive.gif);';   
		}
		
	}

	// affichage date heure debut
	function padlength(what){
		var output=(what.toString().length==1)? "0"+what : what
		return output
	}
	function displaytime(){
		serverdate.setSeconds(serverdate.getSeconds()+1);
		var datestring=montharray[serverdate.getMonth()]+" "+padlength(serverdate.getDate())+", "+serverdate.getFullYear();
		var timestring=padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes())+":"+padlength(serverdate.getSeconds());
		document.getElementById("horloge").innerHTML="Time:"+datestring+" "+timestring;
	}
	
	ajaxRequester();
	serverdate=new Date(currentTime);
	setInterval(displaytime, 1000);  //affichage date-heure avec rafraichissement et sync initial sur le server
	displaytime();
	changeBodyClass('loading', 'standby');
}

window.onresize = handleResize;


if (GBrowserIsCompatible()) {
window.onload = init;
} else {
document.write("Browser not compatible with Google MAP and Tracking application")}

