var jg;

// define some variables
var map;
var mgr;
var mapPoints	= [];
var ttlDistance = 0;
var pointIcon;
var startIcon;
var endIcon;
var endMarker;
var trailLine = 0;
var trailPoints = [];
var distances = [];
var elevations = [];
var geocoder;
var mapPointLineArrays = [];
var trailLineOverlays = [];
var userName = 'anonymous';


//////////////////////////////////////////////////////////////////////////
function hideInstructions() {
    document.getElementById("instructions").style.visibility = "hidden";
	document.getElementById("map").style.visibility = "visible";
	document.getElementById("savePage").style.visibility = "hidden";
	document.getElementById("gpsPage").style.visibility = "hidden";
	document.getElementById("loading").style.visibility = "hidden";
}


function checkGpxBeforeSubmit() {

	document.getElementById("gpsfile").style.backgroundColor = '#ffffff';

	if (document.getElementById("gpsfile").value == "")
	{	
		document.getElementById("gpsfile").style.backgroundColor = '#ffcccc';
		return false;
	}
	if (document.getElementById("gpsfile").value.lastIndexOf(".gpx")==-1)
	{
		document.getElementById("gpsfile").style.backgroundColor = '#ffcccc';
		return false
	}
	document.getElementById("gpxwaiticon").style.visibility = 'visible';

	return true;
}

var xmlHttp;
var postalCode;
var cityName;
var adminName1;
var adminName2;
var countryCode;

function showSaveTrail() {

    if (trailPoints.length < 2) {
	    alert ("You need to map a trail to save");
	    hideInstructions();
	    return
	}

    document.getElementById("instructions").style.visibility = "hidden";
	document.getElementById("map").style.visibility = "hidden";
	document.getElementById("savePage").style.visibility = "visible";
	document.getElementById("gpsPage").style.visibility = "hidden";
	document.getElementById("loading").style.visibility = "hidden";

	clearSaveTrail();
	
	xmlHttp=GetHttpObject(true)
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request")
		return
	}	
	var startPoint = trailPoints[0]
	url = 'getLocation.php5';
	url += '?lat='+startPoint.lat();
	url += '&lng='+startPoint.lng();
	
    xmlHttp.onreadystatechange=gotLocation;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);	
}

function showUploadGPS() {
    	document.getElementById("instructions").style.visibility = "hidden";
	document.getElementById("map").style.visibility = "hidden";
	document.getElementById("savePage").style.visibility = "hidden";
	document.getElementById("gpsPage").style.visibility = "visible";
    document.getElementById("loading").style.visibility = "hidden";	
}

function gotLocation() 
{
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 	{
		var dom = getxmldom( xmlHttp.responseText );

		postalCode = dom.getElementsByTagName("postalcode")[0].firstChild.data;
		cityName = dom.getElementsByTagName("name")[0].firstChild.data;		
    	adminName1 = dom.getElementsByTagName("adminName1")[0].firstChild.data;
		adminName2 = dom.getElementsByTagName("adminName2")[0].firstChild.data;
		countryCode = dom.getElementsByTagName("countryCode")[0].firstChild.data;		
		//document.getElementById("description").value += xmlHttp.responseText;
	}
}

function getxmldom( intext )
{

    // code for IE
    if (window.ActiveXObject)
      {
      var doc=new ActiveXObject("Microsoft.XMLDOM");
      doc.async="false";
      doc.loadXML(intext);
      }
    // code for Mozilla, Firefox, Opera, etc.
    else
      {
      var parser=new DOMParser();
      var doc=parser.parseFromString(intext,"text/xml");
      }

    return doc.documentElement;
}


