(function($) {
    $.fn.location_suggest = function(o) {
        return this.each(function() {
            new $location_suggest($(this), o);
        });
    };
	
	$.fn.extend({
		suggest: function(handler) {
			return this.bind("suggest", handler);
		}
	});
	
    // Default configuration properties.
    var defaults = {
		'type': [],
		'suggest_limit' : 20,
		'text' : '',
		'suggest_text' : 'Введите адрес...',
		'parent': '',
		'result': '',
		'house': '',
		'default_location': ''
	};


    $.location_suggest = function(e, o) {
	
		var self = this;
		this.options = $.extend({}, defaults, o || {});

		this.container = e;
		
		self.options.type = self.options.type.toString();
		
		this.restoreEnv();
   };

    // Create shortcut for internal use
    var $location_suggest = $.location_suggest;

    $location_suggest.fn = $location_suggest.prototype = {
        location_suggest: '0.0.1'
    };

    $location_suggest.fn.extend = $location_suggest.extend = $.extend;

    $location_suggest.fn.extend({

        restoreEnv: function() {
			var self = this;

			$('[class*="location-suggest-s"]', this.container).each(function(i, v) {
				self.registerSuggest($(v), self.options.parent);
				
				if ( self.options.text == '' )
					v.value = self.options.suggest_text;
				
				$(v).bind('focus', function() {
					if ( this.value == self.options.suggest_text )
						this.value = '';
				});
				$(v).bind('blur', function() {
					if ( this.value == '' )
						this.value = self.options.suggest_text;
				});
				
				$(v).bind('change', function() {
					if ( this.value == '' )	{
						$('.location-suggest-v', self.container).val('');
						$('.location-suggest-h', self.container).val('');
						$('.location-suggest-hint', self.container).html('Выбрано: -');
					}
				});
			});
        },

		registerSuggest: function(suggest, code) {

			var self = this;

			//suggest.val('');
			suggest.autocomplete("/service/source/db.location_inline", {
				dataType: 'json',
				extraParams: {
					parent: code,
					type_in: this.options.type,
					default_location: this.options.default_location,
					limit: this.options.suggest_limit,
					type: 'query_suggest'
				},
				parse: function(json) {
					var parsed = [];
					
					if ( !json.list || !json.list.length )
					{
						$('.location-suggest-s').addClass('suggest_not_found');
						return parsed;
					}
					else
					{
						$('.location-suggest-s').removeClass('suggest_not_found');
					}
					
					for (var i in json.list) {
						if ( typeof json.list[i] != 'object' )
							continue;
						
						parsed[parsed.length] = {
							data: json.list[i].normal,
							value: json.list[i]
						};
					}
					
					if ( parsed.length > 0 ) {
						self.first_item = parsed[0];
					}
					
					return parsed;
				},
				formatItem: function(text, i, max, value) {
					var Desc = '';
					if ( value.parent && value.parent.length ) {
						Desc = '<div class="ac_describe">';
						for (var j in value.parent)
						{
							if ( typeof value.parent[j] == 'string' )
								Desc += value.parent[j] + '<br />';
						}
						Desc += '</div>';
					}
					return value.name + Desc;
				},
				returnFocus: false,
				max: this.options.suggest_limit
			}).result(function(event, name, value) {
				suggest.val(name.replace(/<.*>/, ''));
				$('.location-suggest-v', self.container).val(value.id);
				if ( value.house )
					$('.location-suggest-h', self.container).val(value.house);
				else
					$('.location-suggest-h', self.container).val('');
				$('.location-suggest-hint', self.container).html(name);
				$(self.container).trigger("suggest", value);
			});
		}
    });

    $location_suggest.extend({
        defaults: function(d) {
            return $.extend(defaults, d || {});
        }
    });
	
})(jQuery);
