RouteSearch = function( map, start, end, resultdiv, createSteps, callback, disamHandler ) {
    this.map = map;
    this.disamHandler = disamHandler;
    this.callback = callback;
    this.createSteps = createSteps;
    this.resultdiv = resultdiv;
    this.init( start, end );
}

RouteSearch.prototype = {
    route: null,
    requester: null,
    init: function( start, end ) {
        window.routeMarkers = [];
        this.start = start;
        this.end = end;
        var me = this;
        this.requester = MMFactory.createRouteRequester( function() {
            me.generalCallback( arguments[0] );
        }, this.map );    
        this.map.removeAllOverlays();
        var route = new MMRoute( [ start, end ] );
        window.route = route;
        this.requester.request( route );
    },
    addOverlay: function( myroute ) {
        for ( var i = 0, j = myroute.polyLine.length; i < j; i++ ) {
            myroute.polyLine[i].reset( myroute.polyLine[i].points, { 'opacity' : 0.6, 'color': undefined, 'thickness' : 1.0 } );
            this.polyLine = myroute.polyLine[i];
            this.map.addOverlay( this.polyLine )
        }
        this.map.goToPosition( this.map.getAutoScaleLocation( myroute.bounds ) );
    },
    displaySteps: function( myroute ) {
        var step, html;
        html = [];
        for ( var i = 0, j = route.stages.length; i < j; i++ ) {
            for ( var k = 0, l = route.stages[i].steps.length; k < l; k++ ) {
                step = route.stages[i].steps[k];
                html.push( this.createSteps( step, k, 'route' ) );
            }
        }
        this.resultdiv.innerHTML = '';
        this.resultdiv.innerHTML = html.join( '' );
        $("print-directions").show();
    },
    displayRoute: function() {
        this.map.removeAllOverlays();
        this.addOverlay( this.route );
        if ( markers && markers.length > 0 ) {
            var bounds = new MMBounds();
            for ( var i = 0, j = window.markers.length; i < j; i++ ) {
                this.map.addOverlay( window.markers[i] );
                bounds.extend( window.steps[i].start_point );
            }
            this.map.goToPosition( this.map.getAutoScaleLocation( bounds ) );
        }
    },
    handleResults: function( route ) {
        this.route = route;
        this.addOverlay( route );
        if ( typeof this.resultdiv != 'undefined' && typeof this.createSteps == 'function' ) {
            this.displaySteps( route );
        }
    },
    generalCallback: function( myroute ) {
        if ( myroute.geocoding_errors ) {
            return this.disamHandler( myroute.geocoding_errors[0], myroute.geocoding_errors[0].error_code, 'route', this );
        } else {
            this.handleResults( myroute );
        }
        if ( typeof this.callback != 'undefined' ) {
            this.callback( myroute );
        }
    }
}
