//vfrTracker maps2 script
function loadRoutes(data, responseCode) {
	var i;
	if (data.length == 0)  
	{
    showMessage('There are no tracks available');
    map.innerHTML = ' ';
	}
	else 
	{
    // get list of routes
    var xml = GXml.parse(data);
    var routes = xml.getElementsByTagName("route");

    // create the first option of the dropdown box
    var option = document.createElement('option');
    option.setAttribute('value', '0');
    option.innerHTML = 'Select a Track';
    routeSelect.appendChild(option);

    // iterate through the routes and load them into the dropdwon box.
    for (i = 0; i < routes.length; i ++) {
      option = document.createElement('option');
      option.setAttribute('value', '?sessionID=' + routes[i].getAttribute("sessionID") + '&phoneNumber=' + routes[i].getAttribute("phoneNumber"));

      // code txt

      var myDate = new Date();
      var trackDate = routes[i].getAttribute("times").substring(0, 8);
      myDate = myDate.format('d/m/y');

      if ( trackDate ==  myDate)
      {
        option.innerHTML = "->&nbsp;" + routes[i].getAttribute("times") + "\t&nbsp;&nbsp;" + routes[i].getAttribute("phoneNumber");
      }
      else
      {
        option.innerHTML = "&nbsp;&nbsp;" + routes[i].getAttribute("times") + "\t&nbsp;&nbsp;" + routes[i].getAttribute("phoneNumber");
      }
      routeSelect.appendChild(option);
    }

    // need to reset this for firefox
    routeSelect.selectedIndex = 0;
    hideWait();
    showMessage('Select a Track');

    var vfrData = new Array([0, 0], [0, 0]);

    for (i = 0; i < 2; i++ )
    {
      if (i == 0)
      {
        var vfrChart = new JSChart('schartcontainer', 'line');
        vfrChart.setDataArray(vfrData);
        vfrChart.setTitle('GPS GROUND SPEED (MPH)');
      }
      else
      {
        vfrChart = new JSChart('achartcontainer', 'line');
        vfrChart.setDataArray(vfrData);
        vfrChart.setTitle('GPS ALTITUDE (FT)');
      }
      vfrChart.setTitleColor('#8E8E8E');
      vfrChart.setTitleFontSize(8);
      vfrChart.setAxisNameX('');
      vfrChart.setAxisNameY('');
      vfrChart.setAxisColor('#99CCFF');
      vfrChart.setAxisValuesFontSize(7);
      vfrChart.setAxisValuesColor('#949494');
      vfrChart.setAxisPaddingLeft(35);
      vfrChart.setAxisPaddingRight(10);
      vfrChart.setAxisPaddingTop(30);
      vfrChart.setAxisPaddingBottom(15);
      vfrChart.setAxisValuesDecimals(0);
      vfrChart.setShowXValues(false);
      vfrChart.setGridColor('#C5A2DE');
      vfrChart.setGridOpacity(0.3);
      vfrChart.setLineColor('#BBBBBB');
      vfrChart.setLineWidth(2);
      vfrChart.setBackgroundColor('#FFF');
      vfrChart.setSize(250, 150);
      vfrChart.draw();
    }
  }
}

//  ---------------------------------------

function updateRoute()
{

  map.clearOverlays();
  map.innerHTML = ' ';
  routeSelect.length = 0;
  GDownloadUrl('getroutes.php', loadRoutes);
}

//  ---------------------------------------

// this will get the map and route, the route is selected from the list
function getRouteForMap()
{
  if (hasMap())
  {
	map.clearOverlays();
    showWait('Getting Track...');
    var url = 'getgpslocations2.php' + routeSelect.options[routeSelect.selectedIndex].value;    
    GDownloadUrl(url, loadGPSLocations);
  }
  else
  {
    alert("Select a Track before trying to Refresh the Map");
  }
}

//  ---------------------------------------

// check to see if we have a map loaded, don't want to autorefresh or delete without it
function hasMap() {
  if (routeSelect.selectedIndex == 0) { return false; } // means no map
  else { return true; }
}

//  ---------------------------------------

