MMRouteSearch = function( icon, oResults ) {
    new MMElement( document.body );
    this.oResults = new MMElement( oResults );
    this.icon = icon ? icon : MM_DEFAULT_ICON;
    // add a MMRouteMarker css class to the icon
    this.icon.cssClass = ( typeof this.icon.cssClass != 'undefined' ) ? this.icon.cssClass + ' MMRouteMarker' : 'MMMarker MMRouteMarker';
    this.init();
}
MMRouteSearch.prototype.markers = [];
MMRouteSearch.prototype.results = [];

/**
* @method init Creates the route requester
**/
MMRouteSearch.prototype.init = function() {
    var me = this;
    // use MMFactory to create the requester in case we're using the VE integration
    this.requester = MMFactory.createRouteRequester( function() {
        me.routeCallback( arguments[0] );
    } );
}
/**
* @method addOverlay Adds the route polyline to the map
**/
MMRouteSearch.prototype.addOverlay = function( polyline ) {
    for ( var i = 0, j = polyline.length; i < j; i++ ) {
        this.polyline = polyline[i];
        Page.oMap.addOverlay( this.polyline );
    }
}
MMRouteSearch.prototype.addSteps = function( stages ) {
    var html, marker;
    // clear the results and markers arrays otherwise we won't reference them correctly
    this.results = [];
    this.markers = [];
    for ( var i = 0; i < stages.length; i++ ) {
        for ( var j = 0; j < stages[i].steps.length; j++ ) {
            html = this.getHtml( stages[i].steps[j], j );
            marker = Page.oMap.createMarker( stages[i].steps[j].start_point, { 'text' : j + 1, 'label' : j + 1, 'icon' : MM_DEFAULT_ICON } );
            marker.setInfoBoxContent( html.infobox );
            this.markers.push( marker );
            this.results.push( html.result );
        }
    }
    if ( typeof this.oResults != 'undefined' )
        this.oResults.innerHTML = this.results.join( '' );
}
MMRouteSearch.prototype.addEmissions = function() {
    var html = '<div class="MMRouteEmissions">';
    html += '<h4>C0<sub>2</sub> emissions:</h4>';
    html += '<span><strong>Avg. Diesel Car:&nbsp;</strong>' + this.route.emissions.average_diesel_car.value + '&nbsp;kgC0<sub>2</sub></span>';
    html += '<span><strong>Avg. Petrol Car:&nbsp;</strong>' + this.route.emissions.average_petrol_car.value + '&nbsp;kgC0<sub>2</sub></span>';
    html += '</div>';
    this.results.push( html );
}
/**
* @method getHtml Generates html for the infobox and results
* @returns Object
**/
MMRouteSearch.prototype.getHtml = function( step, id ) {
    var html = { result: null, infobox: null };
    var road = ( step.road_name && step.road_number ) ? step.road_name + ' ' + step.road_number : ( step.road_name ) ? step.road_name : step.road_number;
    var instruction = ( id + 1 ) + '.&nbsp;' + step.instruction + ( ( road ) ? ' ' + road + ' for ' + step.distance.miles + ' miles' : '' );
    html.infobox = '<div class="MMDirectionsInfobox">' + instruction + '</div>';
    html.result = '<a class="MMDirectionsAnchor" href="#" onclick="Page.oRouteSearch.markers[' + id + '].openInfoBox(); return false;">' + instruction + '</a>';
    return html;
}
function setDirections(fromAddress, toAddress, locale) {
//	alert(fromAddress);
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }

