/*
	Daestra NZ
	$LastChangedDate: 2010-06-29 09:42:58 +1200 (Tue, 29 Jun 2010) $
	$LastChangedRevision: 16145 $
	$LastChangedBy: augusto $
	$HeadURL: svn://svn.tracplus/TracPlus/TracPlus2/trunk/Legacy/Server/trunk/Web/common/controlgooglemaps2.js $
*/

var DebugMode=true;
var gGoogleMap=null;
var gAircraftUrl=null;
var gDomLastWatchlist;//Last selected craft
var gLastPosition=null; //track last position
var gLastCraftSelectedRefID=null;

//settings
var kPathColour="#FF0000";
var kMaxReports=9999;//Show up to 50 recent reports
var kTimeout=30;//seconds
var kAllcraft="allcraft";

var gInitialTrailLength=kMaxReports; //trail length

var version="$LastChangedRevision: 16145 $";

function SafeGUnload()
{
	try
	{
		GUnload();
	}
	catch(e) {} //supress exception in IE with gUnload line 679
}

function InitialDrawAllCraft()
{
	ShowVersion(version);
	ShowWait(true);
	GDownloadUrl(WatchListUrl(kAllcraft),AllMarkers );
	InitializeTimer();
	AutoSelectOne();
	ShowWait(false);
}

function AllMarkers(data, responseCode)
{
	if (responseCode==200)
	{
		var craftxml = GXml.parse(data);
		var craft = craftxml.documentElement.getElementsByTagName("craft");
		for (var i=0; i < craft.length; i++)
		{
		  var info=craft[i].getElementsByTagName("info")[0];
		  var position=craft[i].getElementsByTagName("pos")[0];
			createMarker(info, position);
		}
	}
}

function ShowWait(isOn)
{
	DomWaiter=document.getElementById('detaillistbox');
	if (DomWaiter!=null)
	{
		if (isOn)
		{
			DomWaiter.className="delay";
		}
		else
		{
			DomWaiter.className="";
		}
	}
}

function AutoSelectOne()
{
	DomWatchlist=document.getElementById('watchlistbox');
	if (DomWatchlist !=null)
	{
		var WatchListLength=DomWatchlist.childNodes.length;
		if (WatchListLength >=1)
		{
			refID=DomWatchlist.childNodes[0].getAttribute('id').replace('watchlist','');
			HandleWatchList(null,refID)
		}
	}
 }

function HandleWatchList(DomSelf, refId)
{
		ShowWait(true);
		ShowVersion(version);
		gLastCraftSelectedRefID=refId;
		if (gDomLastWatchlist!=null)
		{
			gDomLastWatchlist.className='watchlistitems';
		}
		if (DomSelf==null)
		{
			watchlistItemsId=WatchListIDFromRef(refId);

			DomWatchlist=document.getElementById('watchlistbox');
      if (	DomWatchlist != null)
			{
				var DivHeight=51;//default value
				var WatchListLength=DomWatchlist.childNodes.length;
				if (WatchListLength >1)
				{
					//refID=DomWatchlist.childNodes[0].getAttribute('id');
					DivHeight=DomWatchlist.childNodes[0].offsetHeight
				}
				for (var i=0;i< DomWatchlist.childNodes.length;i++)
				{
					var currentID;
					try
					{
					DomWatchlist.scrollTop=i*DivHeight;
					currentID=DomWatchlist.childNodes[i].getAttribute('id');
					}
					catch (e)
					{
						currentID="not found";
					}
					if (watchlistItemsId==currentID)
						break;
				}
			}
			DomSelf=document.getElementById(watchlistItemsId);
		}
		if (DomSelf!=null)
		{
			DomSelf.className='watchlistitemshold';
			gDomLastWatchlist=DomSelf;
		}
		gLastPosition=null; // always zoom to new craft
	  gAircraftUrl=WatchListUrl(refId);
		ShowVersion(gAircraftUrl);

		if (!MapIsValid())
		{
			debug("error can't find map");
		}
		else
		{
			GDownloadUrl(gAircraftUrl,LoadAircraft );
			InitializeTimer();//Start timer
		}
		ShowWait(false);
}