//////////////////////////////////////////////////////////////////////////
function clearSaveTrail() {
    disableSaveTrailParams( false );
    HideLogin();
   	document.getElementById("waiticon").style.visibility = "hidden";
   	document.getElementById("trailName").style.backgroundColor = null;
	document.getElementById("trailName").value = '';
	document.getElementById("description").value = '';
	document.getElementById("userDifficulty").value = 5;
	document.getElementById("userScenery").value = 5;
	document.getElementById("userRating").value = 5;
	document.getElementById("bestMonth").value = 17;
	document.getElementById("isHike").checked = false;
	document.getElementById("isBikeMtn").checked = false;
	document.getElementById("isBikeRoad").checked = false;
	document.getElementById("isRunJog").checked = false;
	document.getElementById("isCityTour").checked = false;
	if (userName) {
        document.getElementById("username").value = userName;
    } else {
        document.getElementById("username").value = 'anonymous';
    }
}

function disableSaveTrailParams( bool ) {
    //disable all but login params
	document.getElementById("trailName").disabled = bool;
	document.getElementById("description").disabled = bool;
	document.getElementById("userDifficulty").disabled = bool;
	document.getElementById("userRating").disabled = bool;
	document.getElementById("userScenery").disabled = bool;
	document.getElementById("bestMonth").disabled = bool;
	document.getElementById("isHike").disabled = bool;
	document.getElementById("isBikeMtn").disabled = bool;
	document.getElementById("isBikeRoad").disabled = bool;
	document.getElementById("isRunJog").disabled = bool;
	document.getElementById("isCityTour").disabled = bool;
	document.getElementById("savebutton").disabled = bool;
}

function HideLogin()
{
    disableSaveTrailParams(false)
    document.getElementById("username").disabled = true;
    document.getElementById("passwordLabel").style.visibility = "hidden";
    document.getElementById("loginLink").style.visibility = "hidden";
    document.getElementById("loginExtraB").innerHTML = "";


    if (userName == 'anonymous') {
        var loginnow = '<a href="Javascript:ShowLogin()">Login Now</a>';
        document.getElementById("loginExtraB").innerHTML =  loginnow
    }
}
function ShowLogin()
{
    disableSaveTrailParams(true)
    document.getElementById("username").disabled = false;
    document.getElementById("passwordLabel").style.visibility = "visible";
    document.getElementById("loginLink").style.visibility = "visible";
    document.getElementById("loginLink").innerHTML = "<a href='Javascript:Login()'>Login</a>";

    var loginpass = "<input type='password' id='password' size='25'>";
    document.getElementById("loginExtraB").innerHTML =  loginpass
}
var un
function Login()
{
    //verify that both fields have something in them and the top 
    un = document.getElementById("username").value;
    var pa = document.getElementById("password").value;
    if (un != "" && un != 'anonymous') {

        //set the login text to a wait sign
        document.getElementById("loginLink").innerHTML = "<img border='0px' src='http://www.trailchaser.com/siteimg/ajax-loader.gif' />";

        //verify the login information
        http_request = GetHttpObject(false);
        url = 'loginUser.php';
    	url += '?user='+un;
    	url += '&pass='+pa;
    
        http_request.onreadystatechange=gotLogin;
    	http_request.open("GET",url,true);
    	http_request.send(null);
    

    }
}
function gotLogin() {
  if (http_request.readyState == 4) {
     if (http_request.status == 200) {

        //document.getElementById('results').innerHTML += ("gotLogin:" +  http_request.responseText + "<br>");
        if (http_request.responseText == '1'){
                userName = un;
                createCookie('tc_user',userName, .1);
                // hide the login information
                HideLogin();

            } else {
                document.getElementById("loginLink").innerHTML = "Login Failed. <a href='Javascript:Login()'>Try Again</a>";
                //make it known that login didn't work.
            }

     } else {
        alert('There was a problem with the submission.');
     }
  }
}





