/**
 * @author Chris Donalds
 * ---------------------------------------------
 * Sample Calls
 * 
 *  --- CREATING NEW MAPS ---
 *  
 *  <div id="mapbox"></div>		// note: do not change the id "mapbox". it is a reusable placeholder div
 *  <script type="text/javascript" language="JavaScript">
 * 		updateMap(lat, lon, 'balloontag', 'options', zoom, maptype, 'listenfor');
 *  </script>
 *  
 *  Prepares a new map and centers the initial point
 * 	where:
 * 		- lat = latitude of center point (float)
 * 		- lon = longitude of center point (float)
 * 		- balloontag = HTML content displayed in balloon popup (string)
 * 		- options = optional parameters (string)
 * 		- zoom = zoom factor (integer [0 - 13])
 * 		- maptype = maptype value (constant = G_HYBRID_MAP, G_NORMAL_MAP, G_SATELLITE_MAP)
 * 		- listenfor = event to listen for (string = clickaddpoint, zoom_changed)
 * 
 *  --- CREATING NEW POINT ---
 *  
 *  <script type="text/javascript" language="JavaScript">
 *  	createMarker(point, 'html', 'option');
 *  </script>
 *  
 *  Creates a new map point with options
 *  where:
 *  	- point = GMap point (object [new GLatLng(lat, lon)])
 *  	- html = HTML content placed in openInfoWindowHtml popup balloon (string)
 *  	- option = various point options (string = null, click, draggable)
 *  
 *  --- GETTING ROUTE DIRECTIONS AND DRAWING POLYLINE ---
 *  
 *  call to:
 *  	javascript:getDirections('route-div', 'searchfrom-field', 'searchto-field', 'locale', travelmode, avoidhwys)
 *  
 *  where:
 *  	locale = en_US, en_CA, fr_CA... (string)
 *  	travelmode = type of travel (constant = G_TRAVEL_MODE_DRIVING, G_TRAVEL_MODE_WALKING)
 *  	avoidhwys = true to avoid highways
 */

var map = null;
var mapobj = null;
var gdir;
var geocoder = null;
var addressMarker;

function createMarker(point, html, option) {
	if (option == '' || option == 'click') {
		var marker = new GMarker(point);
		if (html != '') {
			marker.openInfoWindowHtml(html);
			GEvent.addListener(marker, "click", function(){				
			});
		}
	}else if (option == 'draggable'){
		var marker = new GMarker(point, {draggable: true});
		marker.enableDragging();				
		GEvent.addListener(marker, "drag", function(){
			document.getElementById("latlon").value = marker.getPoint().toUrlValue();
		});
	}
	return marker;
}

function updateMap(latitude, longitude, balloontag, options, zoom, maptype, listenfor){
    if (GBrowserIsCompatible()) {
		//create map
		document.getElementById("mapbox").style.display = "block";
		mapobj = document.getElementById("mapbox");
		map = new GMap(mapobj);
		if(zoom == '' || parseInt(zoom) == 0 || isNaN(zoom)) zoom = 11;
		map.setCenter(new GLatLng(latitude, longitude), zoom);

		//change maptype
		if(maptype != "") map.setMapType(maptype);
					
		//add controls
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		
		//add center point
		var point = new GLatLng(latitude, longitude);
		if (balloontag != "") {
			var marker = createMarker(point, '<div style="width:150px; height: 20px;">' + balloontag + '<\/div>', '');
		}else if (options != "") {
			var marker = createMarker(point, '', options);
		}else{
			var marker = createMarker(point, '', '');
		}
		map.addOverlay(marker);
		
		//handle map object listener
		if (listenfor.indexOf('clickaddpoint')>=0) {
			GEvent.addListener(map, "click", function(overlay, latlng){
				if (latlng) {
					//user clicked on map, get latlng value from point
					coords = latlng.toString();
					var coord = coords.split(", ");
					coord[0] = coord[0].substr(1);
					coord[1] = coord[1].substr(0, coord[0].length - 1);
					//add new point and pass options to it
					var point = new GLatLng(coord[0], coord[1]);
					var marker = createMarker(point, '', options)
					map.addOverlay(marker);
				}
			});
		}
		if (listenfor.indexOf('zoom_changed') >= 0) {
			GEvent.addListener(map, "zoomend", function(){
				document.getElementById("zoom").value = map.getZoom();
			});
		}
	}else{
		alert("Sorry, the Google Maps API is not compatible with your browser.");
	}
}	

function getDirections(divbox, fromfield, tofield, locale, travelmode, avoidhwys) {
	gDivBox = document.getElementById(divbox);
	gFrom = document.getElementById(fromfield);
	gTo = document.getElementById(tofield);
	if (gDivBox && gFrom && gTo) {
		if (locale == null)	locale = "en_US";
		if (travelmode == null)	travelmode = G_TRAVEL_MODE_DRIVING;
		gDivBox.innerHTML = "";
		gdir = new GDirections(map, gDivBox);
		gdir.load("from: " + gFrom.value + " to: " + gTo.value, {
			"locale": locale
		}, {
			"travelMode": travelmode
		});
	}
}

function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("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: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);	
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("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: " + gdir.getStatus().code);	
	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);	
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);	
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);	
	else alert("An unknown error occurred.");
}

function onGDirectionsLoad(){ 
	// Use this function to access information about the latest load()
	// results.
	
	// e.g.
	// document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	// and yada yada yada...
}

