// JavaScript Document

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

var wg_icon = new GIcon( G_DEFAULT_ICON, 'pp_wg.png');
wg_icon.iconSize = new GSize( 36, 47 );
wg_icon.iconAnchor = new GPoint( 17, 43 );
wg_icon.infoWindowAnchor = new GPoint( 18, 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 );
house_icon.infoWindowAnchor = new GPoint( 18, 0 );

var whitegoods_latlang = new GLatLng(51.19602652959574, -0.6049132347106934);


var step_marker;// = new GMarker( get_WG_LatLong(), 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, Whitegoods in Guildford
	map.setCenter( get_WG_LatLong(), 15);

	addMarker( get_WG_LatLong(), "<img src=\"images/maplogo.gif\"><br><div class=\"inkre tefs\">9-9a Farncombe Street<br>Farncombe GU7 3BA</div>" );
		
//	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_WG_LatLong(), marker_icon );
	step_marker = new GMarker( get_WG_LatLong() );
	map.addOverlay(step_marker);
	step_marker.hide();

  }
}

function get_WG_LatLong()
{
	var point = new GLatLng(51.19602652959574, -0.6049132347106934);
	return point;
}

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

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 WGlocation = get_WG_LatLong();

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

	dirs.load("from: " + startPoint.lat() +", " + startPoint.lng() + " to: " + WGlocation.lat() + ", " + WGlocation.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 inkre\">" + "From: "+ geocode.address + "</div>";
//		content += "<div class=\"flr inkbl txtr\">about " + route.getDuration().html + "</div>";
		content += "<div class=\"inkbl txtr fivel\"> " + "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=\"inkre\">";
	content += "Arrive at: Whitegoods, 9-9a Farncombe Street, Farncombe"
	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);

}


//DURATION LOOKUP FUNCTIONS
//=========================
function get_address_distance_and_time( postcode )
{
//alert("get_address_distance_and_time!");
	dirs = new GDirections();
	
	GEvent.addListener(dirs,"error", delivery_redirect);

	house_postcode = postcode;

	localSearch.setSearchCompleteCallback(null, process_target_callback);	
	localSearch.execute(postcode + ", UK");
	
	
}

function get_address_distance_time_and_latlang( postcode )
{
//alert("get_address_distance_time_and_latlang!");
//alert("poscode = "+postcode);
	dirs = new GDirections();
	
	GEvent.addListener(dirs, 'error', delivery_redirect);

	house_postcode = postcode;

	localSearch.setSearchCompleteCallback(null, process_target_callback_with_latlang);	
	localSearch.execute(postcode + ", UK");
}


/*function find_target_from_postcode( postcode )
{
}
*/
function process_target_callback()
{
	process_target();
}


function process_target_callback_with_latlang()
{
//alert("process_target_callback_with_latlang!");
	process_target(true );
}

function process_target( inc_latlang )
{
//alert("process_target!");
	if (localSearch.results[0])
	{		
		var resultLat = localSearch.results[0].lat;
		var resultLng = localSearch.results[0].lng;
		house_latlng = new GLatLng( resultLat,resultLng );

		calc_duration( house_latlng, inc_latlang );
	}
	else
	{
//		alert("Address not found!");
		delivery_redirect();
	}
}


function calc_duration( target_point, inc_latlang )
{
//alert("calc_duration!");
	dirs.load("from: " + whitegoods_latlang.lat() +", " + whitegoods_latlang.lng() + " to: " + target_point.lat() + ", " + target_point.lng() ,{getSteps:true} );

	if ( inc_latlang == true )
		GEvent.addListener(dirs,"load", process_directions_callback_inc_latlang );
	else
		GEvent.addListener(dirs,"load", process_directions_callback );
}

function process_directions_callback_inc_latlang()
{
//alert("process_directions_callback_inc_latlang!");
	process_directions(true);
}

function process_directions_callback( )
{
	process_directions();
}

function process_directions( inc_latlang )
{
//alert("process_directions!");

	//once we get these, we move on to another page.

	var route = dirs.getRoute(0);

	document.getElementById('pigeonhole_house_postcode').value = house_postcode;
	document.getElementById('pigeonhole_distance_meters').value = route.getDistance().meters;
	document.getElementById('pigeonhole_time_seconds').value = route.getDuration().seconds;

//alert("pigeonhole_time_seconds!" + document.getElementById("pigeonhole_time_seconds").value);
	
	if ( inc_latlang == true )
	{
//alert("inc_latlang!" + house_latlng.lat());
		document.getElementById('pigeonhole_house_lat').value = house_latlng.lat();
		document.getElementById('pigeonhole_house_lng').value = house_latlng.lng();
	}

//	alert( document.getElementById("pigeonhole_house_lng").value );
	
	document.getElementById('carrierpigeon').submit();

//	alert("carrierpigeon!");

}

function delivery_redirect()
{	
//alert("delivery_redirect!");
	document.getElementById('duff_postcode').submit();
}

function display_directions_results()
{
//	alert("display_directions_results!");

	var div = document.getElementById('directions');

	div.innerHTML = display_info;
}