function loadGPSLocations(data, responseCode)
{

	var i;
  
  if (data.length == 0)
  {
    showMessage('There is no Track Data');
    map.innerHTML = '';
  }
  else
  {
    //if (GBrowserIsCompatible())
    //{

      // create list of GPS data locations from a XML
      map.innerHTML = '';
	  map.clearOverlays();
	 

      // tracklog.innerHTML = '';
      var xml = GXml.parse(data);

      // markers display on Google map
      var markers = xml.getElementsByTagName("locations");
      var length = markers.length;
	  
      // Google polyLine (track) removeoverlay line / add line 
//		if (pLine !== null) {
//      map.removeOverlay(pLine);
//		map.removeOverlay(aLine);
					//map.removeOverlay(poly);
		//}
      
      var arrGlatLng = [];
	  //document.append("testing auto tracking");
     // Create Google GLatLng's from the returned track data
     for (i = 0; i < length; i++ )
     {
		arrGlatLng.push(new GLatLng(parseFloat(markers[i].getAttribute("latitude")), parseFloat(markers[i].getAttribute("longitude"))));
        // #808080
		//aLine = new GPolyline(arrGlatLng, '#0b11ff', 7, 0.2);
        // #6600FF
		pLine = new GPolyline(arrGlatLng, '#0b11ff', 4, 0.7);
     }
		//CHECK FOR LB TRACKING		
		var checkLB = markers[length - 1].getAttribute("phoneNumber");		
		//checkLB = (checkLB.substr(-4));
		
		var iLen = checkLB.length;
		checkLB = checkLB.substring(iLen, iLen - 4);
		
		if (checkLB == "(LB)") {
			map.clearOverlays();
		
		//LOAD LB TRACKING
		var point = new GLatLng(parseFloat(markers[length - 1].getAttribute("latitude")), parseFloat(markers[length - 1].getAttribute("longitude")));
		var givenRad = 15;
		var givenQuality = 50;
		drawCircle(point, givenRad, givenQuality);
		var averagespd = 0;
		var count = 0;
		var avgspd = 0;		
        if (Number(parseFloat(markers[length - 1].getAttribute("speed"))) > 2) {
		count = count + 1;
		averagespd =  averagespd + Number(parseFloat(markers[length - 1].getAttribute("speed")));
        avgspd =  Math.round(averagespd / count);
        }
		
		// Zoom to track		
		var zoomLevel = map.getZoom();
		if (zoomLevel < 12) {
		zoomLevel = 12;
		}
        // center map on last marker to see progress during refreshes
        
		map.setCenter(new GLatLng(parseFloat(markers[length - 1].getAttribute("latitude")), parseFloat(markers[length - 1].getAttribute("longitude"))), zoomLevel);		
		
        var info = markers[length - 1].getAttribute("extraInfo");
        var pinfo = markers[length - 1].getAttribute("extraInfo");

        if ( info != pinfo) { extraInfoCheck = 1; }
        else {extraInfoCheck = 0;}
		//var i = length - 1;
		i = length - 1;
        var marker = createMarker(i, length, point, avgspd,
        markers[i].getAttribute("speed"),
        markers[i].getAttribute("direction"),
        markers[i].getAttribute("alt"),
        markers[i].getAttribute("distance"),
        markers[i].getAttribute("locationMethod"),
        markers[i].getAttribute("gpsTime"),
        markers[i].getAttribute("phoneNumber"),
        markers[i].getAttribute("sessionID"),
        markers[i].getAttribute("accuracy"),
        markers[i].getAttribute("isLocationValid"),
        markers[i].getAttribute("extraInfo")
        );
        map.addOverlay(marker);
		
	  length = markers.length;
      var sarr = new Array();
	  var aarr = new Array();
	  //var sarr = new Array[];
      //var aarr = new Array[];
	  

      for (i = 0; i < length; i++ )
      {
        sarr[i] = new Array(2);
        aarr[i] = new Array(2);
		
      }

      for (i = 0; i < length; i++ )
      {
        sarr[i][0] = i;
        sarr[i][1] = 0; //Number(markers[i].getAttribute("speed"));
        aarr[i][0] = i;
        aarr[i][1] = 0; //Number(markers[i].getAttribute("alt"));

      }

      for (i = 0; i < 2; i++ )
      {
        if (i == 0)
        {
          var vfrChart = new JSChart('schartcontainer', 'line');
          var vfrData = sarr;
          vfrChart.setDataArray(vfrData);
          vfrChart.setTitle('GPS GROUND SPEED (MPH)');
        }
        else
        {
          vfrChart = new JSChart('achartcontainer', 'line');
          vfrData = aarr;		  	  
          vfrChart.setDataArray(vfrData);		  
          vfrChart.setTitle('GPS ALTITUDE (FT)');
        }
        vfrChart.setTitleColor('#4040ff');
        vfrChart.setTitleFontSize(8);
        vfrChart.setAxisNameX('');
        vfrChart.setAxisNameY('');
        vfrChart.setAxisColor('#99CCFF');
        vfrChart.setAxisValuesFontSize(7);
        vfrChart.setAxisValuesColor('#4040ff');
        vfrChart.setAxisPaddingLeft(35);
        vfrChart.setAxisPaddingRight(10);
        vfrChart.setAxisPaddingTop(30);
        vfrChart.setAxisPaddingBottom(15);
        vfrChart.setAxisValuesDecimals(0);
        vfrChart.setShowXValues(false);
        vfrChart.setGridColor('#C5A2DE');
        vfrChart.setGridOpacity(0.3);
        vfrChart.setLineColor('#4040ff');
        vfrChart.setLineWidth(1);
        vfrChart.setBackgroundColor('#FFF');
        vfrChart.setSize(250, 150);
        vfrChart.draw(); 
      }
      
      // show route name
      showMessage(routeSelect.options[routeSelect.selectedIndex].innerHTML);
	  
	}
	
	//LOAD GPS TRACKING	
	else {
		
      // Create a Google polyline
      
	  //map.addOverlay(aLine);
      map.addOverlay(pLine);
	  
      // interate through all  GPS data, create markers and add them to map
      var averagespd = 0;
      var count = 0;
      var avgspd = 0;
      var ii = 0;
	  var point;

      for (i = 0; i < length; i++ ) {

        point = new GLatLng(parseFloat(markers[i].getAttribute("latitude")), parseFloat(markers[i].getAttribute("longitude")));

        if (Number(parseFloat(markers[i].getAttribute("speed"))) > 2)
        {
          count = count + 1;
          averagespd =  averagespd + Number(parseFloat(markers[i].getAttribute("speed")));
          avgspd =  Math.round(averagespd / count);
        }

        if ( i == 0 )
        { ii = i; }
        else
        { ii = i - 1; }
		
      // Zoom to track
      if (currentInterval == 0) {
        var gBounds = pLine.getBounds();
        var zoomLevel = map.getBoundsZoomLevel(gBounds);
        //zoomLevel = zoomLevel - 0;
        // map.setCenter(gBounds.getCenter(), zoomLevel);  // SET MIDDEL OF TRACK
        // STE TRACK TO POSITION
        map.setCenter(new GLatLng(parseFloat(markers[length - 1].getAttribute("latitude")),
        parseFloat(markers[length - 1].getAttribute("longitude"))), 12);		
		}
      else {
        zoomLevel = map.getZoom();		
        // center map on last marker to see progress during refreshes
        map.setCenter(new GLatLng(parseFloat(markers[length - 1].getAttribute("latitude")),
        parseFloat(markers[length - 1].getAttribute("longitude"))), zoomLevel);		
		}
        
		info = markers[i].getAttribute("extraInfo");
        pinfo = markers[ii].getAttribute("extraInfo");

        if ( info != pinfo) { extraInfoCheck = 1; }
        else { extraInfoCheck = 0; }

        marker = createMarker(i, length, point, avgspd,
        markers[i].getAttribute("speed"),
        markers[i].getAttribute("direction"),
        markers[i].getAttribute("alt"),
        markers[i].getAttribute("distance"),
        markers[i].getAttribute("locationMethod"),
        markers[i].getAttribute("gpsTime"),
        markers[i].getAttribute("phoneNumber"),
        markers[i].getAttribute("sessionID"),
        markers[i].getAttribute("accuracy"),
        markers[i].getAttribute("isLocationValid"),
        markers[i].getAttribute("extraInfo")
        );
        map.addOverlay(marker);
      }


      length = markers.length;
      sarr = new Array();
      aarr = new Array();
	  

      for (i = 0; i < length; i++ ) {
        sarr[i] = new Array(2);
        aarr[i] = new Array(2);
		}

      for (i = 0; i < length; i++ ) {
        sarr[i][0] = i;
        sarr[i][1] = Number(markers[i].getAttribute("speed"));
        aarr[i][0] = i;
        aarr[i][1] = Number(markers[i].getAttribute("alt"));		
		}

      for (i = 0; i < 2; i++ ) {
        if (i == 0)
        {
          var vfrChart = new JSChart('schartcontainer', 'line');
          var vfrData = sarr;
          vfrChart.setDataArray(vfrData);
          vfrChart.setTitle('GPS GROUND SPEED (MPH)');
        }
        else
        {
          vfrChart = new JSChart('achartcontainer', 'line');
          vfrData = aarr;		  
          vfrChart.setDataArray(vfrData);		  
          vfrChart.setTitle('GPS ALTITUDE (FT)');
        }
        vfrChart.setTitleColor('#4040ff');
        vfrChart.setTitleFontSize(8);
        vfrChart.setAxisNameX('');
        vfrChart.setAxisNameY('');
        vfrChart.setAxisColor('#99CCFF');
        vfrChart.setAxisValuesFontSize(7);
        vfrChart.setAxisValuesColor('#4040ff');
        vfrChart.setAxisPaddingLeft(35);
        vfrChart.setAxisPaddingRight(10);
        vfrChart.setAxisPaddingTop(30);
        vfrChart.setAxisPaddingBottom(15);
        vfrChart.setAxisValuesDecimals(0);
        vfrChart.setShowXValues(false);
        vfrChart.setGridColor('#C5A2DE');
        vfrChart.setGridOpacity(0.3);
        vfrChart.setLineColor('#4040ff');
        vfrChart.setLineWidth(1);
        vfrChart.setBackgroundColor('#FFF');
        vfrChart.setSize(250, 150);
        vfrChart.draw();
      }

      // show route name
      showMessage(routeSelect.options[routeSelect.selectedIndex].innerHTML);
	
	}
	
}
}
//  ---------------------------------------


