/*
 - GPX Loader template for Google Maps - Easily display GPS track and waypoint files
 -
 - Author: Bryce Nesbitt
 - URL: http://www.obviously.com/gis/gpx_loader.html
 - Licence: Freeware
 - See also: http://www.topografix.com/gpx_manual.asp
 -
 - There are five simple steps to get going:
 - 1) Give your .gpx file the same base name as this .html file.
 - 2) Visit http://www.google.com/apis/maps/ to get an API key from Google.
 - 3) Make sure you downloaded the pushpin image files (mm_20_red.png)./
 - 3) Test.
 - 4) Edit this template to set zoom level and/or colors.
 -
 - Note: some users have repotrkd their web server sends .gpx files as
 - "plain text".  If this happens to you, and you can't fix the server, try
 - changing the extension to ".xml".
 -
 */
// Modify this to set the icon types used
//
var red_pin = new GIcon();
red_pin.image  		 = "images/mm_20_red.png";
red_pin.shadow 	         = "images/mm_20_shadow.png";
red_pin.iconSize  	 = new GSize(12, 20);
red_pin.shadowSize 	 = new GSize(22, 20);
red_pin.iconAnchor 	 = new GPoint(6, 20);
red_pin.infoWindowAnchor = new GPoint(5, 1);

var green_pin = new GIcon();
green_pin.image  	 = "images/mm_20_green.png";
green_pin.shadow 	 = "images/mm_20_shadow.png";
green_pin.iconSize 	 = new GSize(12, 20);
green_pin.shadowSize = new GSize(22, 20);
green_pin.iconAnchor = new GPoint(6, 20);
green_pin.infoWindowAnchor = new GPoint(5, 1);
function chooseIcon(name, type) {
	if (type == "AIRPORT" ) {
		return(red_pin)
		}
	if (type == "Dot" ) {
		return(red_pin)
		}
	return(green_pin);
}

function chooseLineStyle(name, comment) {
	if (comment == "BB" ) {
		return(new Array("#00f0f0",5,.5))
		}
	return(new Array("#ff2000",6,.7))	// Color,Width,Opacity
}

// *****************************************************
// *****************************************************
// Internal function to create a marker with pop-up text
//
function createMarker(point, thtml, icon) {
  var markera = new GMarker(point, icon);
  GEvent.addListener(markera, "click", function() {
    markera.openInfoWindowHtml(thtml);
  });
  map.addOverlay(markera);
  return markera;
}

//	Load and parse GPX file
//	Builds .gpx filename based on html file
//



var request = GXmlHttp.create();

