///////////////////////////////////////////////////////////////////////////////////////////
// Google Map Loader v1.0
// By Matthew Harris, www.runtings.com
///////////////////////////////////////////////////////////////////////////////////////////
// ChangeLog
//  v1.0 - 14/05/2008 - Initial Release
///////////////////////////////////////////////////////////////////////////////////////////
// Usage Instructions - Include as follows: 
//  addevent.js, google?key=, config.js, googlemap.js, googlemap.css
///////////////////////////////////////////////////////////////////////////////////////////
// this code is based from a composite of several sources (thanks):
//   google map api documentation - kml overlays
//   http://mapperz.blogspot.com/2006/11/google-maps-directions-via-kml-google.html
//   http://esa.ilmari.googlepages.com/scrollzoom.htm
//   http://googlemapsapi.blogspot.com/2007/02/gdownloadurl-update-better-error.html
//   http://maps.forum.nu/gm_minimap_in_infowindow.html
///////////////////////////////////////////////////////////////////////////////////////////

// global placemarker class
function rtpPlaceMarker(Name, Desc, GLatLng, HtmlCode)
{
	// properties
	this.name = Name;
	this.description = Desc;
	this.gLatLng = GLatLng;
	this.htmlCode = HtmlCode;
	this.markerId;
}

// some globals
var map;
var directionsFormCount = 0;
var placeMarkers = [];

// mod - show loading message (requires jQuery)
$(document).ready(function(){
   $("#maploading").removeClass("notloaded");						   
});


// Creates a marker at the given point with the given number label
function createMarker(point, htmlcode) {
  var marker = new GMarker(point);
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(htmlcode);
  });
  
  return marker;
}

// creates a string containing a form for driving directions to this location
function createDirectionsString(point, name) {
	var directionsForm = '<div class="directions-form">' +
	'<form method="get" name="directions_frm_' + directionsFormCount + '" target="' + cfgDirectionsFormTarget + '" action="http://maps.google.co.uk/maps">' +
	'<h6>Get Driving Directions<\/h6>' +
    '<label>Your postcode: <input type="text" name="saddr" class="textbox" value="" \/><\/label>' +
	'<input class="button" type="submit" value="Go" \/><br \/>' +
	'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + '(' + name + ')" \/>' +
	'<input type="hidden" name="hl" value="en" \/>' +
	'<\/form><\/div>';
	
	directionsFormCount += 1;
	
	return directionsForm;
}

// prevents scrolling the document when mouse wheeling over a map
function wheelEvent(e)
{
	if (!e){
		e = window.event
	}
	
	if (e.preventDefault){
		e.preventDefault()
	}
	
	e.returnValue = false;
}

// find the map center point and zoom level
function findMapCenterAndZoom()
{
	// protect from errors
	if(map==null) return;

	// ok to run
	var bounds = new GLatLngBounds();
	
	for (var k=0; k < placeMarkers.length; k++)
	{
		// store the bounds (so we can calculate map center and zoom level)
		bounds.extend(placeMarkers[k].gLatLng);
	}
	
	var czoom = (map.getBoundsZoomLevel(bounds));
	var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2;
	var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2;
	
	// set center point
	map.setCenter(new GLatLng(clat,clng),czoom);
}

// trigger an marker click
function triggerMarkerClick(i)
{
	GEvent.trigger(placeMarkers[i].markerId, "click");
}

// map startup
function loadMap()
{
	if (GBrowserIsCompatible())
	{      
		GDownloadUrl(kmlDocumentUrl, function(data, responseCode) {
		  // To ensure against HTTP errors that result in null or bad data,
		  // always check status code is equal to 200 before processing the data
		  if(responseCode == 200) {
			// success
			processKmlFile(data);
			setupGoogleMap();
			
			// insert the sidebar if an insertion point has been set
			if (cfgSideBarElement)
				setupSideBar(cfgSideBarElement);
				
		  } else if(responseCode == -1) {
			alert("Data request timed out. Please try later.");
		  } else { 
			alert("Request resulted in error. Check XML file is retrievable. Error code: " + responseCode);
		  }
		});		
	} 
    // display a warning if the browser was not compatible
    else {
	  // todo - find div#map and put the error message in here
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }

}
	
function processKmlFile(doc)
{
	var xmlDoc = GXml.parse(doc);
	var placemarks = xmlDoc.documentElement.getElementsByTagName("Placemark");
			
	// got all placemarks in a list
	for (var i = 0; i < placemarks.length; i++)
	{
		// extract info
		var name = GXml.value(placemarks[i].getElementsByTagName("name")[0]);
		var desc = GXml.value(placemarks[i].getElementsByTagName("description")[0]);

		// extract lat/long
		var coords = GXml.value(placemarks[i].getElementsByTagName("coordinates")[0]);				
		var bits = coords.split(",");
		var point = new GLatLng(parseFloat(bits[1]), parseFloat(bits[0]));
		
		// concatenate the name and description
		var infohtml = "<h2>" + name + "<\/h2>" + desc;

		// add the driving directions form
		if (cfgIncludeDrivingDirections)
			infohtml += createDirectionsString(point, name);				
		
		// add all the information to the global store
		var placeMarker = new rtpPlaceMarker(name, desc, point, infohtml);
		placeMarkers.push(placeMarker);
	}
}

// insert a list of markers into the sidebar div
function setupSideBar(branchListElement)
{
	// add to the branch <ul> list
	/*	OfficeOneMarker.openInfoWindowHtml(OfficeOneHTML);*/
	var branch_list = "";
	
	for (var j=0; j < placeMarkers.length; j++) {
	
		var desc = placeMarkers[j].name;
	
	    branch_list += '<li><a href="#" onclick="triggerMarkerClick(' + j + '); return false;">' + desc + '<\/a><\/li>';	
	}
	
	// insert copy
	document.getElementById(branchListElement).innerHTML = 
		"<h1>Branches<\/h1>" +
		'<div class="borderfade_top"><\/div>' +
		"<ul>" + branch_list + "<\/ul>";
}
		

// setup the google map with processed data
function setupGoogleMap()
{	
	// find the map
	map = new GMap2(document.getElementById("map"));
	
	// add navigation controls
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	
	// setup scroll wheel features
	map.enableDoubleClickZoom();
	map.enableScrollWheelZoom();
	map.enableContinuousZoom();
	map.getContainer().style.overflow = "hidden";

	GEvent.addDomListener(map.getContainer(), "DOMMouseScroll", wheelEvent);
	map.getContainer().onmousewheel = wheelEvent; 			
	

	// calculate map center and zoom level			
	////////////////////////////////////////////////////////////////////////
	findMapCenterAndZoom();

	
	// add all the extracted map markers
	////////////////////////////////////////////////////////////////////////
	// setup the markers and infowindow click events
	for (var k=0; k < placeMarkers.length; k++) {
		var marker = createMarker(placeMarkers[k].gLatLng, placeMarkers[k].htmlCode);	
		
		placeMarkers[k].markerId = marker;
	}	
	
	// add the markers to the map
	for (var j=0; j < placeMarkers.length; j++) {
	    map.addOverlay(placeMarkers[j].markerId);		
	}
	
} // setupGoogleMap()


// uses addevent.js
addEvent(window, 'load', loadMap);