var http_request = false;
function GetHttpObject(useXML)
{
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            if (useXML) {
                http_request.overrideMimeType('text/xml');
            } else {
                http_request.overrideMimeType('text/html');
            }
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
    if (!http_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
    return http_request;
}



function makePOSTRequest(url, parameters) {
    http_request = GetHttpObject(false);
    if (!http_request) {
        return false;
    }
    http_request.onreadystatechange = alertContents;
    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", parameters.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(parameters);
}

function alertContents() {
  if (http_request.readyState == 4) {
     if (http_request.status == 200) {
         
        var returnAry = http_request.responseText.split(";");
        var trailId = parseInt(returnAry[0]);
        if (trailId > 0)
        {
            // go to the trail detail page
            window.location = ("http://www.trailchaser.com/showtraildetail.html?id=" + trailId);
        }
        //alert(http_request.responseText);
        result = http_request.responseText;
        //document.getElementById('results').innerHTML = result;
     } else {
        alert('There was a problem with the submission.');
     }
  }
}








function saveValid() {
    	document.getElementById("trailName").style.backgroundColor = '#ffffff';
	var doSubmit = true;
    	if (document.getElementById("trailName").value == "") {
	    	document.getElementById("trailName").style.backgroundColor = '#FFE003';
		doSubmit = false;
	} 
	return doSubmit;
}
function saveTrail() {
    if (! saveValid() ) {
	    return
	}

	//show the wait icon
	document.getElementById("waiticon").style.visibility = "visible";
	
	//disable the interface
	disableSaveTrailParams(true)

	var url = "";
	url=url+"user="+userName;
	url=url+"&name="+document.getElementById("trailName").value;
	url=url+"&dist="+(ttlDistance/1609.344);
	url=url+"&desc="+document.getElementById("description").value;
	url=url+"&udif="+document.getElementById("userDifficulty").value;
	url=url+"&usce="+document.getElementById("userScenery").value;
	url=url+"&urat="+document.getElementById("userRating").value;
	url=url+"&mnth="+document.getElementById("bestMonth").value;

    var trailtype = (document.getElementById("isHike").checked + 0).toString();
	trailtype += (document.getElementById("isBikeMtn").checked + 0).toString();
	trailtype += (document.getElementById("isBikeRoad").checked + 0).toString();
	trailtype += (document.getElementById("isRunJog").checked + 0).toString();
	trailtype += (document.getElementById("isCityTour").checked + 0).toString();
	url=url+"&type="+trailtype;
	
	url=url+"&pcod="+postalCode;
	url=url+"&ccod="+countryCode;
	url=url+"&city="+cityName;
	url=url+"&adm1="+adminName1;
	url=url+"&adm2="+adminName2;
	
	url=url+"&pntCord="+(trailPoints.join(";"));
	url=url+"&pntDist="+distances;
	url=url+"&pntElev="+elevations;

    makePOSTRequest('saveTrail.php', url)
}




//////////////////////////////////////////////////////////////////////////

Array.prototype.max = function(){
	return Math.max.apply({},this)
}
Array.prototype.min = function(){
	return Math.min.apply({},this)
}





function drawBlankGraph()  {
    	jg.clear();

	var xPoints = [0,0,740,740];
	var yPoints = [100,80,80,100];

	jg.setColor("#3F473B");
	jg.fillPolygon( xPoints, yPoints );
	
    	jg.setColor("#8E928C"); 
    	jg.drawLine(0, 80, 740, 80);

    	jg.setColor("#6E6E6E"); 
    	jg.drawLine(0, 20, 740, 20);
	
	jg.setColor("#000000"); 
    	jg.drawString("0 ft", 5, 5);

	jg.setColor("#ffffff"); 
    	jg.drawString("0 ft", 5, 83);

	jg.paint();
}
function removeNulls( ary ) {
	var newary = [];
	for (var i = 0; i < elevations.length; i++ ) {
		if (elevations[i] != null) {
			newary.push(elevations[i]);
		}
	}
	return newary;
}
function drawGraph()  {
    	jg.clear();

	var X;
	var Y;
	var xPoints = [0];
	var yPoints = [100];
	
	var cleanElev = removeNulls(elevations);

	var elevMin = cleanElev.min();
	var elevMax = cleanElev.max();
	var elevDif = elevMax-elevMin;

	if (cleanElev.length > 1)
	{
	    	var xSpread = ( 740 / ttlDistance );
		for (var i = 0; i < cleanElev.length; i++ ) {
			X = parseInt(  ( distances[i] / ttlDistance ) * 740);
			Y = (parseInt ( ( (elevMax - cleanElev[i] ) / elevDif) * 60 ) + 20);
			yPoints.push( Y );
			xPoints.push( X );
		}
		
		xPoints.push( 740 );
		yPoints.push( 100 );
	} else {

		xPoints = [0,0,740,740];
		yPoints = [100,80,80,100];
	}

	jg.setColor("#3F473B"); 
	jg.fillPolygon( xPoints, yPoints );
	
    	jg.setColor("#8E928C"); 
    	jg.drawLine(0, 80, 740, 80);

    	jg.setColor("#6E6E6E"); 
    	jg.drawLine(0, 20, 740, 20);
	
	jg.setColor("#000000"); 
    	jg.drawString(parseInt(elevMax)+" ft", 5, 5);

	jg.setColor("#ffffff");
    	jg.drawString(parseInt(elevMin) + " ft", 5, 83);

	jg.paint();
}
    	


function clearPoints() {
    	jg.clear();
    
	mgr.clearMarkers()

	trailPoints = [];
	mapPoints = [];
	ttlDistance = 0.0;
	trailLine = 0;
        	
    	map.clearOverlays()
	mapPointLineArrays = [];
    	trailLineOverlays = [];
	elevations  = [];
	
	refreshStats();
	drawBlankGraph();
	
}

function loadIcon() {
	pointIcon = new GIcon();
	pointIcon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
	//pointIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	pointIcon.iconSize = new GSize(12, 20);
	//pointIcon.shadowSize = new GSize(22, 20);
	pointIcon.iconAnchor = new GPoint(6, 20);
	pointIcon.infoWindowAnchor = new GPoint(5, 1);

	startIcon= new GIcon();
	startIcon.image = "http://www.google.com/mapfiles/dd-start.png";
	startIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	startIcon.iconSize = new GSize(20, 34);
	startIcon.shadowSize = new GSize(37,34);
	startIcon.iconAnchor = new GPoint(9, 34);
	startIcon.infoWindowAnchor = new GPoint(9, 2);	

	endIcon= new GIcon();
	endIcon.image = "http://www.google.com/mapfiles/dd-end.png";
	endIcon.iconSize = new GSize(20, 34);
	endIcon.iconAnchor = new GPoint(9, 34);
	endIcon.infoWindowAnchor = new GPoint(9, 2);
}

function calculateDistance() {
    //clear the arrays
    trailPoints = [];

    //walk through and find the points that are necessary
    for (i = 0; i < mapPoints.length; i++){
	if (mapPoints[i] != null)
	{
	    trailPoints.push(mapPoints[i]);
	}
    }

    ttlDistance = 0.0;
    distances = [0];
    lastPoint = trailPoints[0];
    if (trailPoints.length > 1 ){
	for (var i = 1; i < trailPoints.length; i++ ) {
	    ttlDistance += trailPoints[i].distanceFrom(lastPoint);
	    lastPoint = trailPoints[i];
	    distances.push(ttlDistance);
	}
    }
    refreshStats();
    
}

function refreshStats()
{
	document.getElementById("numPnts").innerHTML = (trailPoints.length);
	document.getElementById("ttlDistance").innerHTML = (ttlDistance/1609.344).toFixed(2) + "(Miles)";

	var elevMin = elevations.min();
	var elevMax = elevations.max();
	var elevDif = elevMax-elevMin;
	document.getElementById("elevGain").innerHTML = parseInt(elevDif) + "ft";
	calculateCalories();	
}


function createMarker(point, number) {
	var marker;
	if (number == 0)
	{
		marker = new GMarker(point, {icon:startIcon,draggable:true});
	}
	else
	{
		marker = new GMarker(point, {icon:pointIcon,draggable:true});
	}

	//GEvent.addListener(marker, "click", function() {
		//document.getElementById("numPnts").innerHTML += "marker click";
	//});
	//GEvent.addListener(marker, "dragstart", function() {
		//map.closeInfoWindow();
	//});

    	GEvent.addListener(marker, "dragend", function() {
		//mapPoints[number] = marker.getPoint();
		updatePoint( number, marker );
    	});
    	if (number > 0)
	{
		GEvent.addListener(marker, "dblclick", function() {		
			mapPoints[number] = null;
			elevations[number] = null;
			mgr.removeMarker(marker);
			removePoint( number, marker );
			calculateDistance();
			drawGraph();

    		});
	}

	return marker;
}

//////////////////////////////////////////////

function removePoint(mapPointIndex, marker) {
	//check the trail line indexs for the point and update where necessary
	
	
	var numUpdated = 0;
	var pointIndexBefore;
	for (var i=0;i<mapPointLineArrays.length;i++) {
		for (itemInd=0;itemInd < mapPointLineArrays[i].length;itemInd++) {			
			if ( mapPointLineArrays[i][itemInd] == mapPointIndex ) {
			    					
				// if it's not the first or the last in the array
				// just remove it and exit
				if ((itemInd > 0) && (itemInd < mapPointLineArrays[i].length-1)) {
					//remove it
					mapPointLineArrays[i].splice(itemInd, 1);
					updateTrailLine( i );
					return		    
				}
				
				// if it's the last item in the array
    	    	    	    	if (itemInd == mapPointLineArrays[i].length-1) {
	    	    	    	    	// if length > 2 then remove the point
					if (mapPointLineArrays[i].length > 2) {
					    	var prevInd = mapPointLineArrays[i][itemInd-1];
					    	mapPointLineArrays[i].splice(itemInd, 1); 
						updateTrailLine( i );
						
						
    	    	    	    	    	    	//update the next line if there is one
						if (mapPointLineArrays.length > i) {
							mapPointLineArrays[i+1].splice(0,1,prevInd);
							updateTrailLine( (i+1) );
						}
						return					
					}
					
					// if there are only 2 elements in the array..
					if (itemInd == 0) {
					    	// get the next item
					    	var nextInd = mapPointLineArrays[i][1];
						//remove the array
					    	mapPointLineArrays.splice(i,1);
						//remove the line
						map.removeOverlay(trailLineOverlays[i]);						
	    	    	    	    	    	trailLineOverlays.splice(i,1);
						
						if (i > 0) {
						    	//set the prev array last val and update that line
							mapPointLineArrays[i+1].splice(mapPointLineArrays[i-1].length-1,1,nextInd);
							updateTrailLine( i-1 );
						}
						
					} else  {
					    	// it's the 2nd item in the array
						var prevInd = mapPointLineArrays[i][0];
						//remove the array
					    	mapPointLineArrays.splice(i,1);
						//remove the line
						map.removeOverlay(trailLineOverlays[i]);						
	    	    	    	    	    	trailLineOverlays.splice(i,1);
						
						if ( (mapPointLineArrays.length) >= i ) {
						    	mapPointLineArrays[i].splice(0,1, prevInd);
							updateTrailLine( i );
						}
					}
				}
			}
		}
	}
}


function updatePoint(mapPointIndex, marker) {
	mapPoints[mapPointIndex] = marker.getPoint();
	//check the trail line indexs for the point and update where necessary
	var numUpdated = 0;
	for (var i=0;i<mapPointLineArrays.length;i++) {
		for (itemInd=0;itemInd < mapPointLineArrays[i].length;itemInd++) {
			if ( mapPointLineArrays[i][itemInd] == mapPointIndex ) {
				updateTrailLine( i );
				numUpdated += 1;
			}
			if (numUpdated == 2) {
				return
			}
		}
	}
	var point = marker.getPoint();
	topoGetAltitude( point.lat(), point.lng(), function( altitude ) {
	    	elevations[mapPointIndex] = ( topoToFeets( altitude ) );
		drawGraph();
        } );

}


function updateTrailLine(lineIndex) {
    	// get the points that make up the new line
    	var newTrailPoints = [];
    	for (var i=0;i<mapPointLineArrays[lineIndex].length;++i) {
    	    	newTrailPoints.push( mapPoints[mapPointLineArrays[lineIndex][i]] );
    	}
    	var trailLine = new GPolyline(newTrailPoints,'#ff6600', 3, 0.9)

    	//remove the existing ?
    	if (trailLineOverlays.length > lineIndex) {
    	    	map.removeOverlay(trailLineOverlays[lineIndex]);
	    	trailLineOverlays[lineIndex] = trailLine;
    	} else {
    	    	trailLineOverlays.push( trailLine );
    	}
	
	
	
    	//add the new line
    	map.addOverlay( trailLine );
	calculateDistance();
	

}


function addPoint( mapPointIndex )
{
	// if no point exist at all
	if (mapPointLineArrays.length == 0) {
		mapPointLineArrays.push( [mapPointIndex] );
		return
	}
    	var lastLine = mapPointLineArrays[ mapPointLineArrays.length-1 ];
    	if (lastLine.length == 5) {
    		//get the last point index
		var lastPoint = lastLine[lastLine.length-1];
    		//start a new line
		mapPointLineArrays.push( [ lastPoint, mapPointIndex ] );
    	} else {
    		mapPointLineArrays[ mapPointLineArrays.length-1 ].push( mapPointIndex );

    	}
    	updateTrailLine( mapPointLineArrays.length-1 )

}





function checkAddressEnter(e){ //e is event object passed from function invocation
	var characterCode;

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}

	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		gotoAddress();
	}
}
function gotoAddress() {
	var geocoder = new GClientGeocoder();
	var zoom = document.getElementById("zoomLocation");
	var address = zoom.value;
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        alert(address + " not found");
      } else {
        map.setCenter(point, 11);
        hideInstructions();
        //var marker = new GMarker(point);
        //map.addOverlay(marker);
        map.openInfoWindowHtml(point, address);
      }
    }
  );
}

