LocationSearch = function( search_field, country, map, defaulttext, storesearch, callback, handle ) {
    window.locator = this;
    this.input_default = defaulttext;
    this.search_field = search_field;
    this.storeSearch = storesearch;
    this.disamHandler = handle;
    this.callback = callback;
    this.country = country;
    this.map = map;
    this.init();
}

LocationSearch.prototype = {
    init: function() {
        var me = this;
        if ( this.search_field && this.search_field.form ) {
            this.search_field.form.onsubmit = function() {
                return false;
            }
            MMAttachEvent( this.search_field.form, 'submit', function() {
                me.onFormSubmit();
            } );
        }
    },
    onFormSubmit: function() {
        var cc, query, address, geocoder;
        cc = this.getCountryCode();
        query = this.search_field.value;
        if ( query == this.input_default ) {
            query = '';
        }
        address = new MMAddress();
        address.qs = query;
        address.country_code = cc;
        geocoder = new MMGeocoder( GeocoderCallback );
        geocoder.geocode( address );
		// Coolpink: add query as "from" location on direction search
		document.getElementById("directions_from").value = query;
		MarkerFields.DefaultFrom = query;
    },
    getCountryCode: function() {
        if ( typeof this.country == 'string' ) {
            this.getCountryCode = function() {
                return this.country;
            }
        } else {
            this.getCountryCode = function() {
                return this.country.options[this.country.selectedIndex].value;
            }
        }
        return this.getCountryCode();
    },
    handleResult: function( address ) {
        if ( this.storeSearch ) {
            this.storeSearch.getData( address.coords );
        } else {
            this.map.goToPosition( new MMLocation( address.coords, address.zoom_factor ) );
        }
        if ( this.callback && typeof this.callback == 'function' ) {
            this.callback( address );
        }
    }
}

GeocoderCallback = function() {
    if ( arguments[1] == 'MM_GEOCODE_MULTIPLE_MATCHES' || arguments[1] == 'MM_GEOCODE_NO_MATCHES' ) {
        if ( locator && locator instanceof LocationSearch && locator.disamHandler ) {
            return locator.disamHandler( arguments[0], arguments[1], 'location' );
        }
    }
    var coords = arguments[0][0];
    locator.handleResult( coords );
}
