/*
* jQuery geo_autocomplete plugin 1.0
*
* Copyright (c) 2009 Bob Hitching
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* Requires jQuery Autocomplete plugin by Jörn Zaefferer - see http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
* jquery.autocomplete.js requires a minor modification for geo_autocomplete to work, as shown in /lib/jquery.autocomplete_geomod.js
* 
*/
; (function($) {

    $.fn.extend({
        geo_autocomplete: function(_geocoder, _options) {
            options = $.extend({}, $.Autocompleter.defaults, {
                geocoder: _geocoder,
                mapwidth: 100,
                mapheight: 100,
                maptype: 'terrain',
                mapkey: 'ABQIAAAAbnvDoAoYOSW2iqoXiGTpYBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQNumU68AwGqjbSNF9YO8NokKst8w', // localhost
                mapsensor: false,
                parse: function(_results, _status, _query) {
                    var _parsed = [];
                    var acceptedStateCode = { 'US': '', 'VA': '', 'VI': '', 'PR': '', 'AS': '', 'FM': '', 'GU': '', 'MH': '', 'MP': '', 'UM': '' };
                    if (_results && _status && _status == 'OK') {
                        $.each(_results, function(_key, _result) {
                            if (_result.geometry && _result.geometry.viewport) {
                                // place is first matching segment, or first segment
                                // YR: Added code to accept only US based addresses
                                var valid = true;
                                var countryCode = "";
                                for (i = 0; i < _result.address_components.length; i++) {
                                    if (_result.address_components[i].types[0] == "point_of_interest") {
                                        valid = false;
                                        break;
                                    }
                                    else if (_result.address_components[i].types[0] == "country") {
                                        countryCode = _result.address_components[i].short_name;
                                        if (!(countryCode in acceptedStateCode)) {
                                            valid = false;
                                            break;
                                        }
                                        if ((countryCode == "US" && _result.address_components.length < 3) || (countryCode != "US" && _result.address_components.length < 2)) {
                                            valid = false;
                                            break;
                                        }
                                    }
                                }
                                var RE_NONASCII = /[^\u0000-\u007F]/;
                                //Check for non ascii characters
                                if (RE_NONASCII.test(_result.formatted_address) && valid) {
                                    valid = false;
                                }
                                if (valid) {
                                    var city = "", state = "";

                                    for (i = 0; i < _result.address_components.length; i++) {
                                        if ((_result.address_components[i].types[0] == "locality") || (countryCode != "US" && city == "" && _result.address_components[i].types[0] == "administrative_area_level_2")) {
                                            city = _result.address_components[i].short_name;
                                        }
                                        if ((_result.address_components[i].types[0] == "administrative_area_level_1") || (countryCode != "US" && _result.address_components[i].types[0] == "country")) {
                                            state = _result.address_components[i].short_name;
                                        }
                                    }

                                    if (city == "" || state == "") {
                                        var _place_parts = _result.formatted_address.split(',')
                                        var _place_index = -1;
                                        for (i = 0; i < _place_parts.length; i++) {
                                            if (_place_parts[i].trim() == "USA") {
                                                _place_index = i;
                                                break;
                                            }
                                        }

                                        if (city == "" && _place_index > 1) {
                                            city = _place_parts[_place_index - 2]
                                        }
                                        if (state == "" && _place_index > 0) {
                                            state = _place_parts[_place_index - 1]
                                        }
                                    }




                                    var _place = city + ", " + state;

                                    //Check for State Search
                                    if (_place.indexOf(", USA") < 0) {
                                        _parsed.push({
                                            data: _result,
                                            value: _place,
                                            result: _place
                                        });
                                    }
                                }
                            }
                        });
                    }
                    return _parsed;
                },
                formatItem: function(_data, _i, _n, _value) {
                    var _src = ''; //'http://maps.google.com/maps/api/staticmap?visible=' + _data.geometry.viewport.getSouthWest().toUrlValue() + '|' + _data.geometry.viewport.getNorthEast().toUrlValue() + '&size=' + options.mapwidth + 'x' + options.mapheight + '&maptype=' + options.maptype + '&key=' + options.mapkey + '&sensor=' + (options.mapsensor ? 'true' : 'false');
                    var _place = _data.formatted_address.replace(/,/gi, ', ');
                    return /*'<img src="' + _src + '" width="' + options.mapwidth + '" height="' + options.mapheight + '" /> ' +*/_place + '<br clear="both"/>';
                }
            }, _options);

            // if highlight is set to false, replace it with a do-nothing function
            options.highlight = options.highlight || function(value) { return value; };

            // if the formatMatch option is not specified, then use formatItem for backwards compatibility
            options.formatMatch = options.formatMatch || options.formatItem;

            return this.each(function() {
                new $.Autocompleter(this, options);
            });
        }
    });

})(jQuery);