function calculateCalories() {
    	var w = document.getElementById("weight").value;
	document.getElementById('cal_1').innerHTML = parseInt(3.3 * (w/2.204625) * ((ttlDistance/1609.344)/3.0));
	document.getElementById('cal_2').innerHTML = parseInt(4.5 * (w/2.204625) * ((ttlDistance/1609.344)/4.0));
	document.getElementById('cal_3').innerHTML = parseInt(10.2 * (w/2.204625) * ((ttlDistance/1609.344)/6.0));
	document.getElementById('cal_4').innerHTML = parseInt(13.1 * (w/2.204625) * ((ttlDistance/1609.344)/8.0));	
	document.getElementById('cal_5').innerHTML = parseInt(8.4 * (w/2.204625) * ((ttlDistance/1609.344)/13.0));
	document.getElementById('cal_6').innerHTML = parseInt(12.6 * (w/2.204625) * ((ttlDistance/1609.344)/18.0));

}
var xmlDoc;
function loadXML(filename)
{

	//load xml file
	// code for IE
	if (window.ActiveXObject)
	{
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.load("http://www.trailchaser.com/upload/" + filename);
		loadGPS();
	}
	// code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation && document.implementation.createDocument)
	{
		xmlDoc=document.implementation.createDocument("","",null);
		document.getElementById('cal_1').innerHTML = xmlDoc;

		var s = xmlDoc.load("http://www.trailchaser.com/upload/" + filename);
		document.getElementById('cal_2').innerHTML = s;
		xmlDoc.onload=loadGPS;
	}
	else
	{
		alert('Your browser cannot handle this script');
	}
}