function drawCircle(point, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa) {
//calculating km/degree
	radius = 2;
	var center = point;
	nodes = 80;
	
	var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;
	//Loop 
	var points = [];
	var step = parseInt(360/nodes)||10;
	for(var i=0; i<=360; i+=step)
	{
	var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + (radius/lngConv * Math.sin(i * Math.PI/180)));
	points.push(pint);
	//bounds.extend(pint); //this is for fit function
	}
	points.push(points[0]); // Closes the circle
	fillColor = fillColor||liColor||"#0055ff";
	liWidth = liWidth||1;
	var poly = new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa);	
	map.addOverlay(poly);
}



function createMarker(i, length, point, avgspd, speed, direction, alt, distance, locationMethod, gpsTime,
phoneNumber, sessionID, accuracy, isLocationValid, extraInfo)
{

  var icon = new GIcon();

  // Set Icon wrt tracking times
  var currentTime = new Date();
  var date = currentTime.getDate();
  var month = currentTime.getMonth() + 1;
  var year = currentTime.getFullYear();
  year = (year + "").substring(2, 4);
  var hours = currentTime.getHours();
  hours = ((hours < 10) ? "0" : "") + hours;
  var minutes = currentTime.getMinutes();
  minutes = ((minutes < 10) ? "0" : "") + minutes;

  var nowtime = new String(date + "/" + month + "/" + year + "  " + hours + ":" + minutes);

  if ( i == length - 1)
  {

    if (speed < 16 && nowtime != gpsTime)
    {
      icon.image = "images/coolgreen_small.png";
      icon.shadow = "images/coolshadow_small.png";
      icon.iconSize = new GSize(12, 20);
      icon.shadowSize = new GSize(22, 20);
      icon.iconAnchor = new GPoint(6, 20);
      icon.infoWindowAnchor = new GPoint(5, 1);
    }
    else if (speed > 15 && nowtime != gpsTime)
    {
      icon.image = "images/coolred_small.png";
      icon.shadow = "images/coolshadow_small.png";
      icon.iconSize = new GSize(12, 20);
      icon.shadowSize = new GSize(22, 20);
      icon.iconAnchor = new GPoint(6, 20);
      icon.infoWindowAnchor = new GPoint(5, 1);
    }
    else if  (speed > 15 && nowtime == gpsTime)
    {
      icon.image = "images/coolblue_small.png";
      icon.shadow = "images/coolshadow_small.png";
      icon.iconSize = new GSize(12, 20);
      icon.shadowSize = new GSize(22, 20);
      icon.iconAnchor = new GPoint(6, 20);
      icon.infoWindowAnchor = new GPoint(5, 1);
    }

	if  (locationMethod == "8")
    {
      icon.image = "images/icon5.png";
      icon.shadow = "";
      icon.iconSize = new GSize(32, 32); 
      icon.shadowSize = new GSize(32, 32);
      icon.iconAnchor = new GPoint(16, 16);
      icon.infoWindowAnchor = new GPoint(15, 15);
    }

    // Create the Track label
    if (direction >= 0 && direction <= 180)
    {
      var gposx = 10;
      var gposy = 0;
    }
    else // (direction >= 181 && direction <= 360)
    {
      var gposx = -140;
      var gposy = 0;
    }

    var fpl = new Array();
    // Create TRACK LABEL
    if ((extraInfo.length) > 15)
    {
      fpl = extraInfo.split(";");
      var callsign = fpl[0];
      // callsign
      password = fpl[1];
      // password
      var actype = fpl[2];
      // actype
      var dest = fpl[3];
      // dest
      var eet = fpl[4];
      // eet
      var end = fpl[5];
      // endurance
      var pob = fpl[6];
      // pob
      var sms = fpl[7];
      // overdueSMS
      var message = fpl[8];
      // message
      var overdue = fpl[9];
      // overduetime
    }
    else
    {
      var message = extraInfo;
      var dest = "-";
    }
	if (locationMethod == "8")
	{
	var lstr = '<div style="padding: 1px 1px 1px 1px; width:110px; border:1px #006699 solid; "><div style="background-color: #ffffff; color:#000000; padding: 2px; font-size:9px;"><b>' + phoneNumber + '<\/b><br/>' + direction + '&deg;T&nbsp;' + speed + 'mph&nbsp;' + alt + 'ft&nbsp;<br/>' + dest + '<br/>' + gpsTime + '<\/div><\/div>';
	//var lstr = '<div style="padding: 1px 1px 1px 1px; width:110px; border:1px #006699 solid; "><div style="background-color: #ffffff; color:#000000; padding: 2px; font-size:9px;"><b>' + phoneNumber + '<\/b>&nbsp;<br/>iPhone Tracker<br/>' + dest + '<br/>' + gpsTime + '<\/div><\/div>';
	}
    else {var lstr = '<div style="padding: 1px 1px 1px 1px; width:110px; border:1px #006699 solid; "><div style="background-color: #ffffff; color:#000000; padding: 2px; font-size:9px;"><b>' + phoneNumber + '<\/b><br/>' + direction + '&deg;T&nbsp;' + speed + 'mph&nbsp;' + alt + 'ft&nbsp;<br/>' + dest + '<br/>' + gpsTime + '<\/div><\/div>';}
    var label = new ELabel(new GLatLng(point.lat(), point.lng()), lstr, null, new GSize(gposx, gposy), 90, 1 );
    map.addOverlay(label);
  }

  else
  {

    if (extraInfoCheck == 1)
    {
      icon.image = "images/message.png";
      icon.iconSize = new GSize(16, 12);
      icon.iconAnchor = new GPoint(2, 2);
      icon.infoWindowAnchor = new GPoint(3, 1);
    }
    else
    {
      icon.image = "images/point.png";
      icon.iconSize = new GSize(5, 5);
      icon.iconAnchor = new GPoint(2, 2);
      icon.infoWindowAnchor = new GPoint(3, 1);
    }
  }
  var marker = new GMarker(point, icon);
  // this describes how we got our location data
  //var lm = "";
  if (locationMethod == "8")
  {
    lm = "Location Based";
  }
  else if (locationMethod == "262145")
  {
    lm = "GPS";
  }
  else
  {
    lm = locationMethod;
  }
  var str = "</td></tr>";
  // when a user clicks on last marker, let them know it's final one
  if (i == length - 1)
  {
    str = "</td></tr><tr><td align=left><b>vfrTracker</b></td><td><b>&nbsp;</b></td></tr>";
  }

  // this creates the pop up bubble that displays info when a user clicks on a marker

  GEvent.addListener(marker, "click", function()
  {
    if (distance > 1 && avgspd > 0)
    {
      var ltime = (distance / avgspd) * 60;
      ltime = ltime.toFixed(0);

      var Hours = Math.floor(ltime / 60);
      var Minutes = ltime % 60;
    }
    else if (distance < 1)
    {
      var Hours = 0;
      var Minutes = 0;
    }
    var Time = Hours + ":" + Minutes;
    // Get Elevation and adjust with 71ft
    topoGetAltitude( point.lat(), point.lng(), function( altitude )
    {
      var elevation = Math.round( topoToFeets( altitude ) + 71);
      // } );

      if (alt < 0)
      {
        alt = 0;
        var height = 0;
      }
      else
      {
        var height = alt - elevation;
        if (height < 0)
        {
          height = 0;
        }
      }

      var fpl = new Array();
      // Create FLIGHT DATA IN INFO WINDOW
      if (extraInfo.length > 15)
      {
        fpl = extraInfo.split(";");
        var callsign = fpl[0];
        // callsign
        password = fpl[1];
        // password
        var actype = fpl[2];
        // actype
        var dest = fpl[3];
        // dest
        var eet = fpl[4];
        // eet
        var end = fpl[5];
        // endurance
        var pob = fpl[6];
        // pob
        var sms = fpl[7];
        // overdueSMS
        var message = fpl[8];
        // message
        var overdue = fpl[9];
        // overduetime
      }
      else
      {
        var message = extraInfo;
        var callsign = phoneNumber;
        var actype = "-";
        var dest = "-";
        var eet = "0000";
        var end = "0000";
        var pob = "1";
        var sms = "0";
        var overdue = "-";
      }

      eet = eet.substring(0, 2) + "h&nbsp;" + eet.substring(2) + "m";
      end = end.substring(0, 2) + "h&nbsp;" + end.substring(2) + "m";
      if ((overdue == "") || (overdue == "Inactive"))
      {
        overdue = "-";
      }
      if (sms != "0")
      {
        sms = "Active " + overdue;
      }
      else
      {
        sms = "Inactive";
      }

      if (locationMethod == "8") {
	  marker.openInfoWindow(

      "<table border=0 style=\"font - size : 100 % ; font - family : Bitstream Vera Sans, Tahoma, Arial, Helvetica, sans - serif; \">"
      + "<tr bgcolor='#e1e9f0'><td align=left colspan=4>&nbsp;vfrTracker for iPhone/iPad</td></tr>"
      + "<tr><td align=left>Callsign</td><td><strong>" + callsign + "</strong></td><td align=left>Aircraft</td><td><strong>" + actype + "</strong></td></tr>"
      + "<tr><td align=left>Destination&nbsp;&nbsp;</td><td>" + dest + "</td><td align=left>POB</td><td>" + pob + "</td></tr>"         
      + "<tr><td align=left>Position</td><td>0" + displayGLatLng(point) + "</td><td colspan=2>&nbsp;@&nbsp;" + gpsTime + "</td></tr>"
      + "</table>"
      );
	  }
	  else {
	  marker.openInfoWindow(

      "<table border=0 style=\"font - size : 100 % ; font - family : Bitstream Vera Sans, Tahoma, Arial, Helvetica, sans - serif; \">"
      + "<tr bgcolor='#e1e9f0'><td align=left colspan=4>&nbsp;FLIGHTPLAN</td></tr>"
      + "<tr><td align=left>Callsign</td><td><strong>" + callsign + "</strong></td><td align=left>Aircraft</td><td><strong>" + actype + "</strong></td></tr>"
      + "<tr><td align=left>Destination&nbsp;&nbsp;</td><td>" + dest + "</td><td align=left>POB</td><td>" + pob + "</td></tr>"
      + "<tr><td align=left>Overdue</td><td>" + sms + "</td><td align=left>EET</td><td>" + eet + "</td></tr>"
      + "<tr><td align=left>Message</td><td>" + message + "</td><td align=left>Endurance</td><td>" + end + "</td></tr>"
      + "<tr bgcolor='#e1e9f0'><td align=left colspan=4>&nbsp;POSITION</td></tr>"
      + "<tr><td align=left>Speed</td><td>" + Math.round(speed * 0.868976242) +  " kts&nbsp;&nbsp;&nbsp;(" + speed + " mph)</td><td align=left>Altitude&nbsp;&nbsp;</td><td>" + alt +  " ft</td></tr>"
      + "<tr><td align=left>Track</td><td>" + direction +  " &deg;T&nbsp;</td><td align=left>Elevation</td><td>" + elevation +  " ft</td></tr>"
      + "<tr><td align=left>Distance</td><td>" + Math.round(distance * 0.868976242) +  " nm&nbsp;&nbsp;(" + distance + " mi)</td><td align=left>Height</td><td>&#177;&nbsp;" + height +  " ft</td></tr>"
      + "<tr><td align=left>Avg Speed</td><td>" + Math.round(avgspd * 0.868976242) + " kts&nbsp;&nbsp;(" + avgspd + " mph)</td><td align=left>AET</td><td>" + Hours + "h&nbsp;" + Minutes + "m" + "</td></tr>"
      + "<tr><td align=left>Position</td><td>0" + displayGLatLng(point) + "</td><td colspan=2>&nbsp;@&nbsp;" + gpsTime + "</td></tr>"
      + "</table>"
      );}
    }
    );

  }
  );
  return marker;
}