function ShowVersion(v)
{
	if (DebugMode) //show debug info
	{
		DomTop=document.getElementById('topmiddle');
		if (DomTop!=null)
		{
			{
				DomH1=document.createElement('p');
				{
					DomA = document.createElement('a');
					DomA.setAttribute('href',gAircraftUrl);
					DomA.style.textDecoration='none';
					DomA.style.color='#D0D0D0';
					//	DomH1.appendChild(document.createTextNode('<!-- Version '+version +' -->'));
					DomA.appendChild(document.createTextNode('.'));
					DomA2 = document.createElement('a');
					DomA2.setAttribute('href',WatchListUrl(kAllcraft));
					DomA2.style.textDecoration='none';
					DomA2.style.color='#D0D0D0';
					//DomA2.appendChild(document.createTextNode('All Craft'));
					DomA2.appendChild(document.createTextNode('.'));
				}
				DomH1.appendChild(DomA);
			//	DomH1.appendChild(document.createTextNode(' - '));
				DomH1.appendChild(DomA2);
				{
					DomDebug=document.createElement('div');
					DomDebug.setAttribute('id','debug1');
					DomH1.appendChild(DomDebug);
				}
			}
			ClearChildren(DomTop);
			DomTop.appendChild(DomH1);
		}
	}
}



//Make sure we have the map
function MapIsValid()
{
	return (gGoogleMap!=null);
}


function DrawPath(posHist)
{
	var bounds = gGoogleMap.getBounds();
	var width  = bounds.maxX - bounds.minX;
	var height = bounds.maxY - bounds.minY;
	for(i = 0; (i < (posHist.length-1)) && (i <= gInitialTrailLength); i++)
	{
		var segment = new Array();
		segment[0] = posHist[i];
		segment[1] = posHist[i+1];
		//gGoogleMap.addOverlay(new GPolyline(segment,kPathColour,5*(1-i/posHist.length),(1.0-i/posHist.length)));
		//taper=Math.max(5*(1-i/posHist.length),1);
		taper=2;
		gGoogleMap.addOverlay(new GPolyline(segment,kPathColour,taper,0.25));
	}
	//gGoogleMap.addOverlay(new GPolyline(posHist,'#0000FF',1,1));
		gGoogleMap.panTo(posHist[0]);
}




function LoadAircraft(data, responseCode)
{

	if (responseCode==200)
	{
		var xml = GXml.parse(data);
		WriteDetails(xml);
		var positions = xml.documentElement.getElementsByTagName("pos");
		var pos=new Array();
		for (var i = 0; i < positions.length; i++)
		{
				pos[i] = new GLatLng(parseFloat(positions[i].getAttribute("lat")),parseFloat(positions[i].getAttribute("lng")));
		}
		if ((pos !=null) && (pos[0] !=null))
		{
			var newPos=pos[0].toString();
			if ((gLastPosition==null) || (gLastPosition!=newPos))
			{
				ShowWait(true);
				gGoogleMap.clearOverlays();
				GDownloadUrl(WatchListUrl(kAllcraft),AllMarkers );
				gLastPosition=newPos;
				DrawPath(pos);
				ShowWait(false);

				//var info = xml.documentElement.getElementsByTagName("info")[0];
				//var position = xml.documentElement.getElementsByTagName("pos")[0];
				//createMarker(info,position);

			}
		}
	}
	else
	{
		NoDataDisplay();
	}

}

function SetupDetails()
{
	DomDetailListbox=document.getElementById('detaillistbox');
  ClearChildren(DomDetailListbox);
	//DomReports=document.createElement('h2');
	//DomReports.appendChild(document.createTextNode('Reports'));
	//DomDetailListbox.appendChild(DomReports);
	return DomDetailListbox;
}


function NoDataDisplay()
{
	//clear map
	gGoogleMap.clearOverlays();
	GDownloadUrl(WatchListUrl(kAllcraft),AllMarkers );
	DomDetailListbox=SetupDetails();
	if (DomDetailListbox!=null)
	{
		DomDiv=document.createElement('div');
		DomDiv.className = 'detaillistitems';
		DomDiv.appendChild(CreateTextDom('p','none','No reports available'));
		DomDetailListbox.appendChild(DomDiv);
	}
}

