/* 
 * Dropdown plugin
 * Create custom dropdowns that behave like native dropdowns
 *
 * @author Zach Waugh <zwaugh@gmail.com>
 * @version 1.1
 * @requires ui.core.js
 *
 * Copyright (c) 2009 Zach Waugh MIT License
 */

(function($) {

$.widget("ui.dropdown", {
	_init: function() {
		var self = this, options = this.options;
		
		var select_options = this.element.find('option');
		var selected = this.element.find('option[selected]');
		var html = '<dl class="ui-dropdown ui-widget">';
		html += '<dt><a href="#' + selected.attr('value') + '">' + selected.html() + '</a></dt>';
		html += '<dd style="display:none">';
		html += '<ul class="ui-dropdown-options">';
		this.element.find('option').each(function(){
			var href = (options.links) ? $(this).attr('value') : '#' + $(this).attr('value');
			
			if ($(this)[0] == selected[0])
			{
				html += '<li><a href="' + href + '" class="ui-state-active">' + $(this).html() + '</a></li>';
			}
			else
			{
				html += '<li><a href="' + href + '">' + $(this).html() + '</a></li>';
			}
		});
		html += '</ul></dd></dl>';
		
		this.element.hide();
		this.element = $(html).insertAfter(this.element);
		
		// Bind Events
		this.element.find('dt a').click(function(event){ return self._toggleDropdown(event); });
		
		if (!options.links)
		{
			this.element.find('.ui-dropdown-options a').click(function(event) { return self._didChooseDropdownOption(event); });
		}
	},
	
	_hideDropdown: function(event)
	{
		// Hide menu and toggle visibility
		this.element.find('dd').slideUp(this.options.speed);
		this.element.toggleClass('ui-dropdown-visible');
	},
	
	_showDropdown: function(event)
	{
		this.element.find('dd').stop().slideDown(this.options.speed);
		this.element.addClass('ui-dropdown-visible');
	},
	
	_toggleDropdown: function(event)
	{
		event.preventDefault();

		if (this.element.hasClass('ui-dropdown-visible'))
		{
			this._hideDropdown(event);
		}
		else
		{
			this._showDropdown(event);
		}

		return false;
	},
	
	_didChooseDropdownOption: function(event)
	{
		// Indicate selected option in list
		this.element.find('.ui-dropdown-options a.ui-state-active').removeClass('ui-state-active');
		$(event.target).addClass('ui-state-active');
		
		// Swap text with current selection
		this.element.find('dt a').text($(event.target).text());
		
		this._hideDropdown();
		
		// Fire callback
		this._trigger('change', event, {option: event.target});
		
		return false;
	}
});

$.extend($.ui.dropdown, {
	version: "1.7.1",
	defaults: {
		links: false,
		speed: 300
	}
});

})(jQuery);