//  ---------------------------------------


// compass in the popup window
function getCompassImage(azimuth)
{
  if ((azimuth >= 337 && azimuth <= 360) || (azimuth >= 0 && azimuth < 23))
  return "compassN";
  if (azimuth >= 23 && azimuth < 68)
  return "compassNE";
  if (azimuth >= 68 && azimuth < 113)
  return "compassE";
  if (azimuth >= 113 && azimuth < 158)
  return "compassSE";
  if (azimuth >= 158 && azimuth < 203)
  return "compassS";
  if (azimuth >= 203 && azimuth < 248)
  return "compassSW";
  if (azimuth >= 248 && azimuth < 293)
  return "compassW";
  if (azimuth >= 293 && azimuth < 337)
  return "compassNW";
  return "";
}

//  ---------------------------------------


function deleteRoute()
{
  if (hasMap())
  {
    var pass1 = password;
    var pwdialog = prompt('Enter your vfrTracker password', '');

    if (pwdialog == pass1)
    {
      showWait('Deleting track...');

      map.clearOverlays();

      var url = 'deleteroute.php' + routeSelect.options[routeSelect.selectedIndex].value;
      GDownloadUrl(url, deleteRouteResponse);
      return true;
    }
    else
    {
      alert("Password not valid, enter your vfrTracker Mobile Password");
      return true;
    }
  }
}