MMRouteSearch.prototype.handleResult = function(from_lat,from_lon,to_lat,to_lon,searchterm) {
 from=from_lat+","+from_lon;
 to=to_lat+","+to_lon;
  //    map = new GMap2(document.getElementById("map_canvas"));
 Page.oMap.clearOverlays();
 document.getElementById("MMResults").innerHTML='';
 MMElement.prototype.removeCssClass( 'MoreDetails', document.body );
 MMElement.prototype.addCssClass( 'RouteSearch', document.body );
 gdir = new GDirections(Page.oMap, document.getElementById("MMResults"));
// alert(gdir);
 GEvent.addListener(gdir, "load", onGDirectionsLoad);
 GEvent.addListener(gdir, "error", handleErrors);
  var locale="GB_en";
	gdir.load("from: " + from + " to: " + to,
                { "locale": locale });	
}
MMRouteSearch.prototype.requestRoute = function( from, to ) {
		toLat=to.lat;
		toLon=to.lon;
		doRoutePostcode(toLat,toLon,from);
}
/**
* @method constructPoints Converts strings to MMAddress objects for the route search
* @returns Array
**/

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("An unknown error occurred.");
	   
	}

	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...
	}


MMRouteSearch.prototype.constructPoints = function( from, to ) {
    if ( typeof from == 'string' ) {
        from = new MMAddress( { 'qs' : from, 'country_code' : 'GB' } );
    }
    if ( typeof to == 'string' ) {
        to = new MMAddress( { 'qs' : to, 'country_code' : 'GB' } );
    }
    return [ from, to ];
}
MMRouteSearch.prototype.handleError = function() {
    var me = this;
    Page.oDisam.handleGeocode( this.errors[0].results, this.errors[0].error_code, 'route', function( result ) {
        me.handleErrorResponse( result );
    } );
}
MMRouteSearch.prototype.handleErrorResponse = function( result ) {
    this.points[this.errors[0].input_id - 1] = result;
    this.errors.shift();
    if ( this.errors.length > 0 ) {
        return this.handleError();
    }
    this.requester.request( new MMRoute( this.points ) );
}
MMRouteSearch.prototype.routeCallback = function( route ) {
    if ( route.error_code && route.geocoding_errors.length > 0 ) {
        this.errors = route.geocoding_errors;
        this.handleError();
    } else {
        this.route = route;

        Page.oMap.clearOverlays();
        this.addOverlay( route.polyLine );
        this.addSteps( route.stages );
        Page.oMap.goToPosition( Page.oMap.getAutoScaleLocation( route.bounds ) );
        if (document.getElementById('funeral_type').value == "private") {
  				MMElement.prototype.addCssClass( 'privatefunerals',document.body);
  			}
        MMElement.prototype.addCssClass( 'RouteSearch', MMElement.prototype.removeCssClass( 'MoreDetails', MMElement.prototype.removeCssClass( 'StoreSearch', document.body ) ) );
    }
}
function doRoutePostcode(toLat,toLon,from) {
		address = new Object;
        address.qs = from;
        address.country_code = 'GB';
		if (checkPostCode(from)) {
					var p = new doroutepostcode(doRoutePostcodeHandler);
					p.do_routepostcode(toLat,toLon,from);
			//			doPostcode(from);			 
		} else {				
						geocoder = new GClientGeocoder();
						gaddress=from+" GB";				
	 	if (geocoder) {
	        geocoder.getLatLng(
	          gaddress,
	          function(point) {
	            if (!point) {
					if ( locator && locator instanceof LocationSearch && locator.disamHandler ) {
			            return locator.disamHandler( arguments[0], arguments[1], 'location', function() {
			                locator.handleResult( arguments[0] );
			            } );
			        }                        
		     //         doGeonames(from); switched off for now
	            } else {
					 address = new Object;
					 address.qs=from;
					 var lat=point.lat();
					 var lon=point.lng();
					 address.coords=new GLatLng(lat,lon);
					 MMRouteSearch.prototype.handleResult( lat,lon,toLat,toLon,from );		
	            }
	          }
	        );
	      }
		}  
}
var doRoutePostcodeHandler = {
	do_routepostcode: function(result) {

		eval(result);
	 
  	MMRouteSearch.prototype.handleResult( from_lat,from_lon,to_lat,to_lon,qs );	
	
	}
}