//
//=FindGPSLocationByIdAndDate&id=44&from='2007-08-10%2000:00:00'&to='2007-08-17%2000:00:00'&jsonPlain=true
//
////////////////////////////////////////////////////////////////////////
//////
////// GPS Location Management
//////

var arrayGPSLocations			= new Array;
//
// Distance to recenter truck when moving and tracking/autoscroll
//
RECENTER_DISTANCE 	= 0.001;
STOPDETECT_DISTANCE = 0.001;
CLOSELOCATION_DETECT= 0.002;

function GPSLocation( id, tid, lat, lon, recorded )
{
	//
	// Object methods
	//
	//
	// Object properties
	this.m_id 				= id;
	this.m_tid 				= tid;
	this.m_lat 				= lat;
	this.m_lon				= lon;
	this.m_recorded			= recorded;
	
	arrayGPSLocations [ this.m_id ] = this;
}

function findGPSLocationById( id )
{
	for ( var oId in arrayGPSLocations )
	{
		var o = arrayGPSLocations[oId];
		if ( o != null && o.m_id == id )
			return o;
	}
	return null;
}

function OnLoadedGPSLocations( jsonArray )
{
alert("ERROR");
}

var aTruckMarkers 	= new Array;
//
// Manage truck marker pool
// as an associative array
// 
function TruckMarker( tid, lat, lon, stamp, elp)
{
	//
	// Object methods
	this.setEllapsed 	= setEllapsed;
	this.setNewLocation	= setNewLocation;
	//
	// Objects members
	this.tid 		= tid;
	this.lat 		= lat;
	this.lon 		= lon;	
	this.prev_lat 	= lat;
	this.prev_lon 	= lon;
	//
	this.status		= "No Signal";
	this.autoscroll = false;
	//
	this.routepolyline = null;
	//
	this.proximity  = "";
	this.stamp 		= stamp;
	this.ellapsed	= elp;
	//
	this.GMark		= new PdMarker( new GLatLng( lat, lon ), inactiveIcon );
	this.GMark.setTooltip( "Truck "+ this.tid + " Information " );

	//"<tr><td><img src='/tracker/images/video/tvnoise.gif' height=100><BR>"+

	var htmlTestLocation = 
	"<table width=200>"+
	"<tr><td><span class='helpertextheader'>Truck Info "+ this.tid +
	"</span></td></tr>"+
	"</table>";	

	var mark = this.GMark;
	
	GEvent.addListener(
			mark, 
			"click", 
			function() {
				mark.openInfoWindowHtml(htmlTestLocation);
			}
		);
		
	map.addOverlay( this.GMark );	
}

function centerOnTruck( tid )
{
	truckObject = aTruckMarkers[ tid ];
	if ( truckObject == null )
	{
		//alert( "centerOnTruck no truck found for "+tid)
		return;
	}
	map.setCenter( new GLatLng( truckObject.lat, truckObject.lon ) );	
}

function setNewLocation( lat, lon )
{
	//
	this.GMark.setPoint( new GLatLng( lat, lon ) );
	//
	// Update position
	this.prev_lat 	= this.lat;				
	this.prev_lon 	= this.lon;				
	this.lat 	 	= lat;				
	this.lon 	 	= lon;	
	//
	// Update position array
	//
}
var CenterFirst = false;

function setEllapsed( elp )
{
	try
		{
		//
		this.ellapsed	= elp;
		//
		// Manage position change
		//
		travel = Math.sqrt( 
						(this.lat - this.prev_lat )*(this.lat - this.prev_lat ) +
						(this.lon - this.prev_lon )*(this.lon - this.prev_lon ) 
					);
		//
		//
		distanceFromCenter = Math.sqrt( 
						(this.lat - map.getCenter().lat() )*(this.lat - map.getCenter().lat() ) +
						(this.lon - map.getCenter().lng() )*(this.lon - map.getCenter().lng() ) 
					);	
		//
		// If autoscroll set, follow this truck
		//
		if ( this.autoscroll == true )
		{
			if ( 	
					(distanceFromCenter > RECENTER_DISTANCE)
						||
					( CenterFirst == false )
				 )
				{
					map.setCenter( new GLatLng( this.lat, this.lon ) );	
					if (CenterFirst == false)
						CenterFirst = true;
				}
		}
		//
		// Manage time interval
		//
		displayTime = 0;
		//
		if ( elp > 60 * 60 * 24 ) 
			displayTime = Math.round( elp / (60 * 60 * 24 ) ) +" days";
		else
		if ( elp > 60 * 60 ) 
			displayTime = Math.round( elp / (60 * 60 ) ) +" hours";
		else
		if ( elp > 60 ) 
			displayTime = Math.round( elp / ( 60 ) )+" minutes";
		else
			displayTime = " a few seconds";
		//
		this.GMark.setTooltip( "<span class='helpertext'>Truck "+ this.tid + "<BR>Last information received "+ displayTime +" ago</span>" );
		//
		// Check if ellapsed time since last update is relevant
		if ( elp < 60 * 15 )
		{
			// Truck is online, receiving location from GPS
			this.GMark.setImage("/socialinteraction/images/truck_active.png"); //setIcon( activeIcon );
			if ( travel > STOPDETECT_DISTANCE )
				this.status		= "Moving";	
			else
				this.status		= "Stopped";	
		}
		else
		{
			// Truck not online
			this.GMark.setImage("/tracker/images/truck_inactive.png"); //setIcon( inactiveIcon );
			this.status		= "No Signal";		
		}
	}
	catch( err )
	{
	}	
}
//
//
// UPDATE POSITION USING ASYNC CALLS TO SERVER
//
//