//  ---------------------------------------

function deleteRouteResponse(data, responseCode)
{
  map.innerHTML = '';
  routeSelect.length = 0;
  GDownloadUrl('getroutes.php', loadRoutes);
}

//  ---------------------------------------

function autoRefresh()
{
  /*
  1) going from off to any interval
  2) going from any interval to off
  3) going from one interval to another
  */

  if (hasMap())
  {
    newInterval = refreshSelect.options[refreshSelect.selectedIndex].value;

    if (currentInterval > 0)
    {
      // currently running at an interval

      if (newInterval > 0)
      {
        // moving to another interval (3)
        clearInterval(intervalID);
        intervalID = setInterval("getRouteForMap();", newInterval * 1000);
        currentInterval = newInterval;
      }
      else
      {
        // turning off (2)
        clearInterval(intervalID);
        newInterval = 0;
        currentInterval = 0;
      }
    }
    else
    {
      // off and going to an interval (1)
      intervalID = setInterval("getRouteForMap();", newInterval * 1000);
      currentInterval = newInterval;
    }

    // show what auto refresh action was taken and after 5 seconds, display the route name again
    showMessage(refreshSelect.options[refreshSelect.selectedIndex].innerHTML);
    setTimeout('showRouteName();', 5000);
  }
  else
  {
    alert("Select a Track from the List");
    refreshSelect.selectedIndex = 0;
  }
}

