//<![CDATA[

	var route_centerX  = '-90.4371893405914';
	var route_centerY  = '38.6870338102359';
	var route_zoom     = 13;

  var map = null;
  var chart = null;
  
  var elevationService = null;
  
  var mousemarker = null;
  var latlngs  = [];
  var elatlngs = [];
  var afstandsArray = [];
  
  var polyline = null;
  var elevations = null;
  
  var SAMPLES = 300;
	var MILES = "0";
	var KILOMETERS = "1";

  // Load the Visualization API and the piechart package.
  google.load("visualization", "1", {packages: ["columnchart"]});
  
  // Set a callback to run when the Google Visualization API is loaded.
  google.setOnLoadCallback(initialize);


	function initialize(){
//intialize the map
    var myOptions = {
      zoom: route_zoom,
      center: new google.maps.LatLng(route_centerY, route_centerX),
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      scrollwheel: 0
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    
    elevationService = new google.maps.ElevationService();
    
    google.visualization.events.addListener(chart, 'onmouseover', function(e) {
      if (mousemarker == null) {
        mousemarker = new google.maps.Marker({
          position: elevations[e.row].location,
          map: map,
          icon: "http://maps.google.com/mapfiles/ms/icons/green-dot.png"
        });
      } else {
        mousemarker.setPosition(elevations[e.row].location);
      }
    });

		decodePolyline();
  }

  // Clear all overlays, reset the array of points, and hide the chart
  function reset() {
    if (polyline) {
      polyline.setMap(null);
    }
    
    document.getElementById('chart_div').style.display = 'none';
  }

  // Trigger the elevation query for point to point
  // or submit a directions request for the path between points
  function updateElevation() {
    if (latlngs.length > 1) {
      elevationService.getElevationAlongPath({
        path: elatlngs,
        samples: SAMPLES
      }, plotElevation);


	    if (polyline) {
  	    polyline.setMap(null);
  	  }
    
   		polyline = new google.maps.Polyline({
 		     path: latlngs,
 		     strokeColor: "#151B8D", 
   		   strokeWeight: 4, 
  	     strokeOpacity: 0.9,
   		   map: map});

    }
  }

  // Takes an array of ElevationResult objects, draws the path on the map
  // and plots the elevation profile on a GViz ColumnChart
  function plotElevation(results, status) {
    elevations = results;
    
    var multiplier = 1.0;
    var label = "m";
    
    if (getCurrentMultiplier() == 1) {
    	// miles unit / ft
    	multiplier = 3.2808399;
    	label = "ft";
    }
    
    if (status == google.maps.ElevationStatus.OK) {

			if (results[0]) {
				var up_meters   = 0;
				var down_meters = 0;
				var difference  = 0;

		    var path = [];
		  
		  	for (var i = 0; i < results.length; i++) {
		      path.push(elevations[i].location);
  		  }
    
		    var data = new google.visualization.DataTable();
  		  data.addColumn('string', 'Sample');
  		  data.addColumn('number', 'Elevation');
  		  for (var i = 0; i < results.length; i++) {
    		   data.addRow(['', elevations[i].elevation * multiplier]);
    		   
    		   if (i > 0) {
    		   	  difference = (elevations[i].elevation - elevations[i-1].elevation)  * multiplier; 
	    		   if (difference > 0) {
	    		   		up_meters += difference;
	    		   } else {
	    		   		down_meters += -difference;
	    		   }
	    		 }
    		   
    		}

   		  document.getElementById('chart_div').style.display = 'block';
   		  chart.draw(data, {
   		    width: 600,
    		  height: 200,
      		legend: 'none',
      		titleY: "Elevation ("+label+")",
      		focusBorderColor: '#00ff00'
			 		});


      } else {
        alert("No results found");
      }
    } else {
      alert("Elevation service failed due to: " + status);
    }
    
    document.getElementById("info_div").innerHTML = "Total ascent: "+Math.round(up_meters)+" "+label+"<br \>Total descent: "+Math.round(down_meters)+" "+label;
    
  }

  function clearMouseMarker() {
    if (mousemarker != null) {
      mousemarker.setMap(null);
      mousemarker = null;
    }
  }

	// returns distance between two points in miles
	function distance(latlng1,latlng2) {
		var lat1 = latlng1.lat();
		var lon1 = latlng1.lng();
		var lat2 = latlng2.lat();
		var lon2 = latlng2.lng();
	
		var R = 3963.190; // km (change this constant to get miles)

		var dLat = (lat2-lat1) * Math.PI / 180;
		var dLon = (lon2-lon1) * Math.PI / 180; 

		var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) * 
			Math.sin(dLon/2) * Math.sin(dLon/2); 
			
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
		var d = R * c;

		return d;
	}



