//<![CDATA[

var routeMap;
var routeService;
var routeDisplayer;
var routePoints;
var routeLine;
var markersVisible = true;

function setupMap() {
    var mapOpts = {
      zoom: 14,
      draggableCursor: 'crosshair',
      draggingCursor: 'pointer',
      typeControl: true,
      scaleControl: true,
      center: new google.maps.LatLng(40.4500, -80.0000),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };  

    routeMap = new google.maps.Map(document.getElementById("map"), mapOpts);

    routeService = new google.maps.DirectionsService();

    routeDisplayer = new google.maps.DirectionsRenderer();
    routeDisplayer.setMap(routeMap);

    routeLine = new google.maps.Polyline({ map: routeMap,
    					strokeColor: "#6666FF",
					strokeWeight: 3});
    routePoints = new Array();

    // If the user clicks on the map, save the point in an array
    // and put a marker on the point. Save the marker so it can
    // be removed if the user clicks the marker.
    google.maps.event.addListener(routeMap, "click", handleMapClick);
    document.getElementById("message").innerHTML = "starting ";
}

// When the map is clicked on and there are multiple points on the map
// request a route to the new location.
function handleMapClick(mapEvent)
{
    if (routePoints.length > 0)
    {
	var start = routePoints.pop();
	var finish = mapEvent.latLng;

	routePoints.push(start);
	routePoints.push(finish);

	var request = {
		origin: start,
		destination: finish,
		travelMode: google.maps.DirectionsTravelMode.WALKING
	    };

	routeService.route(request, handleDirectionResponse);
    }
    else
    {
	routePoints.push(mapEvent.latLng);
    }
}

// Handle the return from the directions request
//
function handleDirectionResponse(result, status)
{
    if (status == google.maps.DirectionsStatus.OK)
    {
	var i = routePoints.length;
        var route = result.routes[0];
	var last = routePoints.pop();
	var routeLength = 0;

	var dist = distance_between_points(route.overview_path[0], last);
	for (var j = 0; j < route.legs.length; j++)
	{
	    routeLength = route.legs[j].distance.value;
	}

	dist = dist * 3;

	// Safety check for crazy long routes that go out of the way.
	if (dist > routeLength)
	{
	    routePoints = routePoints.concat(route.overview_path);
	}
	routePoints.push(last);

	displayRoute();
    }
}

// Remove the last route click and redraw the map
//
function undoRoute()
{
    endPoint = routePoints.pop();

    displayRoute();
}

// Update the distance displayed and the course outline.
//
function displayRoute()
{

    if (routePoints.length > 1) {
	var dist = calculateDistance( ) / 1609.344;;
	document.getElementById("message").innerHTML =
			"Course length is " + dist.toFixed(2) + " miles";
    }
    else {
	document.getElementById("message").innerHTML = "";
    }

    routeLine.setPath( routePoints );
}

// Clear the turn markers and message.
//
function clearMap() {
    if (!confirm("Clear the course and start over?"))
    {
	return;
    }
    if (routeMap == null) {
	alert( "Can't find the map" );
    }
    document.getElementById("message").innerHTML = "&nbsp;";
    routePoints = new Array();
    routeLine.setPath( routePoints );
    displayRoute();
}

// Utility function for converting degrees to radians
Math.deg2rad = function ( x ) {
        return x * (Math.PI / 180.0); 
}

// Distance in metres
var EARTH_RADIUS = 6367000;

// Calculates the distance (in metres) between 2 points. 
function distance_between_points ( p1, p2 ) {
	var ll_1 = p1;
	var ll_2 = p2;
        var a = Math.deg2rad( 90 - ll_1.lng());
        var b = Math.deg2rad( 90 - ll_2.lng());
        var theta = Math.deg2rad( ll_2.lat() - ll_1.lat());
        var c = Math.acos( Math.cos(a) * Math.cos(b)
			    + Math.sin(a) * Math.sin(b) * Math.cos(theta));

        return c * EARTH_RADIUS; 
}

// Takes an array of points and works out the total distance
function calculateDistance () {
    if (routePoints.length > 1)
    {
	var dist = 0.0;
	var lastPoint;
	var curPoint = routePoints[0];

	for (var i = 1; i < routePoints.length; i++) {
	    lastPoint = curPoint;
	    curPoint = routePoints[i];
	    dist += distance_between_points(lastPoint, curPoint);
	}
    }

    return dist;
}

function getNewMark( point ) {
    // Set up the icon and options to make the nodes of the polyline
    // be our own icon.
    var mark = new google.maps.Marker({
			  draggable: true,
			  position: point.LatLng,
			  flat: true,
			  map: map,
			  icon: 'images/node.png'
			  });

    google.maps.event.addListener(mark, "click", removeMark);

    google.maps.event.addListener(mark, "dragend",
		    function() { courseRedraw(); });
    return mark;
}

function loadMapMaker() {
	setupMap();
}

// This function dumps the map points to the message area.
//
function showPoints( ) {
    var latLonStr = "&lt;course&gt;<br>";
    for (i=0; i < markers.length; i++) {
	latLon = markers[i].getLatLng();
	latLonStr += "&lt;turn lon=\"" + latLon.x
			+ "\" lat=\"" + latLon.y
			+ "\"/&gt;<br>";
    }
    latLonStr += "&lt;/course&gt;";
    document.getElementById("message").innerHTML = latLonStr;
}
//]]>