//  ---------------------------------------

function changeZoomLevel()
{
  if (hasMap())
  {
    zoomLevel = zoomLevelSelect.selectedIndex - 0;
    getRouteForMap();
    // show what zoom level action was taken and after 5 seconds, display the route name again
    showMessage(zoomLevelSelect.options[zoomLevelSelect.selectedIndex].innerHTML);
    setTimeout('showRouteName();', 5000);
  }
  else
  {
    alert("Please select a Route before selecting Zoom Level");
    zoomLevelSelect.selectedIndex = zoomLevel - 0;
  }
}

//  ---------------------------------------

function showMessage(message)
{
  messages.innerHTML = '&nbsp;  &nbsp;' + message;
}

//  ---------------------------------------

function showRouteName()
{
  showMessage(routeSelect.options[routeSelect.selectedIndex].innerHTML);
}

//  ---------------------------------------

function showWait(theMessage)
{
  map.innerHTML = '<img src="images/ajax-loader.gif"' +
  'style="position:absolute;top:25%;left:50%;">';
  showMessage(theMessage);
}

//  ---------------------------------------

function hideWait()
{
  map.innerHTML = ' ';
  messages.innerHTML = ' ';
}

//  ---------------------------------------

function ZoomIn()
{
  map.setZoom(13);
}

