// JavaScript Document

//VARS
//===================================
var map;
var dirs;
//var geocoder;
var localSearch = new GlocalSearch();

var amase_icon = new GIcon( G_DEFAULT_ICON, "pp_amase.png");
amase_icon.iconSize = new GSize( 32, 51 );
amase_icon.iconAnchor = new GPoint( 14, 48 );
amase_icon.infoWindowAnchor = new GPoint( 16, 0 );

var house_icon = new GIcon( G_DEFAULT_ICON, "pp_house.png");
house_icon.iconSize = new GSize( 36, 50 );
house_icon.iconAnchor = new GPoint( 17, 47 );




var step_marker;// = new GMarker( get_Amase_LatLong(), marker_icon );
var housemarker;


function init_map() 
{
  if (GBrowserIsCompatible()) 
  {
  	//create a new map variable
	map = new GMap2(document.getElementById("map"));
	
	//add a zoom in/out and move-the-map-around control
	map.addControl(new GLargeMapControl());

	//add a change-the-map-to-map/satellite/hybrid control
//	map.addControl(new GMapTypeControl());
	
	//centre the map on some co-ordinates (in this case, Whitegoods in Guildford
	map.setCenter( get_Amase_LatLong(), 15);

//	addMarker( get_Amase_LatLong(), "<div style='color:#000000'>Amase<br>Kickboxing and<br>Circuit Training classes</div>" );
	addMarker( get_Amase_LatLong(), "Amase<br>Kickboxing and<br>Circuit Training classes" );
		
//	geocoder = new GClientGeocoder();
//	localsearch = new google.maps.LocalSearch();
//	map.addControl( localsearch );

	//create a new directions variable to get our directions.
	dirs = new GDirections(map);
	
	//cater for the possibility that the directions fail
	GEvent.addListener(dirs,"error", directions_failed);
	
//	step_marker = new GMarker( get_Amase_LatLong(), marker_icon );
	step_marker = new GMarker( get_Amase_LatLong() );
	map.addOverlay(step_marker);
	step_marker.hide();

  }
}

function get_Amase_LatLong()
{
	var point = new GLatLng(51.24672597710759, -0.5385982990264893);
	return point;
}

function addMarker( point, html )
{
	var marker = new GMarker(point, amase_icon);
	
	GEvent.addListener(marker, "click", function(){marker.openInfoWindowHtml(html);} );
	map.addOverlay(marker);
	marker.openInfoWindowHtml(html);
}

function show_directions( address )
{
	localSearch.setSearchCompleteCallback(null, plant_marker);	
	localSearch.execute(address + ", UK");
}

function plant_marker()
{
	if (localSearch.results[0])
	{		
		var resultLat = localSearch.results[0].lat;
		var resultLng = localSearch.results[0].lng;
		var point = new GLatLng(resultLat,resultLng);
//		addMarker( point, "This is your address" );
		plot_journey( point );

	}
	else
	{
		alert("Address not found!");
	}
}

function plot_journey( startPoint )
{
	var Amaselocation = get_Amase_LatLong();

//	alert("plot_journey! YAY!");

	dirs.load("from: " + startPoint.lat() +", " + startPoint.lng() + " to: " + Amaselocation.lat() + ", " + Amaselocation.lng() ,{getSteps:true} );


	//get the directions
//	dirs.load("from: Blackpool to: Preston to: Blackburn", {getSteps:true});
//	dirs.load("from: Blackpool to: Preston to: Blackburn", {getSteps:true});
	
	//add a listener to pick up when Googlemaps returns with our directions.
	GEvent.addListener(dirs,"load", process_directions);
}

function process_directions()
{
	// ========== launch the custom Panel creator a millisecond after the GDirections finishes loading ==========
	// == The delay is required in case we rely on GDirections to perform the initial setCenter ==
	setTimeout('display_directions(document.getElementById("directions"))', 1);
}

function directions_failed()
{
   if (dirs.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: " + dirs.getStatus().code);
   else if (dirs.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: " + dirs.getStatus().code);
   
   else if (dirs.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: " + dirs.getStatus().code);

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

   else if (dirs.getStatus().code == G_GEO_BAD_REQUEST)
	 alert("A directions request could not be successfully parsed.\n Error code: " + dirs.getStatus().code);
	
   else alert("An unknown error occurred.");
}

function display_directions(div)
{
	var content = "";
	
	
	//run through the steps returned by the direction request
	for (var i=0; i<dirs.getNumRoutes(); i++) 
	{
	
		var route = dirs.getRoute(i);
		var geocode = route.getStartGeocode();
		var point = route.getStep(0).getLatLng();
		
		//for the start icon, we will remove the existing one on the map and display our custom one in its stead
		if ( i==0 )
		{
//alert( "changing icons!");		
			map.removeOverlay(dirs.getMarker(i));

			if ( housemarker )
				map.removeOverlay(housemarker);
			
			
			housemarker = new GMarker( point, house_icon);
			map.addOverlay(housemarker);
		}
		
		
		content += add_point_desc( point, geocode.address, "From :" );
		
		//add the distance and time:
		content += "<table><tr><td>" + "Distance approx :" + route.getDistance().html + "</td></tr></table>";;
		content += "<table><tr><td>" + "about " + route.getDuration().html + "</td></tr></table>";;

		content += '<table>';
		for (var j=0; j<route.getNumSteps(); j++) 
		{
			//just do the steps for the time being.
			var step = route.getStep(j);
			content += add_step_desc(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html, i, j );
		}
		content += '</table>';
	}
	
	var geocode = route.getEndGeocode();
	var point = route.getEndLatLng();
//	content += add_point_desc( point, geocode.address, "Arrive At :" );
	content += "<table><tr><td>";
	content += "Arrive at: St Peter's School, Merrow"
	content += "</td></tr></table>";
	
	
	//slap the entire list of directions into the div.
	div.innerHTML = content;
}

function add_point_desc( point, address, extra_bit )
{
	var content = "";
	
	content += "<table><tr>";
	
	content += "<td>" + extra_bit + address + "</td>";

	content += "</tr></table>";
	
	return content;
}

function add_step_desc( point, num, description, dist, route_num, step_num )
{

//	map.setCenter( point );

//	var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
//	var target = '"' + map.setCenter( point ) +'"';
//	var target = '"'+"map"+".panTo(new GLatLng("+point.toUrlValue(6)+"))" +'"';
	var target = '"'+"reposition_step_marker("+route_num+","+step_num+")" +'"';
//	var target = "reposition_step_marker("+point.toUrlValue(6)+")";

	var content = "";
	
	content += '<tr style="cursor: pointer;" onclick='+target+'>';
	
	content += "<td>" + num + "</td>";
	content += "<td>" + description + "</td>";
	content += "<td>" + dist + "</td>";

	content += "</tr>";
	
	return content;
}

function reposition_step_marker( route_num, step_num )
{
	//get the necessary info out of the directions array.
	var route = dirs.getRoute(route_num);
	var step = route.getStep(step_num);
	
	var point = step.getLatLng();
	
	

//	map.removeOverlay(step_marker);
//	step_marker.setpoint( new GLatLng(point.toUrlValue(6)) );

	step_marker.setPoint( point );

	if ( step_marker.isHidden() )
		step_marker.show();

	map.panTo(point);

}

