
/*
	Function jQuery.fn.fancySelect

	A jQuery plugin to relpace ordinary select boxes into more stylized equivalents.
	This plugin uses progressive enhancement techniques.

	Author:
		Mathieu Sylvain 2010 (mathieu.sylvain@nurun.com) for Nurun.com
*/
jQuery.fn.fancySelect = function() {
	jQuery.each(this, function(e) {
		var select, fancySelect, button;
		select = $(this).removeClass("fancySelect").hide().wrap('<div class="fancySelect"></div>');
		button = $('<a href="#" title=""><span class="label"></span></a>');
		fancySelect = select.parent().addClass(select[0].className).append(button);

		function change() {
			var html = $("option[selected='true']", select).html();
			$(button).attr("title", html);
			$(".label", button).html(html);
		}
		function hide() {
			fancySelect.css({"zIndex": "0"});
			select.hide();
			button.focus();
		}
		function show() {
			select.triggerHandler("click");
			select.triggerHandler("focus");
			fancySelect.css({"zIndex": "10000"});
			select[0].size = (select[0].length < 9) ? select[0].length : 9;
			select.fadeIn("fast").focus();
		}
		button.focus(function(e) {
			select.triggerHandler("focus");
		});

		button.click(function(e) {
			e.preventDefault();
			if(!select.attr('disabled')) {
				if (select.css("display") === "none") {
					show();
				}
			} else {
				hide();
			}
		});
		select.bind("select click blur", function(e){
			hide(e);
		});
		fancySelect.keypress(function(e) {
			if (e.keyCode == 40 && !select.attr('disabled')) {
				show();
			} else if (e.which == 13) {
				hide();
			}
		});
		select.change(function(e) {
			change(e);
		});
		change();
	});
};
