var positions = new Array();
var pIndex = -10;
var plotInterval = 200;
var intId;
var colorArray = new Array();
var colorIndex = -1;
var oldDate = "";
var latMin = 90;
var latMax = -90;
var longMin = 180;
var longMax = -180;

// uk
var feed = "/thist.php";
var center = new GLatLng(53.32, -4);
var zoom = 6;

// colours for different days tracks ..
colorArray.push("#0000FF");
colorArray.push("#00FF00");
colorArray.push("#FF0000");
colorArray.push("#00FFFF");
colorArray.push("#FFFF00");

resetView();

function position(fLong, fLat, marker, date) {
	this.fLong = fLong;
	this.fLat = fLat;
	this.marker = marker;
	this.date = date;
}

function init() {
	map.clearOverlays();
	positions = new Array();
	pIndex = -1;
	colorIndex = -1;
	oldDate = "";
	latMin = 90;
	latMax = -90;
	longMin = 180;
	longMax = -180;
	document.forms['tForm'].fpPositionCount.value = 0;
	resetView();
}

function loadPositions() {

	init();	

	var request = GXmlHttp.create();
	var now = new Date();
	document.forms['tForm'].fpStatus.value = "Querying ..";	

	request.open('GET', feed + '?callsign=' + document.forms['tForm'].fpCallSign.value  + '&limit=' + document.forms['tForm'].fpPositionLimit.value + '&date=' + escape(document.forms['tForm'].fpDate.value) + '&ts=' + now.getTime(), true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			document.forms['tForm'].fpStatus.value = "Processing ..";
			var xmlDoc = request.responseXML;
			var reportEl = xmlDoc.documentElement.getElementsByTagName("report");

			for (var i = 0; i < reportEl.length; i++) {

				var time = reportEl[i].getElementsByTagName("time")[0].firstChild.data;

				var date = time.slice(0, 10);

				var fLat = parseFloat(reportEl[i].getElementsByTagName("latitude")[0].firstChild.data);
				var fLong = parseFloat(reportEl[i].getElementsByTagName("longitude")[0].firstChild.data);
				var course = reportEl[i].getElementsByTagName("course")[0].firstChild.data;
				var speed = reportEl[i].getElementsByTagName("speed")[0].firstChild.data;
				var alt = reportEl[i].getElementsByTagName("alt")[0].firstChild.data;

				var tdesc = reportEl[i].getElementsByTagName("tableDescription")[0].firstChild.data;
				var codev = reportEl[i].getElementsByTagName("codeValue")[0].firstChild.data;

				// update min/max for zoom all ..
				if(fLat < latMin) {
					latMin = fLat
				}

				if(fLat > latMax) {
					latMax = fLat
				}

				if(fLong < longMin) {
					longMin = fLong
				}

				if(fLong > longMax) {
					longMax = fLong
				}


				//var symDesc = symEl[0].getElementsByTagName("tableDescription")[0].firstChild.data;
				//var symValue = symEl[0].getElementsByTagName("codeValue")[0].firstChild.data;

				var imgUrl = "/" + tdesc + "/" + codev + ".gif";
				var infoHtml = "<div id='infowindow' style='white-space: nowrap;'><img src=" + imgUrl + ">&nbsp;" + time;

				if(alt != "-1") {
					infoHtml = infoHtml + "<br />Altitude: " + alt;
				}
				if(course != "-1") {
					infoHtml = infoHtml + "<br />Course: " + course;
				}

				infoHtml = infoHtml + "</div>";

				var iMarker = createMarker(fLong, fLat, infoHtml, speed, course, i);

				var posit = new position(fLong, fLat, iMarker, date);
				positions.push(posit);

			} // end for 

			document.forms['tForm'].fpPositionCount.value = positions.length;

			// kick off delayed plotting ...
			if(positions.length > 0) {
				pIndex = 0;
				intId = setInterval("plot()", plotInterval);
				document.forms['tForm'].fpStatus.value = "Plotting ..";
			} else {
				document.forms['tForm'].fpStatus.value = "Nothing found ..";
				resetView();
			}

		} // end if readystate
	} // end function
	request.send(null);
}

function plot() {

	var position = positions[pIndex];
	var date = position.date;
        if(date != oldDate) {
        	colorIndex++;
        	if(colorIndex == colorArray.length) {
        		colorIndex = 0;
        	}
        }

	if(pIndex > 0) {
		if(date == oldDate) {
			var line  = createLine(positions[pIndex-1].fLong, positions[pIndex-1].fLat, positions[pIndex].fLong, positions[pIndex].fLat);
			map.addOverlay(line);
		}
	}
	map.addOverlay(position.marker);

	pIndex++;
        oldDate = date;

	if(pIndex == positions.length) {
		clearInterval(intId);
		zoomAll();
		document.forms['tForm'].fpStatus.value = "Done ..";
	}

}

function createLine(oldLon, oldLat, newLon, newLat) {
	var points = new Array();
	points.push(new GLatLng(oldLat, oldLon));
	points.push(new GLatLng(newLat, newLon));
	var glm = new GPolyline(points, colorArray[colorIndex], 4, 0.50);
	return glm;
}

function zoomAll() {
	if(positions.length > 0) {
		var gb = new GLatLngBounds(new GLatLng(parseFloat(latMin), parseFloat(longMin)), new GLatLng(parseFloat(latMax), parseFloat(longMax)));
		var zoomLevel = map.getBoundsZoomLevel(gb);
		map.setCenter(gb.getCenter(), zoomLevel);
	}
	
}

function resetView() {
	map.setCenter(center, zoom);
}


function createMarker(fLong, fLat, infoHtml, speed, course, zIndex) {

        var icon = new GIcon();
	icon.image = "/speed.php?speed=" + speed + "&course=" + course;
        icon.iconSize = new GSize(24, 24);
        icon.iconAnchor = new GPoint(12, 12);
        icon.infoWindowAnchor = new GPoint(12, 0);

        var point = new GLatLng(fLat, fLong);
        var marker = new GMarker(point, icon);
	//marker.setZIndex(zIndex+1);

        var event = GEvent.addListener(marker, "click", function() {
                        marker.openInfoWindowHtml(infoHtml);
        });

        return marker;
}