function loadGPS()
{
	var bounds = new GLatLngBounds();
	var gpx = xmlDoc.getElementsByTagName('gpx');
	var trk = gpx[0].getElementsByTagName('trk');
	var trkseg = trk[0].getElementsByTagName('trkseg');
	var trkpts = trkseg[0].getElementsByTagName('trkpt');
	for (i=0;i<trkpts.length;i++)
	{
		var lat = trkpts[i].attributes.getNamedItem('lat').nodeValue;
		var lng = trkpts[i].attributes.getNamedItem('lon').nodeValue;

		var point = new GLatLng(parseFloat(lat), parseFloat(lng));

		mapPoints.push(point);
		bounds.extend( point );
		
		//get the elevation
		//var elev = trkpts[i].getElementsByTagName('ele')[0].nodeValue;
		var elevtag = trkpts[i].getElementsByTagName('ele');
		var elev = parseFloat(elevtag[0].childNodes[0].nodeValue);
		elevations.push( elev );
	}

	var trailLine = new GPolyline(mapPoints,'#ff6600', 3, 0.9)
    	map.addOverlay( trailLine );

	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
    document.getElementById("gpxwaiticon").style.visibility = 'hidden';
	hideInstructions();
	calculateDistance();
	drawGraph();

}
function loadXMLDoc(url)
{
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
    }
}
function processReqChange()
{
    // only if req shows "complete"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            
            
            // code for IE
            if (window.ActiveXObject)
              {
                xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async="false";
                xmlDoc.loadXML(req.responseText);
              }
            // code for Mozilla, Firefox, Opera, etc.
            else
              {
                var parser=new DOMParser();
                xmlDoc=parser.parseFromString(req.responseText,"application/xml");
              }
      

		      //var parser=new DOMParser();
      		//xmlDoc=parser.parseFromString(req.responseText ,"application/xml");
		loadGPS();
	}
    }
}

