function loadRoutes(data, responseCode) {
    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(); 
	//geoxml.show();
	//map.addOverlay(geoxml);
	//map.removeOverlay(label);
	//map.removeOverlay(marker);
	//map.removeOverlay(aLine);
	//map.removeOverlay(pLine);
    
	map.innerHTML = ' ';
	//tracklog.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()) {
        
		showWait('Getting map...');
 		var url = 'getgpslocations2.php' + routeSelect.options[routeSelect.selectedIndex].value;
	    
		map.clearOverlays();
		//geoxml.show();		
		//map.showOverlay(geoxml);
		//map.removeOverlay(label);
		//map.removeOverlay(marker);
		//map.removeOverlay(aLine);
		//map.removeOverlay(pLine);
					
		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) { // means no map
        return false;
    }
    else {
        return true;
    }
}

function loadGPSLocations(data, responseCode) {
    if (data.length == 0) {
        showMessage('There is no Tracking Data to view');
        map.innerHTML = '';
    }
    else {
        if (GBrowserIsCompatible()) {

        	// create list of GPS data locations from our XML
			map.innerHTML = '';

 			//tracklog.innerHTML = '';
			var xml = GXml.parse(data);

            // markers display on Google map
            var markers = xml.getElementsByTagName("locations");
            var length = markers.length;
			
			// Google polyLine (track)
			if (pLine != null) 					
					map.removeOverlay(pLine);
					//map.removeOverlay(aLine);
					var arrGlatLng = [];

					// Create Google GLatLng's from the returned track data
					for (var 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', 12, 0.2);
					//#6600FF
					pLine = new GPolyline(arrGlatLng, '#0b11ff', 3, 0.5);
					}
					// 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;

		for (i = 0; i < length; i++) {

			var 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;}
			
			var info = markers[i].getAttribute("extraInfo");
			var pinfo = markers[ii].getAttribute("extraInfo");
		
			if ( info != pinfo) {extraInfoCheck = 1;} else {extraInfoCheck = 0;} 		
						
			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);
				
				//GEvent.trigger(marker,"click"); 
		}
		//if (currentInterval != 0) {
		//GEvent.trigger(marker,"click"); 
		//}
	
length = markers.length;
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] = 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();
		}
		//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"))), zoomLevel);
			
			
		}
		else {
			var 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);
									 } 
        // show route name
        showMessage(routeSelect.options[routeSelect.selectedIndex].innerHTML);
		
		}
	}
}

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);

	//Set Weather Link
	var lat_new = point.lat();
    var lat_new = lat_new.toFixed(0);
    var lng_new = point.lng();
    var lng_new = lng_new.toFixed(0);
    var spos = lat_new+lng_new;
    var surl = "http://old.weathersa.co.za/Aerosport/ShowSpotGraphNEWMODEL.jsp?img="+spos;
	//'<a href="'+surl+'" target="_blank">Aerosport Spot Graph</a>'
	
	//Icon Marker color setting
 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);
		}
	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);
		}	
	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);
		}
		
		
	// 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;
	//if (message = "MESSSAGE") { message = "No Message";} 
	//if (message = "null") { message = "No Message";} 
	//var callsign = phoneNumber;
	//var actype = "-";
	 var dest = "-";
	//var eet = "-"; 
	}
		//var lstr = '<div style="padding: 0px 0px 0px 0px;border:1px #006699 solid;"><div style="background-color: #FFFFFF; padding: 2px;"><b>'+phoneNumber+'<\/b>&nbsp;<br>'+direction+'&deg;T&nbsp;'+speed+'mph&nbsp;'+alt+'ft<\/div><\/div>';
		var lstr = '<div style="padding: 1px 1px 1px 1px; width:125px; border:1px #006699 solid; "><div style="background-color: #FFFFFF; padding: 2px;"><b>'+phoneNumber+'<\/b>&nbsp;<br/>'+direction+'&deg;T&nbsp;'+speed+'mph&nbsp;'+alt+'ft<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);
	//var marker = new GMarker(point,{icon:icon, draggable: true});
	//marker.enableDragging();
	//GEvent.addListener(marker,"drag",function(){measure();});
  
  	function measure(){
		var label;
		var label2;
		var dist=0;
		var line;
		var poly;
			line = [marker.getPoint(), marker.getPoint()];
			dist=marker.getPoint().distanceFrom(marker.getPoint());
			dist=dist.toFixed(0)+"m";
		if (parseInt(dist)>1000){dist=(parseInt(dist)*0.000621371192).toFixed(1)+"mi";}
			label.setContents(dist);
			//label2.setContents(dist);
			label.setPoint(marker.getPoint());
			label.setContents(dist);
			//label2.setPoint(marker.getPoint());
		if (poly)map.removeOverlay(poly);
			poly = new GPolyline(line,'#ff0000', 2, 1);
			map.addOverlay(poly);
		}
		
	// this describes how we got our location data
    var lm = "";
    if (locationMethod == "8") {
        lm = "Cell Tower";
    } else if (locationMethod == "262145") {
        lm = "Satellite";
    } 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";}
	
	marker.openInfoWindow(
	
	"<table border=0 style=\"font-size:100%;font-family:Bitstream Vera Sans, Tahoma, Arial, Helvetica, sans-serif;\">"
		//+"<tr><td align=right><img src=http://www.vfrplanner.org/app/styles/gmaps/map_logo.png alt= Heading></td><td>&nbsp;</td><td rowspan=2 align=right>"
		//+ "<img src=images/" + getCompassImage(direction) + ".jpg alt= Heading>"
        //+ str 
		// &#177; +-  &nbsp; 		
        + "<tr bgcolor='#e1e9f0'><td align=left colspan=4>&nbsp;FPL DETAILS</td></tr>"		
		+ "<tr><td align=left>Callsign</td><td><strong>" + callsign + "</strong></td><td align=left>Aircraft</td><td>" + actype + "</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 SMS</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><td align=left colspan=4><hr /></td></tr>"
		+ "<tr bgcolor='#e1e9f0'><td align=left colspan=4>&nbsp;FLIGHT DATA</td></tr>"		
		+ "<tr><td align=left>Speed</td><td>" + Math.round(speed*0.868976242) +  " kts&nbsp;&nbsp;&nbsp;(" + speed + " mph)</td><td align=left>GPS 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 AGL</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>GPS Time</td><td>" + gpsTime +  "</td><td align=left>Weather</td><td><a href="+surl+" target='_blank'>Spot Graph</a></td></tr>"
		+ "<tr><td align=left colspan=1>Position</td><td>" + displayGLatLng(point) + "</td></tr>"		
        //+ "<tr><td align=left>GPS Accuracy</td><td>" + Math.round(accuracy*0.3048) + " m</td></tr>"
		//+ "<tr><td align=left>Track</td><td>" + sessionID + "</td></tr>"
		//+ "<tr><td align=left>Map Zoom</td><td align=left><a href='javascript:ZoomIn()'>Position</a>&nbsp;&nbsp;<a href='javascript:ZoomOut()'>Track</a></td></tr>"
        //+ "<tr><td align=left>Method</td><td>" + lm + "</td><td>&nbsp;</td></tr>"		
        //+ "<tr><td align=left>Location Valid</td><td>" + isLocationValid + "</td><td>&nbsp;</td></tr>"
		+ "</table>"
        );
	});
        //marker.openInfoWindowHtml(
		//tracklog.innerHTML = '<strong>EET to Marker :&nbsp;&nbsp;</strong>'+ Hours + 'h'+ Minutes +'m';
    });

    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 to Delete Track', '');
 
		if (pwdialog == pass1) {
			showWait('Deleting track...'); 
			
			map.clearOverlays(); 
//geoxml.show();
			//map.showOverlay(geoxml);
			//map.removeOverlay(label);
			//map.removeOverlay(marker);
			//map.removeOverlay(aLine);
			//map.removeOverlay(pLine);
					
            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; }
};