/**
 * Uses searchysearch to make a smart address text entry.
 * Enter a postal/zip code and it will retrieve city/state/country/lat/long
 *
 * jquery.postallocater.js
 * @author Nathan Howell <nathan@navigatormm.com>
 */

(function ($) {

    $.fn.postalLocater = function (_options) {
        var options = {
            countries             : ['CA', 'US'],
            matchers              : []
        };
        $.extend(true, options, _options);

        this.addClass('postallocater');

        $.each(options.countries, function(k,v) {
            options.matchers[k] = 'postalcode_'+v.toUpperCase();
        });

        $(this).searchySearch({
            only_search_on_match: true,
            fields_to_clear: ['input#location_id'],
            fields_to_hide: ['span#location_pl'],
            searcher: function(d) {
                var $this = this;
                $.getJSON('/api/location_search/'+d.searchtext, function(data) {
                    d.results = data;
                    $this.trigger('searchcomplete');
                });
            },
            searchComplete: function(d) {
                var $f = $(this).closest('div');
                $f.find('#postal_code').val(d.results.postal_code);
                $f.find('#location_id').val(d.results.id).trigger('change', d.results);
                $f.find('span#location_pl').text(d.results.full_name).show();
            },
            matchers: options.matchers
        });

    };

}(jQuery));

