var serial = 0;
var intId = 0;
var stationList = new Array();
var stationCount = 0;
var latMin = 90;
var latMax = -90;
var longMin = 180;
var longMax = -180;
var expireTime = 1800000;
var autoPauseB = false;
var track = false;
var trackCall = "";
var stationCountLimit = 50;
var cn = /(^\d+$)|(^\d+\.\d+$)/;
var autoLoadInterval = 10000; // same for all pages at moment ..

// uk
var feed = "/feed.xml";
var center = new GLatLng(52.32, -1.51);
var zoom = 7;

// europe
//var feed = "/feedeurope.xml";
//var center = new GLatLng(50, 15);
//var zoom = 4;

// world
//var feed = "/feedworld.xml";
//var center = new GLatLng(52.32, -1.51);
//var zoom = 1;


resetView();
//loadStations();
startAuto();

function clearStationLimit() {
	stationCountLimit = 0;
	document.forms['tForm'].lStations.value = "";
}

function setLimitStations() {
	var fe = document.forms['tForm'].lStations.value;
	if(cn.test(fe)) {
		stationCountLimit = fe;
	} else {
		clearStationLimit();
	}
}

function autoPause(ap) {
	autoPauseB = ap;
}

function station(stationCallSign, stationOverlay, stationFLong, stationFLat, stationLastHeard) {
	this.stationCallSign = stationCallSign;
	this.stationOverlay = stationOverlay;
	this.stationFLong = stationFLong;
	this.stationFLat = stationFLat;
	this.stationLastHeard = stationLastHeard;
}


