/*
By: http://mondaybynoon.com/2009/02/23/creating-custom-form-elements-using-jquery-selects/
*/

jQuery.noConflict();

var z = 998;

checkExternalClick = function(event)
{
	if (jQuery(event.target).parents('.activedropdown').length === 0)
	{
		jQuery('.activedropdown').removeClass('activedropdown');
		jQuery('.options').hide();
	}
};


jQuery(document).ready(function($)
{
	jQuery(document).mousedown(checkExternalClick);

	jQuery('select').each(function() 
	{
		if(jQuery(this).parent().hasClass('enhanced'))
		{
			targetselect = jQuery(this);
			targetselect.hide();

			// set our target as the parent and mark as such
			var target = targetselect.parent();
			target.addClass('enhanced');

			// prep the target for our new markup
			target.append('<dl class="dropdown"><dt><a class="dropdown_toggle" href="#"></a></dt><dd><div class="options"><ul></ul></div></dd></dl>');
			target.find('.dropdown').css('zIndex',z);
			z--;

			// we don't want to see it yet
			target.find('.options').hide();

			// parse all options within the select and set indices
			var i = 0;
			targetselect.find('option').each(function() 
			{
				// add the option
				target.find('.options ul').append('<li><a href="#"><span class="value">' + jQuery(this).text() + '</span><span class="hidden index">' + i + '</span></a></li>');

				// check to see if this is what the default should be
				if(jQuery(this).attr('selected') == true)
				{
					targetselect.parent().find('a.dropdown_toggle').append('<span></span>').find('span').text(jQuery(this).text());
				}
				i++;
			});
		}
	});


	// let's hook our links, ya?
	jQuery('a.dropdown_toggle').live('click', function() 
	{
		var theseOptions = jQuery(this).parent().parent().find('.options');
		if(theseOptions.css('display')=='block')
		{
			jQuery('.activedropdown').removeClass('activedropdown');
			theseOptions.hide();
		}
		else
		{
			theseOptions.parent().parent().addClass('activedropdown');
			theseOptions.show();
		}
		return false;
	});

	// bind to clicking a new option value
	jQuery('.options a').live('click', function(e)
	{
		jQuery('.options').hide();

		var enhanced = jQuery(this).parent().parent().parent().parent().parent().parent();
		var realselect = enhanced.find('select');

		// set the proper index
		realselect[0].selectedIndex = jQuery(this).find('span.index').text();

		// update the pseudo selected element
		enhanced.find('.dropdown_toggle').empty().append('<span></span>').find('span').text(jQuery(this).find('span.value').text());

		return false;
	});
});