var map = null;
var timer = null;
var liveMode = true;
var dragged = false;
var slider = null;
var raceStart = new Date();
var slideDate = new Date();
var pCache = new Hashtable();

function onLoad() {
	
    map = new GMap2($('map'));
	map.addControl(new GLargeMapControl3D());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	map.addControl(new GOverviewMapControl());
	
	//map.enableScrollWheelZoom();
	map.addMapType(G_SATELLITE_3D_MAP);
	map.addMapType(G_PHYSICAL_MAP);
	  
	GEvent.addListener(map, "dragstart", function() {
		dragged=true;
	});
		
	resize();
	
	if (teams.values().length == 0) { 
		map.setCenter(new GLatLng(48.341646,13.974609), 4);
	} else {
		var sw = new GLatLng(swLat, swLon);
		var ne = new GLatLng(neLat, neLon);
		var bounds = new GLatLngBounds(sw, ne);
		var z = map.getBoundsZoomLevel(bounds);
		if (z > 10) z = 10;
		map.setCenter(new GLatLng(cLat, cLon), z, G_HYBRID_MAP);
	}
	
	
	//map.setMapType(G_HYBRID_MAP);
	drawCourse();
	pollUpdates();
	timer = new PeriodicalExecuter(pollUpdates, 60);
	
	
	endBigWait();
	if (teams.values().length == 0) { 
		tb_show('','/raceLogin.jsp?height=200&width=500','');
	}
}

function pollUpdates() {
	var opt = {
	    	method: 'post',
	    	postBody: 'a=r',
	    	onSuccess: pollResponse,
	    	onFailure: function(t) {
	        	//alert('Error ' + t.status + ' -- ' + t.statusText);
	    	}
	}
	new Ajax.Request('RaceAJAX', opt);
}


function pollResponse(t) {
	
	if (t.responseText.indexOf("NO-COOKIE") != -1) {
		$('clickyHack').style.display="";
		return;
	}
	
	var r = eval('(' + t.responseText + ')');
	var com = r.com;
	for (i=0;i<com.length;i++) {
		
		if (com[i].a == "p") {
			teams.get(com[i].t).setPosition(com[i].p);
			if (com[i].c && !dragged) {
				map.panTo(new GLatLng(com[i].p.latitude, com[i].p.longitude));
			}
			
		} else if (com[i].a == "xx") {
			raceStart.setTime(com[i].s + 3600000);  // DST bodge!
			$('sliderC').style.display="";
			slider = new Control.Slider(	'handle',
							'slider',
							{	axis:'horizontal', 
								range:$R(0,com[i].e), 
								sliderValue:com[i].e, 
								onSlide:slide, 
								onChange:slideChange
							});
			
		} else if (com[i].a == "x") {
			teams.get(com[i].t).setHistory(com[i].d);
			
		} else if (com[i].a == "l") {  
			teams.get(com[i].t).showTrack(com[i].l);
			$('i_' + com[i].t).src="img/checkbox_on.gif";
			
		} else if (com[i].a == "v") {
			teams.get(com[i].t).hideTrack();
			$('i_' + com[i].t).src="img/checkbox_off.gif";

		} else if (com[i].a == "a") {
			teams.get(com[i].t).aged();
		
		} else if (com[i].a == "o") {
			pCache.put(com[i].p.id, com[i].p);
			lastTeamOver.over();
			
		} else if (com[i].a == "refresh") {
			location.reload(true);
		}
	}
	
	if (liveMode && r.d) {
		$('clock').innerHTML = r.d;
	}	
	
	endBigWait();
}


function getWindowHeight() {
	if (window.self && self.innerHeight) {
		return self.innerHeight;
	}
	if (document.documentElement && document.documentElement.clientHeight) {
		return document.documentElement.clientHeight;
	}
	return 0;
}

function getWindowWidth() {
	if (window.self && self.innerWidth) {
		return self.innerWidth;
	}
	if (document.documentElement && document.documentElement.clientWidth) {
		return document.documentElement.clientWidth;
	}
	return 0;

}



function hideC() {
	var cElem = $("control");
	var mapElem = $("map");
	var togElem = $("togglePanel");
	mapElem.style.left="5px";
	mapElem.style.margin="0 5px 0 0";
	cElem.style.display="none";
	togElem.style.left="0px";
	$("panelhidearrow").src="img/show-arrow.png";
	$("panelhidelink").href="javascript: showC();";
	
	$('sliderC').style.left="30px";
	resizeSlider();

}

