//<![CDATA[

var markers = [];
var markersVisible = true;
var course;
var map;
var gmo;
var node;

function setupMap() {
//    var mapSize = new GSize( 900, 700 );
    map = new GMap2(document.getElementById("map"),
    		{draggableCursor: 'crosshair', draggingCursor: 'pointer'});

    map.addControl( new GLargeMapControl() );
    map.addControl( new GMapTypeControl() );
    map.addMapType( G_PHYSICAL_MAP );

    map.enableScrollWheelZoom();

    // Set up the icon and options to make the nodes of the polyline
    // be our own icon.
    node = new GIcon( G_DEFAULT_ICON );
    node.image = "images/node.png";
    node.shadow = null;
    node.iconSize = new GSize( 10, 10 );
    node.iconAnchor = new GPoint( 5, 5 );

    // Set up MarkerOptions
    gmo = { icon: node, draggable: true };

    // 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.
    GEvent.addListener(map, "click", function(overlay,point) {
	// If the user clicks a tag, remove it from the list.
	if (overlay) { // Clicked on the overlay.
	    for (i=0; i < markers.length; i++) {
		if (overlay == markers[i]) {
		    map.removeOverlay( overlay );
		    markers.splice(i,1);
		    break;
		}
	    }
	}
	// The user clicked the map, add it to the route and add a marker
	else { // clicked on the map.
	    mark = getNewMark( point );

	    markers.push( mark );
	    if (markersVisible) {
		map.addOverlay( mark ); 
	    }
	}

	// Redraw the course
	courseRedraw();
    });

    map.setCenter( new GLatLng( 40.4500, -80.0000 ), 14);
}

// Handle the drag event ending. Move the associated
// location of the marker to reflect the drag.
function getNewMark( point ) {
    var mark = new GMarker( point, gmo );
   
    GEvent.addListener(mark, "dragend", function() { courseRedraw(); });

    return mark;
}

// Redraw the course, reflecting drags and clicks
//
function courseRedraw() {
    // Undraw the course
    if (course) {
	map.removeOverlay( course);
    }

    // Get the points on the map
    var i;
    var points = [];
    for (i = 0; i < markers.length; i++) {
	points.push( markers[i].getLatLng() );
    }

    // Redraw the course
    course = new GPolyline(points);
    map.addOverlay( course );

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

}

function loadMapMaker() {
    if (map == null) {
	setupMap();
    }
    map.clearOverlays();
}


// 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.y);
        var b = Math.deg2rad( 90 - ll_2.y);
        var theta = Math.deg2rad( ll_2.x - ll_1.x);
        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 (markers.length > 1) {
	    var dist = 0.0;
	    var i;
	    var lastPoint;
	    var curPoint = markers[0].getLatLng();

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

	return dist;
}


function loadDrawMap( ) {
    var map = setupMap();

    // Download the data in mapdata.xml and load it on the map. The format we
    // expect is:
    // <course>
    //   <turn lat="37.441" lng="-122.141"/>
    //   <turn lat="37.322" lng="-121.213"/>
    // </course>
    var request = GXmlHttp.create();
    request.open( "GET", "mapdata.xml", true );
    request.onreadystatechange = function() {
//	document.getElementById("message").innerHTML += "readyState="
//				    + request.readyState
//				    + "<br>";
	if (request.readyState == 4) {
	    var xmlDoc = request.responseXML;
	    var turns = xmlDoc.documentElement.getElementsByTagName("turn");
	    for (var i = 0; i < turns.length; i++) {
		var point = new GPoint(parseFloat(turns[i].getAttribute("lon")),
			       parseFloat(turns[i].getAttribute("lat")));
		points.push( point );

//		document.getElementById("message").innerHTML += "&nbsp;&nbsp;"
//				    + "lat=" + point.y + ", lon=" + point.x
//				    + "<br>";
	    }

	    map.setCenter(new GLatLng( 40.4450, -79.9500 ), 12 );
//	    map.centerAndZoom(points[0], 2);

	    // Show this marker's index in the info window when it is clicked
	    var html = "Start/End<br>"
			+ "Penn Brewery";
	    GEvent.addListener(mark, "click", function() {
		mark.openInfoWindowHtml(html);
	    });

	}
    }
    request.send(null);
}

// This function hides/shows the marker overlays on the map
//
function toggleMarkers( ) {
    if (markersVisible) {
	hideMarkers();
	document.getElementById("toggle").value = "Show Marks";
    }
    else {
	showMarkers();
	document.getElementById("toggle").value = "Hide Marks";
    }
}

// This function hides the marker overlays on the map
//
function hideMarkers( ) {
    if (markersVisible) {
	for (i=0; i < markers.length; i++) {
	    map.removeOverlay( markers[i]);
	}
	markersVisible = false;
    }
}

// This function paints the marker overlays on the map
//
function showMarkers( ) {
    if (!markersVisible) {
	for (i=0; i < markers.length; i++) {
	    map.addOverlay( markers[i]);
	}
	markersVisible = true;
    }
}

// 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;
}

// Clear the turn markers and message.
function clearMap() {
    if (map == null) {
	alert( "Can't find the map" );
    }
    while (markers.length > 0) {
	obj = markers.shift();
	obj = null;
    }
    document.getElementById("message").innerHTML = "&nbsp;";
    map.clearOverlays();
}

//]]>