function gup( name ){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
}
function loadMap() {
	loadIcon();
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		//map.enableDoubleClickZoom();
		//map.enableScrollWheelZoom();
		map.setCenter(new GLatLng(38.609, -96.34), 4)


		mgr = new MarkerManager(map);
		GEvent.addListener(map,"dblclick", function(overlay, point) {
				//do nothing
			}
		);

		GEvent.addListener(map, "click", function(marker, point) {
	    	    	if (marker) {
		    	    	return;
	    	    	}
			
			topoGetAltitude( point.lat(), point.lng(), function( altitude ) {
			    	elevations.push( topoToFeets( altitude ) );
                                //document.getElementById("result").innerHTML += "<br>"+ topoToFeets( altitude );
				    drawGraph();
                        } );
     		    	mapPoints.push(point);
		    	addPoint( mapPoints.length-1 );
	    	    	mgr.addMarker( createMarker(point, mapPoints.length-1), 1, 17 );
		    	//refreshTrailLine();
			//calculateCalories();
	    	});
    	}
	drawBlankGraph();
	var gpsfile = gup('gpsfile');
	if (gpsfile != "")
	{
		showUploadGPS();
		document.getElementById("gpxwaiticon").style.visibility = 'visible';
		//loadXML( gpsfile );
		loadXMLDoc("http://www.trailchaser.com/upload/" + gpsfile);
	} else {
        document.getElementById("instructions").style.visibility = "visible";
	   document.getElementById("map").style.visibility = "hidden";
	   document.getElementById("savePage").style.visibility = "hidden";
	   document.getElementById("gpsPage").style.visibility = "hidden";
	   document.getElementById("loading").style.visibility = "hidden";
    }

	//check for login info
	var cookieUserName = readCookie('tc_user');
	if (cookieUserName) {
        userName = cookieUserName;
    }
}


///////////////////////////////////////////////////////////////////////////
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

