var teams = new Hashtable();
var lastTeamOver = null;

function Team(id, name, colour, markerNo, normalMarker, lateMarker) {

	this.id = id;
	this.name = name;
	this.colour = colour;
	this.markerNo = markerNo;
	this.normalMarker = normalMarker;
	this.lateMarker = lateMarker;

	this.trackVisible = false;
	this.clinkWaiting = false;
	
	
	this.marker = null;
	this.track = new Array();
	this.position = null;
	this.history = null;

	this.latest = team_latest;
	this.moveHistory = team_moveHistory;
	this.setHistory = team_setHistory;
	this.setPosition = team_setPosition;
	this.showTrack = team_showTrack;
	this.hideTrack = team_hideTrack;
	this.clunk = team_clunk;
	this.clink = team_clink;
	this.over = team_over;
	this.aged = team_aged;
}


/*=======Private methods for internal use only========*/

function team_aged() {
	this.marker.setImage("img/markers/" + this.lateMarker + "/" + this.markerNo + ".png");
}

function team_hideTrack() {
	for (var index = 0; index < this.track.length; ++index) {
  		if (this.track[index] != null) map.removeOverlay(this.track[index]);
	}
	
	this.track = new Array();
	this.trackVisible = false;
	this.clinkWaiting = false;		
}

function team_latest() {
	if (this.position) {
		this.marker.setPoint(new GLatLng(this.position.latitude, this.position.longitude));
	}
}

function team_showTrack(track) {
	for (var index = 0; index < this.track.length; ++index) {
  		if (this.track[index] != null) map.removeOverlay(this.track[index]);
	}
	
	for (var index = 0; index < track.length; ++index) {
  	
		var points = decodeHex(track[index].p);
		var levels = decodeHex(track[index].l);
	
		var e = "new GPolyline.fromEncoded({ color: \"#" + this.colour + "\", weight: 3, opacity: 0.8, points: \"" + points + "\", levels: \"" + levels + "\", zoomFactor: 2, numLevels: 18 });";
  		var polyline = eval(e);
	
		map.addOverlay(polyline);
		this.track[index] = polyline;
	}
	
	this.trackVisible = true;
	this.clinkWaiting = false;
}

function team_setHistory(h) {
	this.history = new Array();
	for (var index = 0; index < h.length; ++index) {
  		var p = h[index];
		this.history[p.m] = p.p;
  	}	 
}

function team_moveHistory(v) {
	if (this.history) {
		while (!this.history[v] && v > 0) {
			v--;
		}
		if (this.history[v]) {
			this.marker.setPoint(new GLatLng(this.history[v].a, this.history[v].o));
			this.marker.sbdId=this.history[v].i;
		}
	}
}

function team_setPosition(position) {
	this.position = position;

	// remove old map blob
	if (this.marker) map.removeOverlay(this.marker);

	var icon = new GIcon(G_DEFAULT_ICON, "img/markers/" + this.normalMarker + "/" + this.markerNo + ".png"); 
	
	/*
	 * 
	 if (position.extra.alert) {
		// change style of 
		icon = new GIcon(G_DEFAULT_ICON, "img/markers/red/" + this.markerNo + ".png"); 
		$('team_' + this.id).style.background="#f00;";
	}
	*/
	
	// draw new map blob
	var marker = new GMarker(new GLatLng(position.latitude, position.longitude), icon);
	marker.team = this;
	
	GEvent.addListener(marker, "click", function() {
		marker.team.clink();
	});
	
	GEvent.addListener(marker, "mouseover", function() {
		marker.team.over();
	});
	
	GEvent.addListener(marker, "mouseout", function() {
		teamOut();
	});
	
	
	map.addOverlay(marker);
	this.marker = marker;
	
}


