(function($) {
	
	$.fn.select_list = function(_config) {
		if(_config=="options") {
			var __options = getArg(arguments, 1);
		}
		
		return $(this).each(function() {
			var _self = $(this);
		
			if(_config=="options") {
				var _data = _self.data("options");
				_data = $.extend(_data, __options);
				_self.data("options", _data);
				return _data;
			}

			var _defaults = {
				anchor      : _self,
				target      : _self,
				container   : _self.parents(".select-list"),
				list        : _self.parents(".select-list").find(".select-list-options"),
				layer       : _self.parents(".list-item,.mod-sub-hd"),
				on          : "click",
				unique      : true,
				min_width   : 200,
				select      : function() {},
				start       : function() {},
				end         : function() {}
			};
			var _options = $.extend(_defaults, _config);
			
			_self.data("options", _options);
			
			var _position = _options.anchor.position();
			_options.list.css("left", _position.left);
			var _top = _position.top + _options.anchor.height();
			_options.list.css("top", _top);
			var _border_width = parseInt(_options.list.css("border-left-width"), 10) + parseInt(_options.list.css("border-right-width"), 10);
			var _width = _options.anchor.width() - _border_width;
			if(_width < _options.min_width) { _width = _options.min_width; }
			_options.list.css("width", _width);
			
			var _action = function() {
				if(_options.unique) { _close_all_dialogs(); }
				_options.start(_self);
				_options.list.show();
				_options.layer.addClass("above");
				hideOnBlur(_options.list, function() {
					_options.layer.removeClass("above");
				});
				return false;
			};
			
			_self.click(function() {
				return _action();
			});
			
			var _setup_list_items = function() {
				_options.list.find("li.select-list-item").unbind("click");
				_options.list.find("li.select-list-item").click(function() {
					_options.select($(this), _options);
					return false;
				});
			}
			
			_setup_list_items();
			
			_self.data("refresh", _setup_list_items);
		});
	}
})(jQuery);

var addItemToSelectList = function(_list, _data) {
	$(_data).addClass("select-list-item");
	//$(_data).insertAfter($(_list).find("li.select-list-item:last"));
	$(_data).insertBefore($(_list).find(".placeholder"));
	var _refresh = _list.parents(".select-list").find(".select-list-trigger:first").data("refresh");
	if(typeof(_refresh)=="function") { _refresh(); }

};