function loadStations() {

	if(autoPauseB) {
		return;
	}

	var request = GXmlHttp.create();
	var now = new Date();
	request.open('GET', feed + '?serial=' + serial + '&ts=' + now.getTime(), true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;
			var stationEl = xmlDoc.documentElement.getElementsByTagName("station");

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

	//			if(stationEl[i].getElementsByTagName("dataTypeIdentifier")[0].firstChild.data == "@") {
					//continue;
				//}
				

				var callSign = stationEl[i].getElementsByTagName("callSign")[0].firstChild.data;

				serial = stationEl[i].getElementsByTagName("serial")[0].firstChild.data;


				var digiPath = stationEl[i].getElementsByTagName("digiPath")[0].firstChild.data;
				
				var posEl = stationEl[i].getElementsByTagName("position");

				if(posEl.length > 0) { // has a position report
					var fLong = parseFloat(posEl[0].getElementsByTagName("longitude")[0].firstChild.data);
	
					var fLat = parseFloat(posEl[0].getElementsByTagName("latitude")[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 msgEl = posEl[0].getElementsByTagName("message");
					if((msgEl.length > 0) && (msgEl[0].firstChild)) { // TODO - firstChild is empty sometimes creating js error ..
						var message = msgEl[0].firstChild.data;
					} else {
						var message = "";
					}


					var symEl = posEl[0].getElementsByTagName("symbol");
					var symDesc = symEl[0].getElementsByTagName("tableDescription")[0].firstChild.data;

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


					var imgUrl = "/" + symDesc + "/" + symValue + ".gif";
					var infoHtml = "<div id='infowindow' style='white-space: nowrap;'><img src=" + imgUrl + ">&nbsp;" + callSign + "<br />" + message + "<br /><small>Digipath: " + digiPath + "</small></div>";

				  	var iMarker = createMarker(fLong, fLat, callSign, infoHtml, imgUrl);

					var stationObj = new station(callSign, iMarker, fLong, fLat, new Date());

					// see if we already have this station ..
					var oldStation = false;
					for(var n=0; n < stationList.length; n++) {
						var tCall = stationList[n].stationCallSign;
						if(tCall==callSign) {
							oldStation = true;

							// remove from map ..
							var tMarker = stationList[n].stationOverlay;
							map.removeOverlay(tMarker);

							// draw a line from the old pos to new pos if the station has moved ..
							// TODO - add some leyway here to stop detecting GPS jitter as real movement ..
							if((stationList[n].stationFLong != fLong) || (stationList[n].stationFLat != fLat)) {

								var lineMarker = createLine(stationList[n].stationFLong, stationList[n].stationFLat, fLong, fLat);
								map.addOverlay(lineMarker);
								
							}

							// overwrite old station in array
							stationList[n] = stationObj;
							break;
						}
					}

					if(!oldStation) {
						stationList.push(stationObj);
						stationCount++;
					}



				  	map.addOverlay(iMarker);
				} // end if has pos
			} // end for 

			if(stationCount > 0) {
				expireOldStations();
				document.forms['tForm'].fpStationCount.value = stationCount;
				popStationList();
			}

			if(track == true) {
				doCenterOnStation(trackCall);
			}

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


function expireOldStations() {
	var nowTime = new Date();
	var expiredStations = false;
	var p=0;
	var sLen = stationList.length;

	do {
		var stationTime = stationList[p].stationLastHeard;
		if((nowTime - stationTime) > expireTime) {
			map.removeOverlay(stationList[p].stationOverlay);
			stationList[p] = null;
			expiredStations = true;
		}
		p++;
	} while (p < sLen);

	if((stationCountLimit > 0) && (stationList.length > stationCountLimit)) {
		p = 0;
		var tLen = sLen - stationCountLimit;
		do {
			if(stationList[p] != null) {
				map.removeOverlay(stationList[p].stationOverlay);
				stationList[p] = null;
			}
			p++;
		} while (p < tLen);

		expiredStations = true;
	}

	if(expiredStations) { // compress station list array
		var nStationList = new Array();
		p = 0;
		do {
			if(stationList[p] != null) {
				nStationList.push(stationList[p]);
			}
			p++;
		} while (p < sLen);

		stationList = nStationList;
		stationCount = nStationList.length;
	}

}

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, "#0000FF", 2, 0.75);
	return glm;
}


function createMarker(fLong, fLat, callSign, infoHtml, imgUrl) {


	var iUrl = "/mcall.php?txt=" + escape(callSign) + "&iUrl=" + escape(imgUrl);

	// make another ajax call to fetch image size ..
	var sRequest = GXmlHttp.create();
	sRequest.open('GET', iUrl + '&xml=1', false);
	sRequest.send(null);
	var rXml = sRequest.responseXML;

	var w = rXml.getElementsByTagName("width")[0].firstChild.data;
	var h = rXml.getElementsByTagName("height")[0].firstChild.data;


	var icon = new GIcon();
	icon.image = iUrl;
	icon.iconSize = new GSize(w, h);
	icon.iconAnchor = new GPoint(0, h / 2);
	icon.infoWindowAnchor = new GPoint(0, h / 2);

	var point = new GLatLng(fLat, fLong);
  	var marker = new GMarker(point, icon);

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

	return marker;
}

function clearStations() {
	map.clearOverlays();
	serial = 0;
	stationCount = 0;
	stationList = new Array();
	document.forms['tForm'].fpStationCount.value = stationCount;
	var pL = document.forms['tForm'].sSelect.options.length;
	document.forms['tForm'].sSelect.options.length = 0;
	track = false;
	trackCall = "";
}

function startAuto() {
	intId = setInterval("loadStations()", autoLoadInterval);
}

function stopAuto() {
	clearInterval(intId);
}

function popStationList() {
	var p=0;
	var sc = stationList.length;
	document.forms['tForm'].sSelect.options.length = stationList.length;
	do {
		document.forms['tForm'].sSelect.options[p] = new Option(stationList[p].stationCallSign, stationList[p].stationCallSign);
		p++;
	} while(p < sc);

	sortSelect(document.forms['tForm'].sSelect);
}

function sortSelect(sObj) {
	if((sObj != null) && (sObj.options != null)) {
		var sArray = new Array();

		var oLen = sObj.options.length;
		var sI = 0;
		do {
			sArray.push(new Option(sObj.options[sI].text, sObj.options[sI].value));
			sI++;
		} while(sI < oLen);

		sArray.sort( function (a, b) {
			if(a.text < b.text) { return -1; }
			if(a.text > b.text) { return 1; }
			return 0;
			}
		);

		sI = 0;
		do {
			sObj.options[sI] = new Option(sArray[sI].text, sArray[sI].value);
			sI++;
		} while (sI < oLen);

	}
}

function trackStation() {
	stopAuto();
	track = true;
	trackCall = document.forms['tForm'].sSelect.options[document.forms['tForm'].sSelect.selectedIndex].value;
	doCenterOnStation(trackCall);
	startAuto();
}

function stopTrack() {
	track = false;
}

function centerOnStation() {
	var cStationCall = document.forms['tForm'].sSelect.options[document.forms['tForm'].sSelect.selectedIndex].value;
	if(track == true) {
		trackCall = cStationCall;
	}
	doCenterOnStation(cStationCall);
}

function doCenterOnStation(sStationCall) {

	var p = 0;
	var sLen = stationList.length;
	do {
		if(stationList[p].stationCallSign == sStationCall) {
			map.setCenter(new GLatLng(stationList[p].stationFLat, stationList[p].stationFLong), 12);
			break;
		}
		p++;
	} while (p < sLen);
	
}

function zoomAllStations() {
	track = false;
	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);
}



