//Magic numbers and other global vars
//lengthy styles broken out for easy modifcation and code readability
var balloonTitleStyle = 'class="content_module_header";' +
	'border-bottom:none;width:400px;padding:3px;font:Arial, Helvetica, sans-serif;font-size:14px;' + 
	'font-weight:bold;color:#fff;"'; //style of div which is the "header/title" of the balloon
var balloonInfoStyle = 'style="line-height:18px;margin-bottom:5px;border: 1px solid #ffffff;' +
	'border-top:none; width:400px;padding:3px;' +
	'overflow:auto;" class="BG-color-bg-events02"' //style of balloons info div
var imageStyle = 'style="float:left;width:180px;margin-right:1em;"'; //style of point of interest image in balloon
var directionalInputStyle = 'style="border-top:1px solid #999;clear:both;"';
//HTML For the directional options div if the "to" or "from" options are selected.
var toHTML = '<center>Directions: <b>To here - <a href="javascript:gohere(\'from\')">From here</a></b></center>' +
	'<div style="margin-top:5px;">Enter Start Address, City and State: </div><div style="margin-top:5px;">' +
	'<input type="text" size=40 MAXLENGTH=60 name="userAddy" id="userAddy" value="" />' +
	'<INPUT value="Get Directions" TYPE="BUTTON" onclick="javascript:getDirections(\'to\');"></div>';
var fromHTML = '<center>Directions: <b><a id=_to href="javascript:gohere(\'to\')">To here</a> - ' + 
	'From here</b></center><div style="margin-top:5px;">Enter End Address, City and State: </div>' +
	'<div style="margin-top:5px;"><input type="text" SIZE=40 MAXLENGTH=60 name="userAddy" id="userAddy" value="" />' +
	'<INPUT value="Get Directions" TYPE="BUTTON" onclick="javascript:getDirections(\'from\');"></div>';

var toOrFrom = "to";

var map;  //google map
var marker; //"pin" marker on map
var gdir; //directions (google object)

// === Array for decoding the directional failure codes ===
var reasons=[];
reasons[G_GEO_SUCCESS]            = "Success";
reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";


function loadGMap() {
	//Main 'kick-off' function to build google map (directional)
	//Step 1, build Google map object and configure it
	//Step 2, build Google directions Object
	//Step 3, build functionality for the directional objects error even to handle directional errors
	//Step 4, build functionality for the directional object to remove the auto-made markers for directional route
	//Step 5, build marker for our point of interest and it's info baloon
	
	//Step 1
	gmapOptions = {mapTypes: [G_HYBRID_MAP,G_PHYSICAL_MAP,G_NORMAL_MAP]};
	//create a new GMap object, bind it to page's "map" element and use the options we defined on the line above
	map = new GMap2(document.getElementById("map"),gmapOptions);
	map.enableScrollWheelZoom();
	map.addControl(new GLargeMapControl()); //panning/zooming control in upper left
	map.addControl(new GMapTypeControl()); //maptype switcher buttons in upper right
	map.setCenter(new GLatLng(intLatitude, intLongitude), intZoom);	//center our map on our point of interest and zoom in
	
	//Step 2
	//create a new GDirections object, associate it with our map and bind the directions list to the HTML element "directions"
	gdir = new GDirections(map, document.getElementById("directions"));

	//Step 3 === catch Directions errors ===
	GEvent.addListener(gdir, "error", function() {
		var code = gdir.getStatus().code; //get the code representing the error
		var reason="Code "+code;
		//if the code is one we defined in the reasons array use the friendly message
		//otherwise just leave the error code
		if (reasons[code]) { reason = reasons[code]; }
		alert("Failed to obtain directions, "+reason); //alert user of error
		GEvent.trigger(marker, "click"); //reset map by triggering the marker's click event (recenter, zoom, clear direcations etc)
	});
	//Step 4
	//Normally you'd think this method should fire on the open event of the direction object, but the markers
	//don't actualy get put on the map until the overlay event, so we can't remove (hide) them until then
	GEvent.addListener(gdir, "addoverlay", function() {
		if(toOrFrom == "to") {
			gdir.getMarker(1).hide();
		} else {
			gdir.getMarker(0).hide();
		}
		
	});
	
	//Step 5
	marker = new GMarker(map.getCenter()); //simple map, center and marker have the same lat-long
	map.addOverlay(marker); //add the newly created marker to the map
	//build the contents of the balloon
	var title = strEntity;
	var info = strDesc;
	var image = "<img src='" + strImageSrc + "' width='100%'>";
	var html = '<div id="balloon"><div ' + balloonTitleStyle + '><h4>' + title + '</h4></div><div ' + balloonInfoStyle + '><div ' + 
		imageStyle + '>' + image + '<div><font size="-1">' + strAddress + "<br/>" + strCityState + strZip + "<br/>" + strPhoneNbr + 
		'</font></div></div>' + info + '<div id="directionInput" ' + directionalInputStyle + 
		'><center>Directions: <b><a id=_to href="javascript:gohere(\'to\')">To here</a> - <a href="javascript:gohere(\'from\')">' +
		'From here</a></b></center></div></div></div>';
	//any time the user click on the marker (or the code wants to 'reset' the map, we should clear directions, re-center,
	//zoom and pop-open the default bubble containing the HTML defined on the line above
	GEvent.addListener(marker, "click", function () {
		//clear any directions which may currently be displayed
		gdir.clear();
		//open the "ballon" and fill it with the html we built above
		marker.openInfoWindowHtml(html);
		//set the center of the map to the marker
		map.setCenter(marker.getLatLng(),intZoom);
	});
	//trigger the marker's click event to open the window now
	GEvent.trigger(marker, "click");
}

function getDirections(direction) {
	//When this function is called we "load" directions using the directions object between the point of interest's
	//address and the address the user has supplied. If they want directions "to" the POI then we do directions from
	//their address to the POI. If they want directions "from" the POI then we do directions from POI to their address
	if(direction == "to") {
		fromAddress = document.getElementById("userAddy").value;
		toAddress = strAddress + " " +strCityState + strZip;
		toOrFrom = "to";
	} else if(direction == "from") {
		fromAddress = strAddress + " " + strCityState + strZip;
		toAddress = document.getElementById("userAddy").value;
		toOrFrom = "from";
	}
	//hide the balloon when in directions mode
	var w = map.getInfoWindow();
	w.hide();
	//load directions object.
	gdir.load("from: " + fromAddress +" to: " + toAddress);
}


function gohere(tofrom) {
	//This function sets the directional input element to contain the "to" or "from" form
	if(tofrom == "to") { 
		document.getElementById("directionInput").innerHTML = toHTML;
	} else if (tofrom == "from") {
		document.getElementById("directionInput").innerHTML = fromHTML;
	}
	//by re-opening the infowindow with the same content that it already has the balloon is re-sized to fit the
	//new "bigger" content (otherwise the content falls out of the bottom of the balloon
	marker.openInfoWindow(document.getElementById("balloon"));
	//Here I try to set focus to the text input control, but I can't get it to work :(
	document.all('userAddy').focus();
}

