var map;
var gdir;
var geocoder = null;
var addressMarker;

// Initialize google map object
function initialize() 
{
	if (GBrowserIsCompatible()) 
	{   
		//initialize map by giving Map Div id   
		map = new GMap2(document.getElementById("map_canvas"),
					{ size: new GSize(340,560) } ); //set the width & height of the Map here

		map.setUIToDefault();
		
		//initialize result container by using its Div id
		gdir = new GDirections(map, document.getElementById("directions"));
		
		//create event to load directions
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		
		//create event to handle errors
		GEvent.addListener(gdir, "error", handleErrors);
	}
}

// Use this function to set Waypoint
function setDirections() 
{
	//create waypoints array & fill it with all locations entered by user
	var waypoints = new Array();

	waypoints[0] = $("#fromAddress").val();
	waypoints[1] = $("#toAddress").val();
	var waypoints_counter=2;
  
	$('input[name="toWaypoints[]"]').each(function()
	{
		waypoints[waypoints_counter]=$(this).val();
		waypoints_counter++;
	});
	
	//this is the main google API function that generates the directions
	gdir.loadFromWaypoints(waypoints);
}

// Use this function to handle errors occured while processing API request
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_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.");
	
	$("#summary").html(""); //empty summary container which will be showing "Loading..." message at this point
}

// Use this function to access information about the latest load() results.
function onGDirectionsLoad()
{ 
	//get total distance
	var total_distance=gdir.getDistance().html;
	total_distance=total_distance.replace("mi", "miles"); //a short trick to display distance as "miles" & not as just "mi"
  
	//get total time
	var total_duration=gdir.getDuration().html;
	
	//display summary into summary block
	total_summary = '<strong>Total Distance : </strong>' + total_distance + " ( about " + total_duration + " )";
	total_summary += '<br/><a id="show_map" href="#" class="thickbox" onclick="open_map_thickbox();return false;">Show Map & Directions</a>';
	
	$("#summary").html(total_summary); //display summary containing Total distance & duration
}


//initialize API onload
$(function(){ initialize();  });

//close API onunload
$(window).unload( function () { GUnload(); } );

//calls to make after finishing complete page load
$(document).ready(function(){

	//configure autocomplete plugin options
	var autocomplete_options={
		mapkey: 'ABQIAAAA55X_3lzk3aRmhCIbDQP_mRRu7eCfY8nQW8KzqwC24ZMcqeC63hRNacB0znAo-sHyGwGlUH3beSuIsQ',  // Update your Google Map API Key here
		selectFirst: false,
		minChars: 3,
		cacheLength: 50,
		width: 300,
		scroll: true,
		scrollHeight: 330
	};

	//call autocomplete plugin
	$('#fromAddress').geo_autocomplete(new google.maps.Geocoder, autocomplete_options).result(function(_event, _data) {
		this.value=_data.formatted_address;
	});
	
	$('#toAddress').geo_autocomplete(new google.maps.Geocoder, autocomplete_options).result(function(_event, _data) {
		this.value=_data.formatted_address;
	});
	
	//call autocomplete plugin on a control that is not yet created using jquery "livequery" plugin
	$('#toWaypoints').livequery(function(){
		$(this).geo_autocomplete(new google.maps.Geocoder, autocomplete_options).result(function(_event, _data) {
			this.value=_data.formatted_address;
		});
	});
	
	//call on form submit
	$("#myForm").submit(function(){
		$("#summary").html("Loading...");
		setDirections(); 
		return false;
	});
	
});

// Add More waypoints
function add_waypoint()
{
	waypoint_tr = '<tr>';
	waypoint_tr += '	<td align="right">To :</td>';
	waypoint_tr += '	<td><input type="text" size="35" id="toWaypoints" name="toWaypoints[]" value="" /></td>';
	waypoint_tr += '	<td><a href="#" onclick="return add_waypoint();" id="show_map">Add</a>&nbsp;<a href="#" onclick="return remove_waypoint(this);">Remove</a></td>';
	waypoint_tr += '</tr>';
	
	$('#waypoints_table > tbody').append(waypoint_tr);
	
	return false;
}

// Remove waypoint
function remove_waypoint(obj)
{
	$(obj).parent().parent().remove();
	return false;
}

//open thickbox to show map
function open_map_thickbox()
{
	var url = "TB_inline?height=590&width=650&inlineId=map_area";
	tb_show("Map &amp; Waypoints", url, true);
}


