/**
 * 
 * Dependencies:
 * - jQuery
 * - jquery.autocomplete.js plug in
 * - breakout_address.js
 */

;(function($) {
        $.fn.locationinput = function(prefix, locations, options) {
            options = $.extend(true, {}, $.locationinput.defaults, options);
            return this.each(function() {
                new $.locationinput(this, prefix, locations, options);
            });
        };
        
        $.locationinput = function(element, prefix, locations, options) {
            var $input = $(element);
            var parent_form = $input.closest('form');
            
            // First add necessary hidden input fields to parent form
            form_html = '<input type="hidden" name="' + prefix + '_name" value="' + options.loc_values.name + '" />';
            form_html += '<input type="hidden" name="' + prefix + '_full_text" value="' + options.loc_values.full_text + '" />';
            form_html += '<input type="hidden" name="' + prefix + '_error_code" value="' + options.loc_values.error_code + '" />';
            form_html += '<input type="hidden" name="' + prefix + '_address" value="' + options.loc_values.address + '" />';
            form_html += '<input type="hidden" name="' + prefix + '_city" value="' + options.loc_values.city + '" />';
            form_html += '<input type="hidden" name="' + prefix + '_state" value="' + options.loc_values.state + '" />';
            form_html += '<input type="hidden" name="' + prefix + '_zip" value="' + options.loc_values.zip + '" />';
            form_html += '<input type="hidden" name="' + prefix + '_country" value="' + options.loc_values.country + '" />';
            form_html += '<input type="hidden" name="' + prefix + '_lat" value="' + options.loc_values.lat + '" />';
            form_html += '<input type="hidden" name="' + prefix + '_lng" value="' + options.loc_values.lng + '" />';
            form_html += '<input type="hidden" name="' + prefix + '_location_key" value="' + options.loc_values.location_key + '" />';
            
            $(parent_form).append(form_html);
            
            // And make sure that input field is named correctly:
            $($input).attr('name', prefix);
            
            var geocoder = new GClientGeocoder();
            // Add change event to input field
            $($input).change(function(){
                    if ($($input).val()) {
                        geocoder.getLocations($($input).val(), geocodeCallback);
                    } else {

                        clearHiddenFields();

                        // onEmpty callback
                        options.onEmpty();
                        $($input).removeClass(options.invalid_class);
                        $($input).removeClass(options.valid_class);
                    }
            });
            
            // Attach autocomplete to field
            $($input).autocomplete(locations, options.autocompleteOptions)
            .result(function(event, item) {
                    // Set Location Key
                    $("input[name='" + prefix + "_location_key']", parent_form).val(item.key);
                    
                    // Add input-valid class
                    $($input).removeClass(options.invalid_class);
                    $($input).addClass(options.valid_class);
                    if (options.textBlack) {
                        $($input).css('color','#111111');
                    }
                    
                    // Callback function
                    options.onLocationFound(item.lat, item.lng);
            });
            
            function geocodeCallback(response) {
                if ($("input[name='" + prefix + "_location_key']", parent_form).val()) {
                    for (var i = 0; i < locations.length; i++) 
                    {
                        if ($($input).val() == locations[i].name) {
                            return false;
                        }
                    }
                }
                clearHiddenFields();
                
                if (response.Status.code != G_GEO_SUCCESS) {
                    // Add input-invalid class
                    $($input).removeClass(options.valid_class);
                    $($input).addClass(options.invalid_class);
                    if (options.textBlack) {
                        $($input).css('color','#111111');
                    }
                    
                    // onError callback
                    options.onError(response.Status.code);
                    
                    return false;
                } else {
                    // Add input-valid class
                    $($input).removeClass(options.invalid_class);
                    $($input).addClass(options.valid_class);
                    if (options.textBlack) {
                        $($input).css('color','#111111');
                    }
                    
                    var address = breakout_address(response);
                    
                    // Callback function
                    options.onLocationFound(address['lat'], address['lng']);
                    
                    // Populate Hidden Fields
                    $("input[name='" + prefix + "']", parent_form).val(address['fullText']);
                    $("input[name='" + prefix + "_lat']", parent_form).val(address['lat']);
                    $("input[name='" + prefix + "_lng']", parent_form).val(address['lng']);
                    $("input[name='" + prefix + "_full_text']", parent_form).val(address['fullText']);
                    if (address['country']) {
                        $("input[name='" + prefix + "_country']", parent_form).val(address['country']);
                    }
                    if (address['city']) {
                        $("input[name='" + prefix + "_city']", parent_form).val(address['city']);
                    }
                    if (address['state']) {
                        $("input[name='" + prefix + "_state']", parent_form).val(address['state']);
                    }
                    if (address['zip']) {
                        $("input[name='" + prefix + "_zip']", parent_form).val(address['zip']);
                    }
                    if (address['house_address']) {
                        $("input[name='" + prefix + "_address']", parent_form).val(address['house_address']);
                    }
                }
            }
            
            function clearHiddenFields() {
                // Clear all hidden fields associated with prefix
                $("input[name='" + prefix + "_name']", parent_form).val('');
                $("input[name='" + prefix + "_full_text']", parent_form).val('');
                $("input[name='" + prefix + "_error_code']", parent_form).val('');
                $("input[name='" + prefix + "_address']", parent_form).val('');
                $("input[name='" + prefix + "_city']", parent_form).val('');
                $("input[name='" + prefix + "_state']", parent_form).val('');
                $("input[name='" + prefix + "_zip']", parent_form).val('');
                $("input[name='" + prefix + "_country']", parent_form).val('');
                $("input[name='" + prefix + "_lat']", parent_form).val('');
                $("input[name='" + prefix + "_lng']", parent_form).val('');
                $("input[name='" + prefix + "_location_key']", parent_form).val('');
            }
        };
        
        $.locationinput.defaults = {
            // Defaults for options
            onLocationFound: function(latitude, longitude){ return ''; },
            onEmpty: function(){ return ''; },
            onError: function(error_code){ return ''; },
            loc_values: {
                name: '',
                full_text: '',
                error_code: '',
                address: '',
                city: '',
                state: '',
                zip: '',
                country: '',
                lat: '',
                lng:'',
                location_key: ''
            },
            autocompleteOptions: {
                minChars: 0,
                matchContains: true,
                autoFill: false,
                scroll: false,
                selectFirst: false,
                formatItem: function(row, i, max) {
                    return row.name;
                }
            },
            valid_class: "input-valid",
            invalid_class: "input-invalid",
            textBlack: false
        };
})(jQuery);