function CreateDom(element, newClassName, DomObj)
{
    DomP = document.createElement(element);
		if (newClassName != null)
			DomP.className = newClassName;
		if (DomObj!=null)
			DomP.appendChild(DomObj);
    return DomP;
}

function CreateTextDom(element, newClassName, text)
{
    return CreateDom(element,newClassName,document.createTextNode(text));
}

function ClearChildren(obj)
{
	if (obj != null)
	{
	while(obj.firstChild)
		obj.removeChild(obj.firstChild);
	}
}

function WriteDetails(xml)
{
	DomDetailListbox=SetupDetails();
	if (xml != null)
	{
		var positions = xml.documentElement.getElementsByTagName("pos");
		var length=Math.min(positions.length,kMaxReports);
		for (var i = 0; i < length; i++)
		{
			var lineinfo=getReportLineInfo(positions[i]);
			DomDiv=document.createElement('div');
			DomDiv.className = 'reportsitem';
			DomDiv.appendChild(CreateTextDom('span','right',SpecialCharsToDom(lineinfo[0])));
			DomDiv.appendChild(CreateTextDom('b',null,SpecialCharsToDom(lineinfo[1])));
			DomDiv.appendChild(CreateTextDom('span','right',SpecialCharsToDom(lineinfo[4])))
			DomDiv.appendChild(CreateDom('br',null,null));
			DomDiv.appendChild(CreateTextDom('span',null,SpecialCharsToDom(lineinfo[2])));
			DomDiv.appendChild(CreateTextDom('span','right',SpecialCharsToDom((i+1) +' of '+ length)));
			DomDiv.appendChild(CreateDom('br',null,null));

			DomDiv.appendChild(CreateTextDom('span',null,SpecialCharsToDom(lineinfo[3])));
			DomDetailListbox.appendChild(DomDiv);
		}
	}
}

function getReportLineInfo(p)
{
	  var Event=p.getAttribute('event');
		var isBreadcrumb=(Event=="Breadcrumb");
		var reportInfo=new Array();
		var t=LocaliseTime(p.getAttribute('jstime'));
		// common code
		reportInfo[1]=p.getAttribute('event');
		reportInfo[3]=p.getAttribute('implat')+' '+p.getAttribute('implng');
		reportInfo[4]=FormattedDate(t);
		if (isBreadcrumb)
		{
			reportInfo[0]="";
			reportInfo[2]=p.getAttribute('height') + "'";
		}
		else
		{
		reportInfo[0]=FormattedTime(t);
		reportInfo[2]=p.getAttribute('height') + "' at "
		+ p.getAttribute('speed') + ' knots'
		+ ' tracking ' + p.getAttribute('course') +'&deg; True'
		}
		return reportInfo;
}

function getIconPath(name, IsShadow)
{
	shadow = (IsShadow)?"shadow":"";
	s = kUrlRoot+"/common/icons/"+name+shadow+".png";
	return s;
}

function createMarker(info,position )
{
	//var info = xml.documentElement.getElementsByTagName("info")[0];
	//var position = xml.documentElement.getElementsByTagName("pos")[0];

	if ((info ==null) ||(position==null))
		return;
	iconname=info.getAttribute("type");

	var baseIcon = new GIcon();
	baseIcon.shadow = getIconPath(iconname,true);
	baseIcon.iconSize = new GSize(45, 40);
	baseIcon.shadowSize = new GSize(55, 40);
	baseIcon.iconAnchor = new GPoint(15, 24);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);

	var icon = new GIcon(baseIcon);
	icon.image =  getIconPath(iconname,false);

	var iconPlot = new GLatLng(parseFloat(position.getAttribute("lat")),parseFloat(position.getAttribute("lng")));
	var marker = new GMarker(iconPlot, icon);
	GEvent.addListener(marker, "click", function()
	{
		var posinfo=getReportLineInfo(position);
		var ref=info.getAttribute("title");
		marker.openInfoWindowHtml('<div class="balloon">'
		+'<p class="lineCount"><b>'+info.getAttribute("registration")+'</b> ('+ref+ ')' +'</p>'
		+'<p class="line0">'+posinfo[0]+' <b>'+posinfo[1]+'</b> '+posinfo[4]+'</p>'
		+'<p class="line1">'+posinfo[2]+'</p>'
		+'<p class="line2">'+posinfo[3] +'</p>'
		+'<p class="line4"><a href="#" onClick="HandleWatchList(null, '+ ref+');">Select</a></p>'
		+ "</div>");
	});
	gGoogleMap.addOverlay(marker);
}

