// The global variable containing the clinic_obj
var global_location_obj;
var global_gdir;
var map;	  

// Load the google map

function gmap_load() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));    

		// Add pan and zoom controls
		map.addControl(new GLargeMapControl());	// Slider
		map.addControl(new GMapTypeControl());      

		// Set map center on Saint Louis, MO
		var pt = new GLatLng(38.66085,-90.197754);
		map.setCenter(pt, 10);

		// Load the various locations into the map        
		load_locations(map);            

		// Prepare the gdir object
		var directions_panel = document.getElementById("directions_panel");
	 	global_gdir = new GDirections(map, directions_panel);
	 	
		GEvent.addListener(global_gdir, "error", handleErrors);
	}
	return false;

}	

/* Function borrowed from http://www.google.com/apis/maps/documentation/directionsAdvanced.html */
function handleErrors(){
	if (global_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: " + global_gdir.getStatus().code);

	else if (global_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 (global_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: " + global_gdir.getStatus().code);

	else if (global_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: " + global_gdir.getStatus().code);

	else if (global_gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + globa_gdir.getStatus().code);  

	else
		alert("An unknown error occurred.");
		  
	return;
}

  

function load_locations(map) { 	
	// Add each location to the map
	// Requires you to declare a JSON object called locn_objs
	var i;

	for (i = 0; i < location_objs.length; ++i) {
	 	var location_obj = location_objs[i];
	 	
		if (location_obj.latitude && location_obj.longitude) {
			var pt = new GLatLng(location_obj.latitude, location_obj.longitude);
			var gmarker = new GMarker(pt, {clickable: true});					

			var handler_obj = new map_obj_handler(location_obj, gmarker);

			// Allows you to click and see info
			map.addOverlay(gmarker);
			GEvent.addListener(
				gmarker,
				"click",
				handler_obj.handler
			);
			
			// Create a link on the page that will open this marker up
			var page_link_div = document.getElementById("location" + i);
			if (page_link_div) {
				var anchor = document.createElement("a");
				anchor.onclick = handler_obj.handler;
				anchor.href = "#map";
				anchor.innerHTML = "Show on map";
				var div = document.createElement("div");
				div.appendChild(anchor);
				page_link_div.appendChild(div);
			}
		}
	}
	return;
}

// Object to create persistence in handlers
function map_obj_handler(location_obj, gmarker) {
	this.location_obj = location_obj;
	this.gmarker = gmarker;
	
	this.handler = function() {
		// Save this marker as the clinic you're looking at
		global_location_obj = location_obj;
		gmarker.openInfoWindowHtml(generate_select_direction_window());
		return;			
	}
}

// Convert the location_object's address to something useful for GMaps	
function toGAddress(location_obj) {
	return location_obj.address + ", " + location_obj.city + ", " + location_obj.state; 
}

// Convert the location_object's data into something printable by HTML
function toHTML(location_obj) {
 	var string = new String();

 	if (location_obj.website) {
		string += "<span style=\"font-family: Arial; font-weight: bold\">";
		string += "<a href=\"" + location_obj.website + "\" target=\"_blank\">";
		string += location_obj.name + "</a></span><br />\n";
	}
	else {
		string += "<span style=\"font-family: Arial; font-weight: bold\">" + location_obj.name + "</span><br />\n";	
	}
	string += location_obj.address + "<br />\n";	
	string += location_obj.city + ", " + location_obj.state + "<br />\n";
	string += location_obj.phone;
	return string;		
}

function inputDirectionsTo(gAddress) { 
	// First get access to the content of the menu
 	var info_window = map.getInfoWindow();
 	var info_window_locn = info_window.getPoint();

	// Create the new menu
	var fromClickAction = "inputDirectionsFrom('" + gAddress + "');";
	var dir_string = "<span style=\"font-weight: bold;\">Get directions: </span>";
	dir_string += "To here - ";	
	dir_string += "<a href=\"javascript:" + fromClickAction + "\" id=\"fromhere\" >From here</a><br />\n";
	dir_string += "<span style=\"font-family:Arial; color: #888; font-size: 8pt;\">Start address</span><br />\n";
	dir_string += "<form>\n";
	dir_string += "<input type=\"text\" size=\"50\" id=\"input_address\"> <input type=\"submit\" value=\"Go\" onclick=\"getDirectionsTo(document.getElementById('input_address').value); return false;\"><br />\n";
	dir_string += "</form>";
	
	// Have a back button that just returns to the original state of the address
	dir_string += "<span style=\"font-size: 8pt;\"><a href=\"javascript:restore_direction_menu();\">&laquo;Back</a></span>";

	var big_string = toHTML(global_location_obj) + "<br /><br />" + dir_string  + "<br /><br /><br />";

	map.openInfoWindowHtml(info_window_locn, big_string);
	return;
}

function inputDirectionsFrom(gAddress) {
 	// First get access to the content of the menu 	
 	var info_window = map.getInfoWindow();

 	var info_window_locn = info_window.getPoint();

	// Create the new menu
	var toClickAction = "inputDirectionsTo('" + gAddress + "');";
	var dir_string = "<span style=\"font-weight: bold;\">Get directions: </span>";
	dir_string += "<a href=\"javascript:" + toClickAction + "\" id=\"tohere\">To here</a> -\n";
	dir_string += "From here <br/>";
	dir_string += "<span style=\"font-family:Arial; color: #888; font-size: 8pt;\">End address</span><br />\n";
	dir_string += "<form>\n";
	dir_string += "<input type=\"text\" size=\"50\" id=\"input_address\"> <input id=\"start_address\" type=\"submit\" value=\"Go\" onclick=\"getDirectionsFrom(document.getElementById('input_address').value); return false;\"><br />\n";
	dir_string += "</form>\n";

	// Have a back button that just returns to the original state of the address
	dir_string += "<span style=\"font-size: 8pt;\"><a href=\"javascript:restore_direction_menu();\">&laquo;Back</a></span>";

	var big_string = toHTML(global_location_obj) + "<br /><br />" + dir_string + "<br /><br /><br />";
	map.openInfoWindowHtml(info_window_locn, big_string);
 	return;
}

function getDirectionsTo(fromAddress) {
 	var query_string = "from: " + fromAddress + " to:" + toGAddress(global_location_obj); 	
	global_gdir.load(query_string);
	map.closeInfoWindow();
	return;		
}

function getDirectionsFrom(toAddress) {
 	var query_string = "from: " + toGAddres(global_location_obj) + " to:" + toAddress;
	global_gdir.load(query_string);
	map.closeInfoWindow();
	return;
}

// Restores the window_menu	to selecting directions (called by back button)
function restore_direction_menu() {
 	var info_window = map.getInfoWindow();
 	var info_window_locn = info_window.getPoint();
	map.openInfoWindowHtml(info_window_locn, generate_select_direction_window());
	return;
}

function generate_select_direction_window() {
		//Create the area as a DOM node for future access
		var caption_string = "<div id='address_html'>\n" + toHTML(global_location_obj) + "</div>\n";

		// Add directions			
		var toClickAction = "inputDirectionsTo('" + toGAddress(global_location_obj) + "'); return false;";
		var fromClickAction = "inputDirectionsFrom('" + toGAddress(global_location_obj) + "'); return false;";
		caption_string += "<div id='directions_menu'>"
		caption_string += "<span style=\"font-weight: bold;\">Get directions: </span>";
		caption_string += "<a href=\"#\" id=\"tohere\" onclick=\"" + toClickAction + "\">To here</a> - ";
		caption_string += "<a href=\"#\" id=\"fromhere\" onclick=\"" + fromClickAction + "\">From here</a>\n";
		caption_string += "</div><br />";
		
		return caption_string;
}