function team_clink() {
	if (this.clinkWaiting) return;
	
	if (this.trackVisible == false) startBigWait();
	this.clinkWaiting = true;
	
	var extra = "";
/*	if (!liveMode) {
		extra = "&d=" + $('daySelect').options[$('daySelect').selectedIndex].value + $('timeSelect').options[$('timeSelect').selectedIndex].value;	
	}
*/	// get route polyline
	var opt = {
	    	method: 'post',
	    	postBody: 'a=v&t=' + this.id + extra,
	    	onSuccess: pollResponse,
	    	onFailure: function(t) {
	        	alert('Error ' + t.status + ' -- ' + t.statusText);
	    	}
	}
	new Ajax.Request('RaceAJAX', opt);
	
}


function team_clunk() {
	dragged = false;
	
	if (this.marker) {
		map.panTo(this.marker.getPoint());
	}
	if (liveMode) {
		// inform server
		var opt = {
		    	method: 'post',
		    	postBody: 'a=t&t=' + this.id,
		    	onSuccess: function(t) {},
		    	onFailure: function(t) {
		        	alert('Error ' + t.status + ' -- ' + t.statusText);
		    	}
		}
		new Ajax.Request('RaceAJAX', opt);
	}
}


function team_over() {	
	
	if (!liveMode && !pCache.containsKey(this.marker.sbdId)) {
		$('status').innerHTML = "<div align=\"center\"><img src=\"img/spinner.gif\"><br><br>Please wait...</div>";

		lastTeamOver = this;
		// do AJAX
		var opt = {
		    	method: 'post',
		    	postBody: 'a=o&p=' + this.marker.sbdId,
		    	onSuccess: pollResponse,
		    	onFailure: function(t) {
		        	alert('Error ' + t.status + ' -- ' + t.statusText);
		    	}
		}
		new Ajax.Request('RaceAJAX', opt);
		return;
	} 
	
	// if we get here, we're not in live mode, and we should have a position in the cache
	var pos = this.position;
	if (!liveMode) {
		pos = pCache.get(this.marker.sbdId);
	}

	if (pos) {
		var alert = "";
		var battery = "";
		var temperature = "";
		/*if (pos.extra.alert) {
			alert = "<tr><th style=\"background-color: #f00; color: #fff;\" colspan='2'>ALERT ACTIVATED</th></tr>"
		}
		if (pos.extra.battery) {
			battery = "<tr><th>Battery:</th><td>" + pos.extra.battery + "</td></tr>";
			temperature = "<tr><th>Temp:</th><td>" + pos.extra.temperature + "</td></tr>";
		}
		*/
		
		var info = "<h4>" + this.name + "</h4><table>" + alert + "<tr><th>GPS Time:</th><td>" + pos.extra.gpsTime + "</td></tr><tr><th>Latitude:</th><td>" + pos.extra.laf + "</td></tr><tr><th>Longitude:</th><td>" + pos.extra.lof + "</td></tr><tr><th>OS Position:</th><td>" + pos.extra.os + "</td></tr><tr><th>COG/SOG:</th><td>" + pos.course + "&deg; at " + (pos.speed).toFixed(1) + " " + units + "</td></tr>" + battery + temperature + "</table>";
		$('status').innerHTML = info;
 	}
}

function teamOut() {
	$('status').innerHTML = "<h4>" + raceName + "</h4><p>Click on a team name below to centre the map on that team.  Clicking the checkbox to the right of a team turns on/off their track.</p><p>In 'Live Update' mode the most recent information is always shown so you don't need to refresh this page.</p>";
}

function ntos(n){
    n=n.toString(16);
    if (n.length == 1) n="0"+n;
    n="%"+n;
    return unescape(n);
}


function decodeHex(str){
    str = str.replace(new RegExp("s/[^0-9a-zA-Z]//g"));
    var result = "";
    var nextchar = "";
    for (var i=0; i<str.length; i++){
        nextchar += str.charAt(i);
        if (nextchar.length == 2){
            result += ntos(eval('0x'+nextchar));
            nextchar = "";
        }
    }
    return result;
    
}


function formatPos(pos) {

}

function formatAngle(a) {

}

