var GPX = new function(){

	this.parseGpxFile = function(file, callbackFunc){
		var rte = null;
		var wpt = null;
		
		//console.log("Getting GPX file: " + file);
		var request = GXmlHttp.create();
		request.open("GET", file, true);

		request.onreadystatechange = function() {
		  if (request.readyState == 4) {
				var gpxDoc = request.responseXML;
				if( !gpxDoc ) {
					//alert("Could not load GPX document " + file);
				} else if( !gpxDoc.documentElement ) {
					//alert("Document " + file + "\nwas not recognized by the XML loader");
				} else if( gpxDoc.documentElement.childNodes.length < 1 ) {
					//alert("The XML loader could not parse document " + file);
				} else {
					Util.log("Parsing GPX file: " + file);
				
						
					//	Parse tracks in <rte></rte>
					//
					
					wpt = gpxDoc.documentElement.getElementsByTagName("wpt");
					rte = gpxDoc.documentElement.getElementsByTagName("trk");
					
					return callbackFunc({'rte':rte, 'wpt':wpt});
		
				} // gpxDoc
			} // readyState
		} // function
		request.send(null);
		
	}
	
	this.parseTrack = function(rte, minimal, moveDistance){
		var points = [];
		
		var move = 0.0;
		if(moveDistance!=undefined)
			move = moveDistance;
		
		if (rte) {
			// Process each route
			//
			for (var i = 0; i < rte.length; i++) {

				// Process each point of each route, string 
				// them into a single polyline
				//
				var rtept = rte[i].getElementsByTagName("trkpt");
				var lat, lng, lastLat, lastLng, o=0;
				for (var k = 0; k < rtept.length; k++) {
					
					lat = parseFloat(rtept[k].getAttribute("lat"));
					lng = parseFloat(rtept[k].getAttribute("lon"));
					
					if(!minimal || lastLat==null || lastLng==null || MapUtil.distance(new GLatLng(lng, lat), new GLatLng(lastLng, lastLat))>100 || k==rtept.length-1){
						points.push(new GPoint(lng + move, lat + move));
						
						lastLat = lat;
						lastLng = lng;
						
						o++;
					}
				}
				
				Util.log("Found " + o + " points");
				
			}
		}
		
		return points;
	}

}
