(function($) {
	$.fn.location_area = function(o) {
		return this.each(function() {
			new $location_area($(this), o);
		});
	};

	// Default configuration properties.
	var defaults = {
		'select_text' : '- Выберите район -',
		'parent': '',
		'limit': 150,
		'parent_container': '',
		'multiple': 0
	};

	// constructor
	$.location_area = function(e, o)
	{
		var self = this;
		this.options	= $.extend({}, defaults, o || {});
		
		this.container = e;
		this.cache = {};
		this.validate_classes = [];
		
		this.setupList();
	};

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

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

	$location_area.fn.extend = $location_area.extend = $.extend;

	$location_area.fn.extend({
		
		setupList: function() {
			if ( $('.location-area-o', this.container).length > 0 ) {
				this.validate_classes = [];

				var classList = $('.location-area-o', this.container).attr('class').split(' ');
				if ( classList != undefined ) {
					for ( var i = 0; i < classList.length; i++ ) {
						if ( classList[i] != 'list' && classList[i] != 'location-area-o' )
							this.validate_classes.push(classList[i]);
					}
				}
			}
			$('*',this.container).remove();
			
			this.showLoader();
			var self = this;
			var parent = this.options.parent;
			
			if (typeof this.cache[parent] == 'object')
				return self.loadListSuccess(this.cache[parent], parent);

			$.ajax({
				mode: 'abort',
				port: 'list_area',
				type: 'POST',
				url: '/service/source/db.location_area',
				dataType: 'json',
				data: {
					parent: parent,
					type: 'areas',
					limit: this.options.limit
				},
				
				error: function() {
					if (confirm("Не удалось получить список.\nПовтотирить?"))
						self.setupList();
				},
				
				success: function(json) {
					self.loadListSuccess(json, parent);
				}
			});
		},

		loadListSuccess: function(json, parent) {
			var self = this;
			
			if ( json.count > 0 )
			{
				var list = $('<select/>');
				list.addClass('list').addClass('location-area-o');
				for ( var i in this.validate_classes ) {
					list.addClass(this.validate_classes[i]);
				}
				if ( this.options.multiple ) {
					list.attr('multiple', 'multiple')
						.attr('title', this.options.select_text);
				} else {				
					list.append($('<option/>').attr({value: ''}).html(this.options.select_text));
				}
				list.attr('name',this.options.result);

				jQuery.each(json.list, function(i, v) {
					list.append($('<option/>').attr({
						value: v.id,
						_type: v.type,
						selected: false
					}).html(v.name));
				});
				
				$('*',this.container).remove();
				this.container.append(list);
				
				if ( this.options.parent_container != "" )
				{
					$('.'+this.options.parent_container).css('display','');
				}
				
				if (this.cache[parent] == undefined)
					this.cache[parent] = json;
				
				if ( this.options.multiple ) {
					if ( $.browser.msie )
						list.get(0).selectedIndex = -1; // IE достал!!!
					list.asmSelect({
						prefix: 'Ar',
						listType: 'ul',
						animate: true,
						sortable: false,
						hideWhenAdded: true,
						highlight: false,
						removeLabel: this.options.removeLabel,
						addItemTarget: 'bottom',
						listAlign: this.options.listAlign
					});
					if ( $.browser.msie )
						list.get(0).selectedIndex = -1; // IE достал два раза!!!
				}
			} else {
				if ( this.options.parent_container != "" )
				{
					$('.'+this.options.parent_container).css('display','none');
				}
			}
			
			this.removeLoader();
		},
		
		changeParent: function(params) {
			this.setupList();
		},

		showLoader: function() {
			
			this.removeLoader();
			
			var loader = $('<input type="text" />');
			loader.attr({
				readonly: true, disabled: true,
				value: 'Загрузка...'
			}).addClass('loader');
			
			this.container.append(loader);
		},

		removeLoader: function() {
			$('.loader', this.container).remove();
		}

	});

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

})(jQuery);
