/****
Author:         Andrei Vais
Date:           07/01/2009
Filename:       directions.js
Description:    Hooks into the Google Maps API to display directions to Majestic House.
****/


var map;
var localSearch = new GlocalSearch();
var icon = new GIcon();
var gdir;
var geocoder = null;
var addressMarker;
        
icon.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";
icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
icon.iconSize = new GSize(12, 20);
icon.shadowSize = new GSize(22, 20);
icon.iconAnchor = new GPoint(6, 20);


function usePointFromPostcode(postcode, callbackFunction) {
	
	//alert('usePointFromPostcode');
    localSearch.setSearchCompleteCallback(null, 
        function() {
			
	        if (localSearch.results[0])
	        {		
		        var resultLat = localSearch.results[0].lat;
		        var resultLng = localSearch.results[0].lng;
		        var point = new GLatLng(resultLat,resultLng);
		        //alert("point:" + resultLat + " :: " + resultLng);
		        //alert(point);
    
                var toLatLng = "53.6513,-1.7819";
                var fromLatLng = resultLat + "," + resultLng;
                //alert(fromLatLng);
                //alert(toLatLng);
    	        
                setDirections(fromLatLng, toLatLng, "en");
                
		        callbackFunction(point);
	        }else{
		        //alert("Postcode not found!");
		        mapLoad();
	        }
        });	
    //alert("postcode: " + postcode);
    //localSearch.execute(postcode + ", UK");
    localSearch.execute(postcode);
    return false;
}

function showPointLatLng(point)
{
   // alert("Latitude: " + point.lat() + "\nLongitude: " + point.lng());
    var marker = new GMarker(point,icon);
    map.addOverlay(marker);
    map.setCenter(point, 12);
}

function mapLoad() {
    if (GBrowserIsCompatible()) {
    
        map = new GMap2(document.getElementById("locationmap"));
		gdir = new GDirections(map, document.getElementById("directionsmap"));
        
        var point = new GLatLng(53.6513,-1.7819);
		var marker = new GMarker(point,icon);
		
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(point, 12, G_DEFAULT_MAP_TYPES[0]);        		
        map.addOverlay(marker);
		
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
    }
}

    
function setDirections(fromLatLng, toLatLng, locale)
{
    document.getElementById("directionstitle").style.visibility = "visible";
    document.getElementById("directionsmap").style.visibility = "visible";
    //alert("fromAddress: " + fromLatLng + " toAddress: " + toLatLng + " locale: " + locale);
    gdir.load(fromLatLng + " to: " + toLatLng,
    {
       "locale": locale
    });
    
    GMap2.removeOverlay();
}


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_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: " + 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("Sorry the postcode provided could not be found.");
   }
}

function onGDirectionsLoad()
{ 
  // Use this function to access information about the latest load()
  // results.

  // e.g.
  // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
  // and yada yada yada...
}

function initializeDirectionsForm()
{
    //check if the form exist
    var directionsForm = document.getElementById("directions");
    var fromPostcode = document.getElementById("postcode");		
	if(directionsForm)
	{
	    directionsForm.action = "#";
	    directionsForm.onsubmit = function()
        {
            usePointFromPostcode(fromPostcode.value, showPointLatLng);
            return false;
        }
	}
}

addLoadEvent(initializeDirectionsForm);
addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);