/*************************************************************************************************************************
Copyright - Stephen D. Miller, TexasTailchaser.com 

The content on the TexasTailchaser.com and all web pages therin, including without limitation, the text, software, scripts, 
graphics, photos, sounds, videos, interactive features and the like ("Content") and the trademarks, service marks and logos 
contained therein ("Marks"), are owned by or licensed to TexasTailchaser.com, subject to copyright and other 
intellectual property rights under United States and foreign laws and international conventions. Content on the Website is provided 
to you AS IS for your information and personal use only and may not be used, copied, reproduced, distributed, transmitted, broadcast, 
displayed, sold, licensed, or otherwise exploited for any other purposes whatsoever without the prior written consent of Stephen D.Miller, TexasTailchaser.com. 
TexasTailchaser.com reserves all rights not expressly granted in and to the Website and the Content. 

Any violations are not protected, recognized, permissable, classified, or permitted under "Fair Use" and "Public Domain" claims. 

In plain english, you are not allowed to copy or download ANY of the underlying code (HTML, CSS, Javascript, AJAX, etc) for ANY use whatsoever. 
Go write your own code!!!
***************************************************************************************************************************/


// Group to receive data from
var groupName = "Tailchasers";
var lastUpdated = new Date();

// Get only users online last 60min
var lastOnlineThreadsHoldMinutes = 60;

// Check for position updates each 30sec
var updateIntervalMS = 30000;

//holds current position
var gGpsPosition;
var gGpsPositionLoaded = false;

var userDictionary = [];
var markerDictionary = [];

var map = null;

var getGPDUsersCount = 1;

function getGPSUsers()
{
	// Get users who has been online last 60min in group 'gpsgate.com' from the server
	GpsGate.Server.MyService.getUpdatedUsersInGroup(groupName, lastUpdated, getUpdatedUsersInGroup_callback);
	
	// Callback function
	function getUpdatedUsersInGroup_callback(result)
	{
		// Set last update to the time when the query was executed on the server
		// this will make next call to only get users with new positions since this call
		lastUpdated = result.queryTimeStamp
		lastUpdated.setMinutes(lastUpdated.getMinutes() -5);
		
		// Iterate through the result of gateUsers
		for(var i = 0; i < result.users.length; i++)
		{
			var user = result.users[i];
			// Add user to dictionary
			userDictionary[user.username] = user;
		}
			
		// if we got any new users, repaint the map
		if(result.users.length > 0)
		{
			// Repaint the map with new positions
			repaintMap();
		}else{
			getGPDUsersCount++;
			if(getGPDUsersCount > 5) {
				document.getElementById("lastGPSTimestamp").innerHTML = "GPS not active.";
				getGPDUsersCount = 0;
			}
		}
		
		// make a new call to the server in n sec
		setTimeout(getGPSUsers, updateIntervalMS);
	}
}

function repaintMap()
{		
	for(var username in userDictionary)
	{
		// Get the user from dictionary
		var user = userDictionary[username];
		
		// Get the latest position from the user
		var lat = user.trackPoint.position.latitude;
		var lng = user.trackPoint.position.longitude;
		
		// Create a marker
		gGpsPosition = new GLatLng(lat, lng);
		
		var marker = markerDictionary[username];
		
		if(marker == null)
		{
			marker = new GMarker(gGpsPosition);
			
			// Add InfoWindow when click on marker
			GEvent.addListener(marker, "click",
				GEvent.callbackArgs(marker, function(user)
				{
					var htmlString = "<div class='text'><strong>Username:&nbsp;</strong>" 
									 + user.username 
									 + "<br>"
									 + "<strong>Last updated pos:</strong>"
									 + "<br>"  
									 + user.trackPoint.utc.toLocaleDateString() 
									 + "<br>"
									 + user.trackPoint.utc.toLocaleTimeString();
									 + "</div>";
									
					this.openInfoWindowHtml(htmlString);
				},
				user
			));			
			markerDictionary[username] = marker;
			gMap.addOverlay(marker);
			centerMap();		
		}
		else
		{
			marker.setPoint(gGpsPosition);
			centerMap();
		}
	}
}

function centerMap() {
	gGpsPositionLoaded = true;
	document.getElementById("lastGPSTimestamp").innerHTML = "GPS Updated: <br>" + dateFormat(lastUpdated);
	if(autoCenterOnChaser)
		gMap.setCenter(gGpsPosition, gMap.getZoom());
}


function dateFormat(date) {

	hours = padZeros(date.getHours());
	minutes = padZeros(date.getMinutes());
	secs = padZeros(date.getSeconds());
	month = padZeros(date.getMonth() + 1);
	days = padZeros(date.getDate());
	year = date.getYear();
	
	var ap = "AM";
	if (hours   > 11) { ap = "PM";        }
	if (hours   > 12) { hours = hours - 12; }
	if (hours   == 0) { hours = 12;        }

	return hours + ":" + minutes + ":" + secs + " " + ap + " " + month + "/" + days + "/" + year;
	
}

function padZeros(val) {
	if(val < 10) 
		return "0" + val;
	else
		return val;
}


//triggered by user
function centerOnChaser(obj) {
	if(obj.className == "autoCenterOff") {
		if(autoCenterRadar) {//turn off auto-center radar
		}
		obj.className = "autoCenterOn";
		obj.innerText = "Turn GPS-Center OFF";
		document.getElementById("autoCenterRadar").style.visibility = "hidden";
		autoCenterOnChaser = true;
		centerMap();
	}else{
		autoCenterOnChaser = false;
		obj.className = "autoCenterOff";
		obj.innerText = "Turn GPS-Center ON";
		document.getElementById("autoCenterRadar").style.visibility = "visible";
	}		
}

var loadNearestRadarTimerValue;

function loadNearestRadar() {
	if(gGpsPositionLoaded) {
		if(gAutoLoadNearestRadar) {
			var closestCity = "AMA";
			var closestCityMeters = 100000;
			for(i=0; i<cityArray.length; i++) {
				meters = getCenterPoint(cityArray[i]).distanceFrom(gGpsPosition);
				if(meters < closestCityMeters) {
					closestCityMeters = meters;
					closestCity = cityArray[i];
				}
			}
			if(closestCity != gRadarCity) {
				gRadarCity = closestCity;
				loadRadar();
			}
		}
		loadNearestRadarTimerValue = 900000;
	}else{
		loadNearestRadarTimerValue = 1000;
	}
	window.setTimeout("loadNearestRadar()", loadNearestRadarTimerValue);
}
