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 = $H();
var tagsOn; // just a list (non-associative) of tag IDs that are currently active.


function rN() {
	return Math.floor(Math.random()*1000000000);
}

function onLoad() {
	
	
	var myLatlng = new google.maps.LatLng(48.341646,13.974609);
	var myOptions = {
	  zoom: 4,
	  center: myLatlng,
	  mapTypeId: google.maps.MapTypeId.HYBRID,
	  scaleControl: true,
	  mapTypeControl: true,
	  mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
	};

	map = new google.maps.Map(document.getElementById("map"), myOptions);

		
	google.maps.event.addListener(map, 'dragstart', function() {
	    dragged=true;
	  });
	
	google.maps.event.addListener(map, 'click', function() {
		if ($('teamInfo').visible()) Effect.BlindUp('teamInfo', { duration: 0.5 });	
	  });
	
	
	resize();
	
	if (teams.values().length > 0) { 
		var sw = new google.maps.LatLng(swLat, swLon);
		var ne = new google.maps.LatLng(neLat, neLon);
		var bounds = new google.maps.LatLngBounds(sw, ne);
		map.fitBounds(bounds);
	}
	
	
	new Ajax.Request('RaceAJAX',
			  { method:'post',
			    parameters: {a: "c", random: rN()},
			    onSuccess: courseResponse});

	pollUpdates();
	timer = new PeriodicalExecuter(pollUpdates, 60);
	
	refreshTags();
	
	endBigWait();
	
	loadGribData();
	
	new Tip($('clock'), "This clock tells you when the positions on the map were last updated.", {
		title: "Last Update Time",
		hook: { tip: 'topLeft', mouse: true },
		offset: { x: 14, y: 14 },
		delay: 0,
		style: 'racetip',
		width: 170
	});
	
	if ($('gribClock')) {
		new Tip($('gribClock'), "This clock tells you the current GRIB (wind) overlay you're viewing.", {
			title: "GRIB (Wind) Time",
			hook: { tip: 'topLeft', mouse: true },
			offset: { x: 14, y: 14 },
			delay: 0,
			style: 'racetip',
			width: 170
		});
	}
	
	
	
}

function clickTag(tag) {
	
	if (tagsOn.indexOf(tag) == -1 && tagsAll.indexOf(tag) > -1) {
		tagsOn.push(tag);
	} else {
		tagsOn = tagsOn.without(tag);
	}
	refreshTags();
}

function refreshTags() {
	tagsAll.each(function(tag) {
		if (tagsOn.indexOf(tag) > -1) {
			$('tag_' + tag).src="img/checkbox_on.gif";
		} else {
			$('tag_' + tag).src="img/checkbox_off.gif";
		}
	});
	teams.values().each(function(team) {
		team.checkTags();
	});
}

var cma = new Array();
function courseResponse(t) {


	
	if (t.responseText != "") {
		var r = eval('(' + t.responseText + ')');
		
		var stages = r.stages; // line sections array

		for (i=0; i<stages.length; i++) {
			var stageNodes = stages[i].nodes;

			var llArray = new Array();
			
			for (j=0; j<stageNodes.length; j++) {
				var stageNode = new google.maps.LatLng(stageNodes[j].a, stageNodes[j].o);
				llArray.push(stageNode);
				
				if (stageNodes[j].n && stageNodes[j].n.length > 1 && !stageNodes[j].n.startsWith(".")) {
					var cm = Object();
					cm.a = stageNodes[j].a;
					cm.o = stageNodes[j].o;
					cm.n = stageNodes[j].n;
					
					cma.push(cm);
				}
				
			}	
			
			if (stages[i].colour != "000000") {
				 var course = new google.maps.Polyline({
					    path: llArray,
					    strokeColor: "#" + stages[i].colour,
					    strokeOpacity: 0.4,
					    strokeWeight: 10,
					    geodesic: true
					  });

				 course.setMap(map);
			}
		}
	
	}
	
	cma.each(function(cm) {
		
		var marker = new google.maps.Marker({
		      position: new google.maps.LatLng(cm.a, cm.o),
		      map: map,
		      icon: new google.maps.MarkerImage("img/yellow-buoy.png", new google.maps.Size(13, 13), new google.maps.Point(0,0), new google.maps.Point(6,6)), shadow: new google.maps.MarkerImage('img/shadow-yellow-buoy.png', new google.maps.Size(20, 13), new google.maps.Point(0, 0), new google.maps.Point(6, 6))
		  	});
		
		google.maps.event.addListener(marker, 'mouseover', function() {

			new Tip($('map'), cm.n, {
				title: "Racing Mark",
				hook: { tip: 'topLeft', mouse: true },
				offset: { x: 14, y: 14 },
				delay: 0,
				style: 'racetip',
				width: 170
			});
			
		});

		google.maps.event.addListener(marker, 'mouseout', function() {
			if ($('map').prototip) $('map').prototip.remove();
		});
	
		
	});
	
	
	
}


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 + ')');
	
	if (liveMode && r.d) {
		$('clock').innerHTML = r.d;
	}	
	
	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 google.maps.LatLng(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.set(com[i].p.id, com[i].p);
			lastTeamOver.over();
			
		} else if (com[i].a == "refresh") {
			location.reload(true);
		}
	}
	
	
	
	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 viewport = document.viewport.getDimensions(); // Gets the viewport as an object literal
	var width = viewport.width; // Usable window width
	var height = viewport.height; // Usable window height
	
	
	//var height = getWindowHeight() - offsetTop;
	if (height >= 0) {
		$('map').style.height = height + "px";
		$('wait').style.height = height + "px";
		$('waitFade').style.height = height + "px";
		$('spinner').style.margin = (height/2 -40) + "px auto 0 auto";
		if ($('tags')) {
			$('teams').style.height = ((height-5)-$('tags').getHeight()) + "px";
		} else {
			$('teams').style.height = (height-5) + "px";
		}	
		$("togglePanel").style.padding = (height/2 -3) + "px 0 0 0"; 
		$("teamInfo").style.width = width/2 + "px";
		$("teamInfo").style.left = (200 + ($('map').getWidth()/2)) - ($('teamInfo').getWidth()/2) + "px";
		$("time").style.left = (200 + ($('map').getWidth()/2)) - ($('time').getWidth()/2) + "px";
		
	}
	
	resizeSlider();
	google.maps.event.trigger(map, 'resize');
}

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);
	teams.values().each(function(team) { team.moveHistory(v); });
}

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;
}

