$.fn.dropdown = function(params) {
	params = params || {};
	var expand = params.expand || 'click';
	var links = params.links || [];
	
	var dropdown = this;
	var dropdown_title = dropdown.find('a.dropdown-title');
	var rand = Math.ceil(Math.random() * 10000000000);
	var dropdown_list_id = 'dropdown-list-' + rand;
	var dropdown_list = $('<ul></ul>').css({
		background: 'transparent'
		,listStyle: 'none'
		,overflow: 'visible'
		,position: 'absolute'
		,zIndex: 1100
	}).attr('id', dropdown_list_id).appendTo(dropdown);
	dropdown_list.hide();
	
	for (var i in links) {
		var link = links[i];
		
		if (!link.title) {
			continue;
		}
		
		var item = $('<li></li>').appendTo(dropdown_list);
		if (link.selected) item.addClass('selected');
		var anchor = $('<a></a>').attr('href', link.url).text(link.title).css({
			display: 'block'
			,overflow: 'visible'
			,whiteSpace: 'nowrap'
		}).appendTo(item);
		if (link.className) anchor.addClass(link.className);
		var pos = Number(i) + 1;
		if (pos == links.length) item.addClass('last');
	}

	if (expand == 'hover') {
		dropdown.hover(function() {
			dropdown.addClass('expanded');
			dropdown_list.slideToggle('fast', function() {
//				dropdown_list.css('width', dropdown_list.width());
				dropdown_list.css('width', 'auto');
			});
		}, function() {
			dropdown.removeClass('expanded');
			dropdown_list.stop().hide().height('auto');
		});
	} else {
		var dropdown_title_click = function() {
			var dropdown_list = $('#' + dropdown_list_id);
			
			if (dropdown.hasClass('expanded')) {
				dropdown.removeClass('expanded');
				dropdown_list.stop().slideUp('fast', function() {
					dropdown_list.height('auto').hide();
				});
				return;
			}
			
			dropdown.addClass('expanded');
			dropdown_list.slideDown('fast', function() {
				dropdown_list.css('width', dropdown_list.width());
				dropdown_list.css('width', 'auto');
			});
			setTimeout(function() {
				$(document.body).one('click', function(e) {
					var $e = $(e.target);
					
					if (
						$e.hasClass('dropdown-title')
						|| $e.parent().hasClass('dropdown-title')
						|| $e.parent().parent().hasClass('dropdown-title')
					) {
						return;
					}

					dropdown.removeClass('expanded');
					dropdown_list.stop().height('auto').hide();
				});
			}, 1);
		};
		dropdown_title.click(function() {
			dropdown_title_click();
			return false;
		});
	}
	
	dropdown_list.css('minWidth', dropdown_title.outerWidth());
	
	if ($.isFunction(params.onComplete)) {
		params.onComplete();
	}
};

