// JavaScript Document

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

//var home_icon = new GIcon( G_DEFAULT_ICON, 'pp_wg.png');
var home_icon = new GIcon( G_DEFAULT_ICON );
//home_icon.iconSize = new GSize( 36, 47 );
//home_icon.iconAnchor = new GPoint( 17, 43 );
//home_icon.infoWindowAnchor = new GPoint( 18, 0 );

var house_icon = new GIcon( G_DEFAULT_ICON );
//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 );
//house_icon.infoWindowAnchor = new GPoint( 18, 0 );

var home_iconsrc = "images/iccmaplogo.gif";
//var home_latlang = new GLatLng(51.564319379865324, -0.1329946517944336);
var home_address_inline = "Islington Carers Centre, Unit 1, 53 Hargrave Road,  London N19 5SH";
var home_address = "Islington Carers Centre<br/>Unit 1, 53 Hargrave Road<br/>London N19 5SH";

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

var house_postcode;
var house_latlng;



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, the home co-ordinates
	map.setCenter( get_Home_LatLong(), 15);


	marker_msg = "<div class=\"fll maptext\" style=\"margin-left: 3px; color:#4E4EFF; \" >" + home_address + "</div>";
	if ( home_iconsrc )
		marker_msg = "<div class=\"cntr\"><img src=\"" + home_iconsrc + "\"></div>";
//		marker_msg = "<div class=\"fll\"><img src=\"" + home_iconsrc + "\"></div>" + marker_msg;

//	addMarker( get_Home_LatLong(), "<img src=\"images/maplogo.gif\"><br><div class=\"inkre tefs\">" + home_address + "</div>" );
	this_marker = addMarker( get_Home_LatLong(), marker_msg );
		
//	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_Home_LatLong(), marker_icon );

//	step_marker = new GMarker( get_Home_LatLong() );
//	map.addOverlay(step_marker);
//	step_marker.hide();

	//pan to the home point, so it looks nice.
	map.panTo(get_Home_LatLong());
//	this_marker.click();

	this_marker.openInfoWindowHtml(marker_msg);


  }
}

function get_Home_LatLong()
{
	var point = new GLatLng(51.564319379865324, -0.1329946517944336);
	return point;
}

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

	return marker;
}

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

function plant_marker()
{
//alert("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 )
{
//alert("plot_journey!")
	var Homelocation = get_Home_LatLong();

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

	dirs.load("from: " + startPoint.lat() +", " + startPoint.lng() + " to: " + Homelocation.lat() + ", " + Homelocation.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_map_directions);
}

function process_map_directions()
{
//alert("process_map_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, "<span class=\"inkre\">From: "+geocode.address+"</span>" );
		//add the distance and time:
//		content += "<table style=\"width:600px\"><tr>";
		content += "<div class=\"\" style=\"width:600px\">";
		content += "<div class=\"fll \">" + "From: "+ geocode.address + "</div>";
//		content += "<div class=\"flr inkbl txtr\">about " + route.getDuration().html + "</div>";
		content += "<div class=\"inkbl txtr mgl5\"> " + "Distance approx " + route.getDistance().html + ", about " + route.getDuration().html +"</div>";
		content += "</div>";
		
//		content += "</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 );
//	content += "<table style=\"width:600px\"><tr><tr><td class=\"inkre\">";
	content += "<div class=\"\">";
	content += "Arrive at: " + home_address_inline;
	content += "</div>";
//	content += "</td></tr></table>";
	
	
	//slap the entire list of directions into the div.
	div.innerHTML = content;
}

function add_point_desc( point, address )
{
	var content = "";
	
	content += "<table style=\"width:600px\"><tr>";
	
	content += "<td style=\"width:100%\">" + 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>";

	content += "<div class=\"clr\" style=\"width:600px; cursor: pointer;\" onclick="+target+"\">";
	content += "<div class=\"fll\" style=\"width:30px\">" + num+ "</div>";
	content += "<div class=\"fll\" >" + description + "</div>";
	content += "<div class=\"flr\" style=\"width:50px\">" + dist + "</div>";
	content += "</div>";

	
	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);

}