function rloadtrigger()
{
		if (request.readyState != 4) {
			// Not yet fully loaded
			return;
		}

		var gpxDoc = request.responseXML;

		if( !gpxDoc ) {
			alert("Could not load GPX document " + URL);
		} else if( !gpxDoc.documentElement ) {
			alert("Document " + URL + "\nwas not recognized by the XML loader");
		} else if( gpxDoc.documentElement.childNodes.length < 3 ) {
			alert("The XML loader could not parse document " + URL);
		} else {
			//
			//	Parse document <bounds>.  Open map.  Guess at zoom level.
			//
			minlat 		= 0;
			minlon 		= 0;
			maxlat 		= 0;
			maxlon 		= 0;
			bounds = gpxDoc.documentElement.getElementsByTagName("bounds");
			if( bounds && bounds.length )
				{
				minlat = parseFloat(bounds[0].getAttribute("minlat"));
				minlon = parseFloat(bounds[0].getAttribute("minlon"));
				maxlat = parseFloat(bounds[0].getAttribute("maxlat"));
				maxlon = parseFloat(bounds[0].getAttribute("maxlon"));
				}
			zoomlat		= minlat+(maxlat-minlat)/2;
			zoomlon		= minlon+(maxlon-minlon)/2;
			zoomlevel	= 12;

//			If we get fed a GPX without <bounds> tags, center on Batsto like the normal map does.
			if (zoomlat == 0) {
				zoomlat = 39.64124;
				zoomlon = -74.646715;
				}

		        var point = new GLatLng(zoomlat,zoomlon);
			map.panTo(point); 
			bounds = [];

			//	Parse waypoints in <wpt></wpt> tags
			//
			var wpt;
			wpt = gpxDoc.documentElement.getElementsByTagName("wpt")
			if( wpt ) {
				for (var i = 0; i < wpt.length; i++) {

					point = new GPoint(parseFloat(wpt[i].getAttribute("lon")),
									   parseFloat(wpt[i].getAttribute("lat")));

					// Extract <name></name> tag
					tname  = "";
					tlabel = "";
					element = wpt[i].getElementsByTagName("name");
					if( element.length ) {
						tname   = element[0].firstChild.nodeValue;
						tlabel += element[0].firstChild.nodeValue;
						}

					// Tack on  <cmt></cmt> tag
					element = wpt[i].getElementsByTagName("cmt");
					if( element.length ) {
						if(tlabel) { tlabel += ": "; }
						tlabel += element[0].firstChild.nodeValue;
						}

					// Tack on <desc></desc> tag
					element = wpt[i].getElementsByTagName("desc");
					if( element.length ) {
						if(tlabel) { tlabel += " - "; }
						tlabel += element[0].firstChild.nodeValue;
						}

					// Extract <url></url> tag, build html for popup
					element = wpt[i].getElementsByTagName("url");
					if( element.length ) {
						turl = element[0].firstChild.nodeValue;
						var thtml 	= "<a href=\"" + turl + "target=\"_blank\">" + tlabel + "</a>";
						} else {
						var thtml	= tlabel;
						}

					// Determine map symbol based on <type></type> tag
					myicon = green_pin;
//					myicon = G_DEFAULT_ICON;
					type = wpt[i].getElementsByTagName("type");
					if( type.length ) {
						myicon = chooseIcon( tname, type[0].firstChild.nodeValue );
					}

					createMarker(point, thtml, myicon);
					}
				}
			wpt = [];
			

			//	Parse tracks and routes
			//

			// tracks
			var trk;
			trk = gpxDoc.documentElement.getElementsByTagName("trk");
			if (trk) {
				// Process each route
				//
				for (var i = 0; i < trk.length; i++) {
					tcolor="#4012FE";
					twidth=6;
					topacity=.7;

					// Extract <name></name> tag
					tname = "";
					element = trk[i].getElementsByTagName("name");
					if( element.length ) {
						if( element[0].firstChild ) {
							tname = element[0].firstChild.nodeValue;
							}
						}

					// Determine line color based on <cmt></cmt> and <name></name> tags
					type = trk[i].getElementsByTagName("cmt");
					if( type.length ) {
						if( type[0].firstChild ) {
							array    = chooseLineStyle( tname, type[0].firstChild.nodeValue );
							tcolor   = array[0];
							twidth   = array[1];
							topacity = array[2];
							}
						}

					// Process each point of each route, string 
					// them into a single polyline
					//
					points = [];
					var trkpt = trk[i].getElementsByTagName("trkpt");
					for (var k = 0; k < trkpt.length; k++) {
						points.push(new GPoint(
							parseFloat(trkpt[k].getAttribute("lon")),
							parseFloat(trkpt[k].getAttribute("lat"))));
						}
					map.addOverlay(new GPolyline(points, tcolor, twidth, topacity));
					points = [];
					}
				trk = []
				}

			// routes

                        var rte;
                        rte = gpxDoc.documentElement.getElementsByTagName("rte");
                        if (rte) {
                                // Process each route
                                //
                                for (var i = 0; i < rte.length; i++) {
                                        tcolor="#FF0000"; // red
                                        twidth=6;
                                        topacity=.7;

                                        // Extract <name></name> tag
                                        tname = "";
                                        element = rte[i].getElementsByTagName("name");
                                        if( element.length ) {
                                                if( element[0].firstChild ) {
                                                        tname = element[0].firstChild.nodeValue;
                                                        }
                                                }

                                        // Determine line color based on <cmt></cmt> and <name></name> tags
                                        type = rte[i].getElementsByTagName("cmt");
                                        if( type.length ) {
                                                if( type[0].firstChild ) {
                                                        array    = chooseLineStyle( tname, type[0].firstChild.nodeValue );
                                                        tcolor   = array[0];
                                                        twidth   = array[1];
                                                        topacity = array[2];
                                                        }
                                                }

                                        // Process each point of each route, string
                                        // them into a single polyline
                                        //
                                        points = [];
                                        var rtept = rte[i].getElementsByTagName("rtept");
                                        for (var k = 0; k < rtept.length; k++) {
                                                points.push(new GPoint(
                                                        parseFloat(rtept[k].getAttribute("lon")),
                                                        parseFloat(rtept[k].getAttribute("lat"))));
                                                }
                                        map.addOverlay(new GPolyline(points, tcolor, twidth, topacity));
                                        points = [];
                                        }
                                rte = []
                                }

			} // gpxDoc
	

} // rendergpx


function rendergpx(gpxurl) {
	var URL = "/gpx/" + gpxurl;
	request.open("GET", URL, true);
	// Set the callback to be run when the XML document is loaded
	request.onreadystatechange = rloadtrigger;
	request.send(null);
}
