/*

File: trail_map.js
Purpose: To display an interactive map via the Google Maps API. Trail map overlays
	are displayed on demand; map data comes from a KML file.
Requirements:
	• An Google Maps API key (<http://www.google.com/apis/maps/>) referenced in
		the <head> element via the <script> element. It must have at least the v=2.x
		parameter.
		e.g., <script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2sensor=false&amp;key=ABQIAAAA4rdFuq3qAb8hCfcU8HQtHRS-md13dsta7qI8jZfgj5vlUAbu3hSAZo_bQWz8o0gsVdZAGw6KO6Qndg"></script>
	• onload() and onunload() events in the <body> tag. The GUnload() function is
		handled by Google.
		e.g., <body onload="initializeMap();" onunload="GUnload();">
	• An element, such as a <div>, with an id attribute of "map_canvas"
	• The object, "trailData", defined in the <head> element

*/



//==============================================================================
// Global variables
//==============================================================================

// Truckee, California
var initialLatitude = 39.342163;
var initialLongitude = -120.203568;
var initialZoom = 10;                                                           // Maximum zoom is 17

var center = new GLatLng(initialLatitude, initialLongitude);
var geoXml = {};
var map;
//var markers = new Object;                                                     // Supposedly a depreciated method
var markers = {};
var sidebarMarker = -1;



//==============================================================================
// Inital map display & configuration
//==============================================================================

function initializeMap() {
	if (GBrowserIsCompatible()) {

		var mapContainer = document.getElementById("map_canvas");
		map = new GMap2(mapContainer);

		// Add controls & map type
		map.addControl(new GSmallZoomControl());                                // Just the +/- for zoom
		map.addControl(new GMapTypeControl());                                  // Display-type controls (map, satellite, hybrid)
		map.addControl(new GScaleControl());                                    // Scale
		map.setMapType(G_HYBRID_MAP);                                           // Satellite view with streets, too
		//map.enableScrollWheelZoom();                                          // Allow zooming with the scroll wheel
		map.setCenter(center, initialZoom);                                     // Set center & zoom
		
		placeMarkers();
		
	} else {
		alert("Sorry, the Google Maps functionality on this page is not compatible with your web browser.");
	}
}



//==============================================================================
// Write all of the markers
//==============================================================================

function placeMarkers() {

	for (var trailId in trailData) {

		var html;
		var trailName;
		var longdescription;
		var surface;
		var shortDescription;
		var difficulty;
		var conditions;
		var conditionsDate;
		var webpage;
		var googleMap;
		var latitude;
		var longitude;
		var kml;
				
		var trail = trailData[trailId];

		// Get the data for each trail
		for (var property in trail) {
			if (property == "trailName")        { trailName = trail[property]; }
			if (property == "longDescription")  { longDescription = trail[property]; }
			if (property == "surface")          { surface = trail[property]; }
			if (property == "shortDescription") { shortDescription = trail[property]; }
			if (property == "difficulty")       { difficulty = trail[property]; }
			if (property == "conditions")       { conditions = trail[property]; }
			if (property == "conditionsDate")   { conditionsDate = trail[property]; }
			if (property == "webpage")          { webpage = trail[property]; }
			if (property == "googleMap")        { googleMap = trail[property]; }
			if (property == "latitude")         { latitude = trail[property]; }
			if (property == "longitude")        { longitude = trail[property]; }
			if (property == "kml")              { kml = trail[property]; }
		}

		// Plot a marker for each trail
		var point = new GLatLng(latitude, longitude);
		//var onclick = "myLightWindow.activateWindow({href: 'full-trail-description.php?trail_id=" + trailId + "', height: 500, width: 713}); return false;";
		var onclick = "return showWashBox('full-trail-description.php?trail_id=" + trailId + "');";
		var html = "<div class=\"map_balloon\">\
	<h5>" + trailName + "</h5>\
	<div><span>Type: </span>" + surface + "</div>\
	<div><span>Difficulty: </span>" + difficulty + "</div>\
	<div><span>Description: </span>" + shortDescription + "</div>\
	<br />";
		if (kml !== null && kml !== '') {
			html += "	<a style=\"cursor: pointer;\" onclick=\"hideBalloonKeepTrail(" + trailId + ");\">Trail route only</a>";
			html += "	<br />";
		}
		html +=	"	<a onclick=\"" + onclick + "\" href=\"full-trail-description.php?trail_id=" + trailId + "\">Full description</a>\
</div>";
		var marker = createMarker(trailId, point, html, kml);
		map.addOverlay(marker);                                                 // Mark the location with a red marker (This line must be after map.setCenter())
		//markers.trailId = marker;                                             // Set-up for the sidebar click
		markers[trailId] = marker;                                              // Equivalent to the line above if "trailId" evaluated, but it is literal

	}

}



//==============================================================================
// Create a single marker & associate with it an HTML info window and trail KML
//==============================================================================

function createMarker(trailId, point, html, kml) {                              // Inline functions are used because otherwise they'll fire without waiting/listening
	var marker = new GMarker(point);    			                            // To use a custom icon, add the icon object (that you create) as an argument
	GEvent.addListener(marker, "click",
		function() {
			if (geoXml) {
				map.removeOverlay(geoXml);
			}
			geoXml = new GGeoXml("http://truckeetrails.org/trail_data/" + kml);
			map.openInfoWindowHtml(point, html, {
				onOpenFn: function()  { map.addOverlay(geoXml); },              // onOpenFn & onCloseFn only work with GMap2 object (not GMarker)
				onCloseFn: function() { map.removeOverlay(geoXml); }
			})
		}
	);
	//GEvent.addListener(marker, "click", function() { var geoXml = new GGeoXml(kmlUri); map.addOverlay(geoXml); });
	return marker;
}



//==============================================================================
// Show the info window & KML of a trail selected from the list
//==============================================================================

function showTrail(trailId) {
	map.setCenter(center, initialZoom);
	if (trailData.hasOwnProperty(trailId)) {
		var marker = markers[trailId];
		GEvent.trigger(marker, 'click');
	}
}



//==============================================================================
// Hide the info window but keep the trail until the next trail is selected
//==============================================================================

function hideBalloonKeepTrail(trailId) {
	if (trailData.hasOwnProperty(trailId)) {
		map.closeInfoWindow();
		map.addOverlay(geoXml);
	}
}
