/*

 88888888b  888888ba  dP    dP  .88888.           8888ba.88ba  
 88         88    `8b Y8.  .8P d8'   `88          88  `8b  `8b 
a88aaaa    a88aaaa8P'  Y8aa8P  88        .d8888b. 88   88   88 
 88         88   `8b.    88    88   YP88 88'  `88 88   88   88 
 88         88    .88    88    Y8.   .88 88.  .88 88   88   88 
 88888888P  88888888P    dP     `88888'  `88888P' dP   dP   dP 

E.B.Y.G.o.M v0.2b
Easilly Build Your Google Map - Beta Version 1
http://www.canazza.co.uk/scripts/EBYGoM

By David McQuillan
	Started		31 March 2008
Last Update 	10 April 2008
*/


/*

Google API Documentation: http://code.google.com/apis/maps/documentation/reference.html

##Function List

gMapLoad() - Called on page load, initilises the Google Maps and Directions Pane

load_directions(from, to) - shows the directions From somewhere To somewhere, From and To can be place names or co-ordinates

start_point_to_point(from,to) - a more robust version of load_directions, use this if the search may contain a postcode

createMarker(location,caption,icon) - create a marker on a point, location is a GLatLng(a,b) caption is a string/html and icon is a GIcon()

dragMarker(location,start,end) - creates a draggable marker at location, which, when the drag starts, executes 'start' (function) and when it is dropped or clicked executes 'end' (function) - the default is a bubble with the co-ordinates

newIcon(image_url,width,height) - creates a new icon with an image (url relative to document) with width and height set as parameters, the hotspot is defaulted to the middle bottom of the image (like the default google image)

*/

/*	Setup Variables */
if(!MapIdName)				
var MapIdName = "map"; 						//the id attribute of the Map Element - default is "map"
	
if(!DirectionsIdName)		
var DirectionsIdName = "map_directions";	//the id attribute of the Directions Element - default is "map_directions"

var map = null;								//Once the page loads this will become the gMap2 object
var directions = null;						//Once the page loads this will become the gDirections object
var map_div = null
var directionsPanel = null
var Location_String = "(0, 0)"; //Copy the Co-ordinates from the draggable marker here to set the Default Position



if(!default_zoom)
var default_zoom = 10

///////////////////////////////////////////////////////////////
///	Initial Load function for google Maps API
//	Sets up Map and Direction objects
//	Adds Map types and removes the old physical map (will now be Normal, Hybrid and Terrain
//	Sets up Div Styles
//	Sets the Map center (default is 0,0 zoom 1)
//	Enables the scroll Wheel
//	Adds Map controls
//

function gMapLoad() {
	map_div = document.getElementById(MapIdName);
	directionsPanel = document.getElementById(DirectionsIdName);
	
	map_div.innerHTML = "Loading Google Maps";

	def_array = default_loc_string.split(",")
	
	default_long = 	parseFloat(	def_array[1].substr(	0,	def_array[1].length - 1	)	);
	default_lat = 	parseFloat(	def_array[0].substr(	1,	def_array[0].length 	)	);
	if(isNaN(default_long))default_long = 0;
	if(isNaN(default_lat))default_lat = 0;	
		
			
	if (GBrowserIsCompatible()) {
		map = new GMap2(map_div);				
		map.addMapType(G_PHYSICAL_MAP); 		
		map.removeMapType(G_SATELLITE_MAP);
		map.enableScrollWheelZoom();
     	map.addControl(new GSmallMapControl());
      	map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(default_lat,default_long),default_zoom);
      	directions = new GDirections(map, directionsPanel);
		GEvent.addListener(directions, "error", handleErrors);

		build_map()
	}
}
function handleErrors(){
	switch(directions.getStatus().code) {
		case G_GEO_UNKNOWN_ADDRESS:
			directionsPanel.innerHTML = "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code;
			break;
		case G_GEO_SERVER_ERROR:
			directionsPanel.innerHTML = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code;
			break;
		case G_GEO_MISSING_QUERY:
			directionsPanel.innerHTML = "The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code;
			break;
		case G_GEO_BAD_KEY:
			directionsPanel.innerHTML = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code;
			break;
		case G_GEO_BAD_REQUEST:
			directionsPanel.innerHTML = "A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code;
			break;
		default:
			directionsPanel.innerHTML = "An unknown error occurred.";
	}
}


function setDirections(fromAddress, toAddress, locale) {
      directions.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }


function start_point_to_point(From_code,To_code) {
	if(To_code == "G_DEFAULT") {
		To_code = default_lat+","+default_long
	}
	if(From_code == "G_DEFAULT") {
		From_code = default_lat+","+default_long;
	}
	directionsPanel.innerHTML = "";
	setDirections(From_code,To_code,"en_uk");
}

/////////////////////////////////////////////////
//	createMarker
//	Creates a marker at the position (type:gLatLng()) with caption (type: string/html) in a popup balloon
//

function createMarker(position,caption,icon) {
	var marker = new GMarker(position,icon);
    map.addOverlay(marker);
	if(caption)
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindow(caption);
	})
	return marker;
}

function dragMarker(position,start,end) {


		var marker = new GMarker(position,{draggable: true, icon:Icons[0]});
		if(!start) {
			start = function() {
          		map.closeInfoWindow();
       		};
		}
		if(!end) {
			end = function() {
			  marker.openInfoWindowHtml("Location: " + marker.getPoint().toString());
			}	
		}
        GEvent.addListener(marker, "dragstart", start);

        GEvent.addListener(marker, "dragend", end);
        GEvent.addListener(marker, "click", end);
        map.addOverlay(marker);
		return marker
}
var Icons = Array();

function newIcon(image_url,w,h) {
		 Icon = new GIcon();
		 Icon.image = image_url;
		 Icon.iconSize = new GSize(w,h);
		
		 Icon.iconAnchor = new GPoint(Math.floor(w/2), h); //Change this to change the position of the anchor point, default is bottom middle
		 Icon.infoWindowAnchor = new GPoint(Math.floor(w/2), 0); 
		 Icon.infoShadowAnchor = new GPoint(Math.floor(w/2), h);
		 Icon.printImage = image_url;
		 Icon.mozPrintImage = image_url;
		 Icons.push(Icon);
}
newIcon("custom_pointer_icon.gif",35,50);

///////////////////////////////////////////
//	addEvent() 
//	Browser independent Add event listener (Used for body onload)
//

function addEvent(obj, evType, fn){ 		
	 if (obj.addEventListener){ 
	   	obj.addEventListener(evType, fn, false); 
	   	return true; 
	 } else if (obj.attachEvent){ 
	  	var r = obj.attachEvent("on"+evType, fn); 
	  	return r; 
	 } else { 
	   	return false; 
	 } 
}
addEvent(window, 'load', gMapLoad);
addEvent(window, 'unload', GUnload);

var default_loc_string = Location_String;		//Default Position
var default_long = 	0;
var default_lat = 	0;