function SpecialCharsToDom(x)
{
    return x
			.replace(/&deg;/g,'\u00B0')
			.replace(/&quot;/g,'"');
}

function debug(x)
{
	//alert(x); //should be only ref to alert
}

// ---- Timer code

// timer
var secs =0;
var timerID = null
var timerRunning = false


function InitializeTimer()
{
	// Set the length of the timer, in seconds
	secs = 0;
	StopTheClock();
	StartTheTimer();
}

function StopTheClock()
{
	if(timerRunning)
			clearTimeout(timerID)
	timerRunning = false
}

function StartTheTimer()
{
			var onesecond = 1000
			timerRunning = true;
			timerID = self.setTimeout("UpdateSelf()", onesecond);
}

function UpdateSelf()
{
	UpdateClock();
	UpdateFAQ();
	if (gAircraftUrl!=null)
	{
		RedrawAircraft()
	}
	StartTheTimer();
}

function RedrawAircraft()
{
		secs = (secs +1) % kTimeout;
		if (secs==0)
		{
			gLoad=true;
			GDownloadUrl(gAircraftUrl,LoadAircraft );
		}
}

function UpdateClock()
{
	DomTime=document.getElementById('utctime');
	if (DomTime!=null)
		{
			ClearChildren(DomTime);
			DomTime.appendChild(document.createTextNode(currentLocalTime()));
		}
}


function currentUTCTime()
{
	var today=new Date();
	var h=today.getUTCHours();
	var m=today.getUTCMinutes();
	var s=today.getUTCSeconds();

	var utc=padTimeDate(h)+":"+padTimeDate(m)+":"+padTimeDate(s)+" UTC ";
	return utc;
}

function currentLocalTime()
{
	var today=new Date();
	var h=today.getHours();
	var m=today.getMinutes();
	var s=today.getSeconds();

	var utc=padTimeDate(h)+":"+padTimeDate(m)+":"+padTimeDate(s)+" local ";
	return utc;
}

function padTimeDate(i)
{
	if (i<10)
		{i="0" + i}
		return i
}

function LocaliseTime(dd)
{
	var t=new Date(eval("Date.UTC("+dd+")"))
	return t;
}

function FormattedTime(x)
{
	var fdate=padTimeDate(x.getHours())+":";
	fdate+=padTimeDate(x.getMinutes())+":";
	fdate+=padTimeDate(x.getSeconds())+" ";
	return fdate;
}

function FormattedDate(x)
{
	var fdate=x.getFullYear()+"-";
	fdate+=padTimeDate(x.getMonth()+1)+"-";
	fdate+=padTimeDate(x.getDate());
	return fdate;
}

function FormattedDateTime(x)
{
	return FormattedDate(x) +' ' + FormattedTime(x);
}

var gFAQ=-1;
var gFAQFire=-1;

function UpdateFAQ()
{
		DomFAQ=document.getElementById('FAQ');
		if (DomFAQ!=null)
		{
			if ((gFAQFire++ % kFAQRefreshSeconds)==0)
			{

				var DivHeight=70;//default value
				DivHeight=DomFAQ.offsetHeight+2;
				//alert('Div height=' +DivHeight);
				gFAQ++;
				DomFAQ.scrollTop=(gFAQ % kFAQLength)*DivHeight;
				//DomFAQ.scrollTop=(1 % kFAQLength)*DivHeight;
			}
		}

}

function ChangeTrailLength(me)
{
	gInitialTrailLength= me.options[me.selectedIndex].value*1;
	//kMaxReports=gInitialTrailLength;
	if (gLastCraftSelectedRefID!=null)
		HandleWatchList(null, gLastCraftSelectedRefID);
}
