//*************************************************************************//
// maps.js
//
// This script has been written to support the justawalktothebeach website.
//
//
// The ldt panned routes are read from an xml file (routes.xml) listing travellers
// and their planned routes
//
// <travellers>
//   <ldt name="Nick the mad one" html="Nick is cyling from ...">
//	   <point lat="51.667190" lng="-1.336560" />
//	   <point lat="51.649740" lng="-1.574310" />
//	   ...
//   </ldt>
//   ...
// </travellers>
//
// The route detail is reconstructed from a route planned on maps.google.com.
// 'Send' the route to info@justawalktothebeach.org 
// The link is of the form:
//   <http://maps.google.com/maps?f=d&hl=en&geocode=2358511006754617768,
//	51.667190,-1.336560 %3B17081750908458806847,
//	51.649740,-1.574310 %3B13771225708539933918,
//	&saddr=startpoint&daddr=route description
//	+to:saunton+sands,+devon and some more information ...>
//
// The lat/long listed in the first section of the link should be copied to the routes file
//
//
// Copyright: justawalktothebeach 2008
// Author: Nick Battam
// Date: 02-May-2008
//*************************************************************************//

// main map object
var map;
// marker on Saunton Sands
var SAUNTON_SANDS = new GLatLng(51.11764, -4.216347);
// initial map centre
var MAP_CENTRE = new GLatLng(51.941230, -1.555080);
// datafile
var DATAFILE="/Assets/routes.xml";

// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var side_bar_html = "";
var gmarkers = [];
var htmls = [];
var i = 0;
var dirs = [];

// global directions object that is reused
var directions = null;

// A function to create the marker and set up the event window
// Dont try to unroll this function. It has to be here for the function closure
// Each instance of the function preserves the contends of a different instance
// of the "marker" and "html" variables which will be needed later when the event triggers.    
function createMarker(point, name, html, image){

	var marker = new GMarker(point);
	
	if (name == null) {
		// simple handler if only html provided
		GEvent.addListener(marker, "click", function(){
			marker.openInfoWindowHtml(html);
		});
	}
	else {
		// name link added to side bar linked to caption and route information.		
		var modHtml = "";
		var tailHtml = "";
		
		modHtml += '<table width="300">';
		modHtml += '<tr>';
		// prepend an image if one has been passed
		if (image != null ) {
			modHtml += '<td rowspan="2">'
			modHtml += '<img align=left height="100px" alt="' + name + '" src="' + image + '"/>'
			modHtml += '</td>'
		}	
		modHtml += '<td>'
		modHtml += html;
		tailHtml += '</td>'

		modHtml += '</tr>';
		modHtml += '<tr>';
		modHtml += '<td>';
		
		tailHtml += '&nbsp;</td>';
		tailHtml += '</tr>'
		tailHtml += '</table>'
		// cache the html including the image
		htmls[i] = modHtml + tailHtml;
		
		// append the 'show route' instruction 
		if (dirs[i].length > 1) {
			modHtml += '<br>Show <a href="javascript:ldtClick(' + i + ')">route</a>.';
		}	
	
		modHtml += tailHtml;
		
		// create the listener
		GEvent.addListener(marker, "click", function(){
			marker.openInfoWindowHtml(modHtml);
		});		
		
		// save the info we need to use later for the side_bar
		gmarkers[i] = marker;
		// add a line to the side_bar html
		side_bar_html += '<a href="javascript:ldtClick(' + i + ')">' + name + '</a><br>';
		i++;
	}
	
	
	return marker;
}

// This function picks up the click and opens the corresponding info window
function ldtClick(i){
  	gmarkers[i].openInfoWindowHtml(htmls[i]);
	createDirections(dirs[i]);
}

function load(){
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.enableScrollWheelZoom();
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        
        var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10, 15));
        map.addControl(new GScaleControl(), bottomRight);
        
        map.setCenter(MAP_CENTRE, 7);
        
        var mgrOptions = {
            borderPadding: 50,
            maxZoom: 15,
            trackMarkers: true
        };
        
        var marker = createMarker(SAUNTON_SANDS,null,"Saunton Sands: the big finish");
     	map.addOverlay(marker);
		
	    loadPoints();
        
    }
    // display a warning if the browser was not compatible
    else {
        alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}

// load the route data from the datafile
function loadPoints(){
     
    // </markers>
    GDownloadUrl(DATAFILE, function(data, responseCode){
        xmlDoc = GXml.parse(data);
       
        
        // ========= Now process the polylines ===========
        var lines = xmlDoc.documentElement.getElementsByTagName("ldt");
        // read each line
        for (var a = 0; a < lines.length; a++) {
        
            // read each point on that line
            var points = lines[a].getElementsByTagName("point");
            var pts = [];
            for (var i = 0; i < points.length; i++) {
                pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
									 parseFloat(points[i].getAttribute("lng")));
            }

			// Store the point vector         
			dirs[a] = pts;
			
			// Extract the decrions to use in the screen
            var html = lines[a].getAttribute("html");
            var label = lines[a].getAttribute("name");
			var image = lines[a].getAttribute("image");
            
            // create the marker
            var marker = createMarker(pts[0], label, html, image);
            map.addOverlay(marker);
        }
		
        // put the assembled side_bar_html contents into the side_bar div
        document.getElementById("side_bar").innerHTML = side_bar_html;
		
		// Create link in side bar for clearing displayed links
		document.getElementById("side_bar_base").innerHTML =  '<a href="javascript:clearDirections()">Clear All</a><br>';

        
    });    
}

// clear the directions object
function clearDirections() {
	createDirections(null);
}

// Create and add a set of directions
// to the map using waypoints
function createDirections(waypoints){

	// if this is the first set of directions, create
	if (directions == null) {
		directions = new GDirections(map);
		GEvent.addListener(directions, "addoverlay", hideDirMarkers);
	}
	
	// load the directions from the precreated waypoint list
	if (directions!=null && waypoints != null) {
		directions.loadFromWaypoints(waypoints, {getPolyline:true,preserveViewport:true});
	}
	else {
		// if a null argument is passed clear the map
		directions.clear();
	}
	
	// dynamically hide the waypoint markers
	function hideDirMarkers(){
		var numMarkers = directions.getNumGeocodes();
		for (var i = 0; i < numMarkers; i++) {
			var marker = directions.getMarker(i);
			if (marker != null) {
				marker.hide();
			}
		}
	}
}