function showC() {
	var cElem = $("control");
	var mapElem = $("map");
	var togElem = $("togglePanel");
	mapElem.style.left="205px";
	mapElem.style.margin="0 205px 0 0";
	cElem.style.display="";
	togElem.style.left="200px";
	$("panelhidearrow").src="img/hide-arrow.png";
	$("panelhidelink").href="javascript: hideC();";
	
	$('sliderC').style.left="230px";
	resizeSlider();
}

function resizeSlider() {
	var sub = 255;
	if ($("control").style.display=="none") {
		sub = 55;
	}
	$('slider').style.width = (getWindowWidth() - sub) + "px";
	if (slider) {
		slider.trackLength = slider.maximumOffset() - slider.minimumOffset();
		slider.setValue(slider.value);
	}		
}

function resize() {
	var offsetTop = 0;
	var mapElem = $("map");
	var waitElem = $("wait");
	
	for (var elem = mapElem; elem; elem = elem.offsetParent) {
		offsetTop += elem.offsetTop;
	}
	var height = getWindowHeight() - offsetTop;
	if (height >= 0) {
		mapElem.style.height = height + "px";
		$('wait').style.height = height + "px";
		$('waitFade').style.height = height + "px";
		$('spinner').style.margin = (height/2 -40) + "px auto 0 auto";
		$("teams").style.height = (height-200) + "px";
		$("togglePanel").style.padding = (height/2 -3) + "px 0 0 0"; 
	}
	
	resizeSlider();
}

function liveClicked() {
	startBigWait();
	
	if (!liveMode) {
		
/*		$("daySelect").disabled=true;
		$("timeSelect").disabled=true;
*/		
		$('sliderC').style.display="none";
		
		var t = teams.values();
		for (var index = 0; index < t.length; ++index) {
  			var tm = t[index];
			tm.latest();
		}
		
		pollUpdates();
		timer = new PeriodicalExecuter(pollUpdates, 60);

		liveMode = true;
		$("liveCheck").src="img/checkbox_on.gif";
		
	} else {
	
		// stop timer
		timer.stop();
		liveMode = false;
		$("liveCheck").src="img/checkbox_off.gif";
		
		var opt = {
	    		method: 'post',
	    		postBody: 'a=x',
	    		onSuccess: pollResponse,
	    		onFailure: function(t) {
	        		//alert('Error ' + t.status + ' -- ' + t.statusText);
	    		}
		}
		new Ajax.Request('RaceAJAX', opt);
	}
}

/*
function dateChanged() {
		$("timeSelect").disabled=true;

		var opt = {
	    		method: 'post',
	    		postBody: 'a=d&d=' + $('daySelect').options[$('daySelect').selectedIndex].value,
	    		onSuccess: pollResponse,
	    		onFailure: function(t) {
	        		alert('Error ' + t.status + ' -- ' + t.statusText);
	    		}
		}
		new Ajax.Request('RaceAJAX', opt);
	
}


function submitDate() {
	startBigWait();
	$("daySelect").disabled=true;
	$("timeSelect").disabled=true;
	
	var opt = {
	    		method: 'post',
	    		postBody: 'a=h&d=' + $('daySelect').options[$('daySelect').selectedIndex].value + $('timeSelect').options[$('timeSelect').selectedIndex].value,
	    		onSuccess: pollResponse,
	    		onFailure: function(t) {
	        		alert('Error ' + t.status + ' -- ' + t.statusText);
	    		}
		}
		new Ajax.Request('RaceAJAX', opt);
}
*/

function startBigWait() {
	$('waitFade').style.display="";
	$('wait').style.display="";
}

function endBigWait() {
	$('waitFade').style.display="none";
	$('wait').style.display="none";
}

function slide(v) {
	v = v.toFixed(0);
	
	slideDate.setTime(raceStart.getTime() + v*60000);
	$('clock').innerHTML=formatDate(slideDate);
}

function slideChange(v) {
	v = v.toFixed(0);
	
	slideDate.setTime(raceStart.getTime() + v*60000);
	$('clock').innerHTML=formatDate(slideDate);
	
	var t = teams.values();
	for (var index = 0; index < t.length; ++index) {
  		var tm = t[index];
		tm.moveHistory(v);
	}
}

function formatDate(d) {
	return Days[d.getDay()] + ", " + leadingZero(d.getDate()) + "/" + leadingZero(d.getMonth()+1) + " " + leadingZero(d.getHours()) + ":" + leadingZero(d.getMinutes()) + ":" + leadingZero(d.getSeconds());	
}

var Days = new Array('Sun','Mon','Tue','Wed',
	'Thu','Fri','Sat');


function leadingZero(nr)
{
	if (nr < 10) nr = "0" + nr;
	return nr;
}
