/****************************************************************************************************
	enhancedSelect 
	
	Built with jQuery - http://jquery.com
	
	Build-A-Bear Workshop

	Created by the friendly folks at Happy Cog
	http://www.happycog.com/
****************************************************************************************************/
(function($){
	
	$.fn.enhancedSelect = function(options) {

		var defaults = {};
		var options = $.extend(defaults, options);
		
		return this.each(function() {
			
			var select = $(this);
			
			select.wrap('<span class="enhanced"></span>');
			select.hide();
			
			this.enhanced = select.parent();
			var enhanced = this.enhanced
			
			// prep the target for our new markup
			enhanced.append('<dl class="dropdown"><dt><a class="dropdown_toggle" href="#"></a></dt><dd><div class="droplist"><ul></ul></div></dd></dl>');

			// we don't want to see it yet
			this.droplist = enhanced.find('.droplist');
			var droplist = this.droplist;
			droplist.hide();
			
			this.dropdown = enhanced.find('.dropdown');
			var dropdown = this.dropdown;
			droplist.css({'display':'none'});
			
			// parse all options within the select and set indices
			select.find('option').each(function() {
				option = $(this);
				// create the option
				replaceOption = $('<li><a href="#"><span class="value">' + option.text() + '</span></a></li>');
				
				var color = /colorize_(.*)/i.exec(option.attr("class"))
				if(color){
					replaceOption.addClass("colorized");
					replaceOption.find("a span.value").prepend('<span class="swatch" style="background-color: #'+ color[1] +'">'+ color[1] +'</span> ');
				}
				
				droplist.find('ul').append(replaceOption)
				
				// check to see if this is what the default should be
				if(option.attr('selected') == true) {
					enhanced.find('a.dropdown_toggle').append(replaceOption.find('a').html());
				}
			});


			// let's hook our links, ya?
			enhanced.find('a.dropdown_toggle').click(function() {			
				if(droplist.css('display')=='block') {
					dropdown.removeClass('activedropdown');
					droplist.css({'display':'none'});
				} else {
					dropdown.addClass('activedropdown');
					droplist.css({'display':'block'});
				}
				return false;
				
			});
		  
		  
			// bind to clicking a new option value
			enhanced.find('.droplist a').click(function(e) {
				enhanced.find('.droplist').hide();
				// set the proper index
				select[0].selectedIndex = $(this).find('span.index').text();
				// update the pseudo selected element
				enhanced.find('.dropdown_toggle').empty().append($(this).html());
				return false;
			});
		
			// add an event to $(document) to ensure if they click outside the dropdown will close
			$(document).mousedown(function(event){
				if ($(event.target).parents('.activedropdown').length === 0) {
				    enhanced.find('.activedropdown').removeClass('activedropdown');
				    enhanced.find('.droplist').hide();
				}
			});
			
		});
		
	};

})(jQuery);