function onUpdatedPosition( data )
{

		if ( data == null )
			return;
			
		splitPosition = data.split('*');
	
		if (splitPosition == null ) 
			return;
			
		nTrucks = splitPosition.length-1; // remove trail split
		//
		//debugInfo("updateposition got "+nTrucks+" trucks");
		//
		//
		loadTruckTid = null;
		//
		for ( i=0; i < nTrucks; i++ )
		{
			truckInfo = splitPosition[i].split(',');
			if ( truckInfo == null )
			  	return;
			//				  	
			tid = truckInfo[0];
			lat = truckInfo[1];
			lon = truckInfo[2];
			stp = truckInfo[3];
			elp = truckInfo[4];
			//
			debugInfo("updateposition Adding marker at "+lat+" "+lon+" ID="+tid);		
			//
			truckObject = aTruckMarkers[ tid ];
			if ( truckObject == null )
			{
				//alert("Adding truck "+tid );
				truckObject = new TruckMarker( tid, lat, lon, stp, elp );
				if ( loadTruckTid == null )
					loadTruckTid = 1;
			}
			//
			truckObject.setNewLocation( lat, lon );			
			truckObject.setEllapsed( elp );
			//
			aTruckMarkers[ tid ] = truckObject;
			//
		}// end for each truck
		//
		//
		if ( loadTruckTid != null )
			loadroute(loadTruckTid,BuildTodayDate());
		
		//
}

function updateposition()
{
//	debugInfo("updateposition");
//	DAO(
//		"/tracker/view/mapLog.jsp?tid=fetch&r1="+Math.random()*9999999+"&r2="+Math.random()*9999999, "onUpdatedPosition", null);
	url="http://www.homelesscoach.org/gpsLogLast.txt?"+Math.random()*9999999+"&r2="+Math.random()*9999999;
	var httpRequest = GetHTTPRequestObject();
	httpRequest.onreadystatechange = function()
	{
		if (httpRequest.readyState == 4) 
		{
			debugInfo( "DAO "+url+ " httpRequest.readyState==4 "+ httpRequest );

			daostatus = 200;
			try 
			{ 
				daostatus = httpRequest.status;
			}catch(e)
			{
				debugFatal("DAO ERROR Exception "+e);
			}
	        if ( daostatus == 200) 
	        {
				buffer=httpRequest.responseText;
				var aParams = buffer.split(',');
				
				tid = "TRUCK-1";
				lat = aParams[1];
				lon = aParams[2];

				stp = 0;//truckInfo[3];
				elp = 0;//truckInfo[4];
				//
				debugInfo("updateposition Adding marker at "+lat+" "+lon+" ID="+tid);		
				//
				truckObject = aTruckMarkers[ tid ];
				if ( truckObject == null )
				{
					//alert("Adding truck "+tid );
					truckObject = new TruckMarker( tid, lat, lon, stp, elp );					
				}	
				//
				truckObject.setNewLocation( lat, lon );			
				truckObject.setEllapsed( elp );
				//
				aTruckMarkers[ tid ] = truckObject;				
			}
		}
	}
	httpRequest.open('GET', url, true);	// true async false sync
	httpRequest.setRequestHeader("Content-Type", "text/xml");	
	httpRequest.send('');
}

//
//
//
var selectedGPS = null;
var aCalSpecialDates = new Array;