function decodePolyline () {

  var bounds = new google.maps.LatLngBounds();

  var len = route_polyline.length;
  var index = 0;
	var d=new Array();
  var lat = 0;
  var lng = 0;
  
  var eleveationincrement = Math.round(len/300)+1;
	var elei = 0;  

  reset();

  while (index < len) {
    var b;
    var shift = 0;
    var result = 0;
    do {
      b = route_polyline.charCodeAt(index++) - 63;
      result |= (b & 0x1f) << shift;
      shift += 5;
    } while (b >= 0x20);
    var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
    lat += dlat;

    shift = 0;
    result = 0;
    do {
      b = route_polyline.charCodeAt(index++) - 63;
      result |= (b & 0x1f) << shift;
      shift += 5;
    } while (b >= 0x20);
    var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
    lng += dlng;

    var latlng = new google.maps.LatLng(
        lat * 1e-5,
        lng * 1e-5
      );
		
    bounds.extend(latlng);
		latlngs.push(latlng);
		
		if (latlngs.length > 1) {
			var dist = afstandsArray[afstandsArray.length-1] + distance(latlngs[latlngs.length-2], latlng);
			afstandsArray.push(dist);
		} else {
			afstandsArray.push(0);
		}
		
		if (elei == 0) {
			elatlngs.push(latlng);
			elei = eleveationincrement
		}
		elei --;
  }
  
  map.fitBounds(bounds);
  updateElevation();
  addMileMarkers();
  
}


	function afstandIValgteEnhed(valueToApplyTo){
		return valueToApplyTo * getCurrentMultiplier();
	}

	function getCurrentMultiplier(){
		var unitInput = document.controlPanel.units;
		var curValue;

		if (unitInput.value == 101) {
			curValue = KILOMETERS;
		} else if (unitInput.value == 100) {
			curValue = MILES;
		} else if (unitInput[0].checked) {
			curValue = MILES;
		} else if (unitInput[1].checked) {
			curValue = KILOMETERS;
		}
		var multiplier;

		if (curValue==KILOMETERS) {
			multiplier = 1.609345;
		} else {
			multiplier = 1.0;
		}

		return multiplier;
	}


	function addMileMarkers() {
		var totaldist = 0;
		var sidsteMilMarker = 0;
		var totalDistance = afstandIValgteEnhed(afstandsArray[afstandsArray.length-1]);

		//alert("Total distance:"+totalDistance);

		// start
    var marker = new google.maps.Marker({
      position: latlngs[0],
      map: map,
      icon: "http://www.logyourrun.com/images/M_images/map_pointer_0.png", 
      draggable: false
    });

		// end
    var marker = new google.maps.Marker({
      position: latlngs[latlngs.length-1],
      map: map,
      icon: "http://www.logyourrun.com/images/M_images/map_pointer_e.png", 
      draggable: false
    });

		if(totalDistance >= 30) {
			var increment = 5;
		} else if(totalDistance >= 16) {
			var increment = 2;
		} else {
			var increment = 1;
		}

		for (var i=2; i < (afstandsArray.length); i++)
		{
			//alert(i+":"+afstandsArray[i]+"("+afstandsArray.length+")");

			var legdistance = afstandsArray[i] - afstandsArray[i-1];
			legdistance = afstandIValgteEnhed(legdistance);
			var afstandTilNaesteMarker = Math.ceil(totaldist/increment)*increment - totaldist;

// GET MILE MARKER NUMBER
			var begyndelsesAfstand = Math.floor(afstandIValgteEnhed(afstandsArray[i]));

// next point IS HERE
			if (afstandTilNaesteMarker == 0) {
				afstandTilNaesteMarker += increment;
			}

			while ((afstandTilNaesteMarker < (totaldist + legdistance)) && ((totaldist + afstandTilNaesteMarker) < (totaldist + legdistance))) {
				//alert ("afstandTilNaesteMarker="+afstandTilNaesteMarker+"<totaldist("+totaldist+")+legdist("+legdistance+") increment"+increment);
				if(begyndelsesAfstand >= sidsteMilMarker+increment) {
					sidsteMilMarker += increment;
					mileMarker(afstandTilNaesteMarker, legdistance, latlngs[i-2], latlngs[i-1], sidsteMilMarker);
				}
				afstandTilNaesteMarker += increment;
			}
			totaldist += legdistance;
		}
	}

	function mileMarker(distToNextMarker, legDistance, point1, point2, sidsteMilMarker) {

		var percent = (distToNextMarker/legDistance);

		klat = percent * (point1.lat()-point2.lat());
		klng = percent * (point1.lng()-point2.lng());

		if (parseFloat(point1.lat()) < parseFloat(point2.lat())) {
			klat = -klat;
			klng = -klng;
		}

		var newpoint =  new google.maps.LatLng(parseFloat(point1.lat()) + klat, parseFloat(point1.lng()) + klng);

    var marker = new google.maps.Marker({
      position: newpoint,
      map: map,
      icon: "http://www.logyourrun.com/images/M_images/map_pointer"+sidsteMilMarker+".png", 
      draggable: false
    });

	}


	//]]>