//  ---------------------------------------

function ZoomOut()
{
  map.setZoom(10);
}

//  ---------------------------------------

function redrawPath()
{

  topoGetAltitude( point.lat(), point.lng(), function( altitude )
  {
    // elevation = (altitude + " / " + Math.round( topoToFeets( altitude )));
    // elevation = altitude;
    return altitude;
  }
  );
}

//  ---------------------------------------

// Simulates PHP's date function
Date.prototype.format = function(format)
{
  var returnStr = '';
  var replace = Date.replaceChars;
  for (var i = 0; i < format.length; i++ )
  {
    var curChar = format.charAt(i);
    if (replace[curChar])
    {
      returnStr += replace[curChar].call(this);
    }
    else
    {
      returnStr += curChar;
    }
  }
  return returnStr;
}

//  ---------------------------------------

;
Date.replaceChars =
{
  shortMonths : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  longMonths : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  shortDays : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
  longDays : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],

  // Day
  d : function()
  {
    return (this.getDate() < 10 ? '0' : '') + this.getDate();

  }
  ,
  D : function()
  {
    return Date.replaceChars.shortDays[this.getDay()];

  }
  ,
  j : function()
  {
    return this.getDate();

  }
  ,
  l : function()
  {
    return Date.replaceChars.longDays[this.getDay()];

  }
  ,
  N : function()
  {
    return this.getDay() + 1;

  }
  ,
  S : function()
  {
    return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th')));

  }
  ,
  w : function()
  {
    return this.getDay();

  }
  ,
  z : function()
  {
    return "Not Yet Supported";

  }
  ,
  // Week
  W : function()
  {
    return "Not Yet Supported";

  }
  ,
  // Month
  F : function()
  {
    return Date.replaceChars.longMonths[this.getMonth()];

  }
  ,
  m : function()
  {
    return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1);

  }
  ,
  M : function()
  {
    return Date.replaceChars.shortMonths[this.getMonth()];

  }
  ,
  n : function()
  {
    return this.getMonth() + 1;

  }
  ,
  t : function()
  {
    return "Not Yet Supported";

  }
  ,
  // Year
  L : function()
  {
    return (((this.getFullYear() % 4 == 0) && (this.getFullYear() % 100 != 0)) || (this.getFullYear() % 400 == 0)) ? '1' : '0';

  }
  ,
  o : function()
  {
    return "Not Supported";

  }
  ,
  Y : function()
  {
    return this.getFullYear();

  }
  ,
  y : function()
  {
    return ('' + this.getFullYear()).substr(2);

  }
  ,
  // Time
  a : function()
  {
    return this.getHours() < 12 ? 'am' : 'pm';

  }
  ,
  A : function()
  {
    return this.getHours() < 12 ? 'AM' : 'PM';

  }
  ,
  B : function()
  {
    return "Not Yet Supported";

  }
  ,
  g : function()
  {
    return this.getHours() % 12 || 12;

  }
  ,
  G : function()
  {
    return this.getHours();

  }
  ,
  h : function()
  {
    return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12);

  }
  ,
  H : function()
  {
    return (this.getHours() < 10 ? '0' : '') + this.getHours();

  }
  ,
  i : function()
  {
    return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes();

  }
  ,
  s : function()
  {
    return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds();

  }
  ,
  // Timezone
  e : function()
  {
    return "Not Yet Supported";

  }
  ,
  I : function()
  {
    return "Not Supported";

  }
  ,
  O : function()
  {
    return ( - this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00';

  }
  ,
  P : function()
  {
    return ( - this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':' + (Math.abs(this.getTimezoneOffset() % 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() % 60));

  }
  ,
  T : function()
  {
    var m = this.getMonth();
    this.setMonth(0);
    var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1');
    this.setMonth(m);
    return result;
  }
  ,
  Z : function() 
  {
    return - this.getTimezoneOffset() * 60;

  }
  ,
  // Full Date / Time
  c : function()
  {
    return this.format("Y-m-d") + "T" + this.format("H:i:sP");
  }
  ,
  r : function()
  {
    return this.toString();

  }
  ,
  U : function()
  {
    return this.getTime() / 1000;

  }
}

//  ---------------------------------------

;