function OnGPSArchiveDateLoaded( jsonArray )
{
	//
	aCalSpecialDates = new Array;
	//
	var oObjects = eval(jsonArray);
	//
	if ( HasErrorProperty( oObjects) )
		return null;
	//
	count = 0;
	//
	html="";
	//
	for ( var oId in oObjects)
	{
		var oObject = oObjects[oId];
		day =  oObject.m_date.substr(0,10);
		//html+= oObject.m_gpsid+" On " + day +"<BR>";
		aCalSpecialDates[ day ] = oObject.m_gpsid;
	}
	//
	oTruckInfo = GetTruckInfoById( selectedGPS );
	//
	html+='<span class="truckinfo">GPS Information ('+selectedGPS+')';
	html+='<BR>Name: '+oTruckInfo.m_name;
	html+='<BR>Description: '+oTruckInfo.m_name;
	//
	addCalendar("Calendar"+oTruckInfo.m_tid, "Select Date", "firstinput", "sampleform");
	//
	html+='</span><BR><form name="sampleform">';
	html+="<input type='hidden' name='firstinput' size=20> <small><a class='truckinfo' href='javascript:showCal(\"Calendar"+oTruckInfo.m_tid+"\")'>Select Archive Date</a></small>";
	html+='</form><div class="maploadinginfo" id="maploadingdiv"></div>';
	document.getElementById("mapcontroldiv").innerHTML = html;
}
////
//// Converts any date that starts with
//// 2007-06-22 15:21:00.0
//// into a UTC string
////
function DateStringToDate( fulldatestring )
{
	datestring = fulldatestring.substring(0,10);
	hourstring = fulldatestring.substring(11);

	dateparts=datestring.split('-');
	timeparts=hourstring.split(':');

	//alert(dateparts[0]+"$"+dateparts[1]+"$"+dateparts[2]+" "+timeparts[0]+"$"+timeparts[1]+"$"+timeparts[2]+"$");

	return new Date( dateparts[0],dateparts[1]-1,dateparts[2],
				timeparts[0],timeparts[1],timeparts[2]
				 );
}
//
//
function onRouteLoaded( jsonArray ) 
{  
	document.getElementById("maploadingdiv").innerHTML="Rendering";	
	//
	// Get current truck
	//
	truckObject = GetTruckInfoById( selectedGPS );

	//
	var oObjects = eval(jsonArray);
	//
	if ( HasErrorProperty( oObjects) )
		return null;
	//
	var locationVertices = new Array;
	count = -1;
	lastDateRecorded  = new Date( 2000,1,1);
	var verticesArray = 0;
	//
	var oLocation = null;
	//
	//
	var decimateCounter = 0;
	//
	for ( var oId in oObjects)
	{
		decimateCounter++;
		var oObject = oObjects[oId];				
		//				  	
		recorded = oObject.m_recorded;
		tid2 	 = oObject.m_tid;
		lat 	 = oObject.m_lat;
		lon 	 = oObject.m_lon;
		//
		dateRecorded = DateStringToDate( recorded );
		//				
		//alert ( dateRecorded - lastDateRecorded );
		//
		if ( dateRecorded - lastDateRecorded > 1000*60*5 ) // 10 minutes
		{
			count++;
			locationVertices[ count ] = new Array
			verticesArray 	 = 0;					
			lastDateRecorded = dateRecorded;
		}
		//
		//
		if ( (decimateCounter++ %10)==1)
		{
			oLocation = createGLatLon( lat, lon )
			locationVertices[ count ][verticesArray] = oLocation;
			verticesArray++;
		}
		//
	}
	document.getElementById("maploadingdiv").innerHTML="";
	//
	if ( oLocation != null )
	{
		map.setCenter( oLocation , 10); 
	}
	//
	if ( truckObject == null )
		return;
	//
	// Check and remove previous route
	if ( truckObject.m_route != null )
	{
		for ( i = 0; i< truckObject.m_route.length; i++ )
			map.removeOverlay( truckObject.m_route[i] );
	}
	//
	// Create route
	truckObject.m_route = new Array;
	//
	//alert( locationVertices.length+" segments for "+ truckObject.tid );
	//
	for ( i = 0 ; i< locationVertices.length; i++ )
	{
		if ( (i % 2 ) == 1 )
			color = "#FF0000";
		else
			color = "#FF0066";
		truckObject.m_route[i] = createPolyline( locationVertices[i], color, 10);
		map.addOverlay( truckObject.m_route[i] );			
	}

}
//
//
// Build today's date YYYY-MM-DD
//
function BuildTodayDate()
{
	var currentTime = new Date()
	var month = currentTime.getMonth() + 1
	var day = currentTime.getDate()
	var year = currentTime.getFullYear()

	if ( day < 10 ) day ="0"+day;
	if ( month < 10 ) month="0"+month;

	return year+"-"+month+"-"+day;
}
//
function loadroute( tid, selectedDate )
{

	debugInfo( "loadroute "+selectedDate );
	//
	// Get current truck
	//
	truckObject = GetTruckInfoById( selectedGPS );
	//
	// Convert truck-id into id
	//tid = 1;//truckObject.m_tid;
	//
	//
	var url = DAOAPI_GETGPSLOCATIONSBYIDDATE+tid+"&from='"+selectedDate+"'&to='"+selectedDate+"'";
	//			
	//alert( "loadroute "+selectedDate+" " +url );
	DAO( url, "onRouteLoaded", null );
	//
	document.getElementById("maploadingdiv").innerHTML="Loading route for "+selectedDate+". Please wait...";
}
