/*
 * jNice  * by Sean Mooney (sean@whitespace-creative.com)
 * modified by Martin Hlozek (martin.hlozek@bmedia.cz)
*/

(function($){
	$.fn.jNice = function(options){
		var self = this;
		/* each form */
		this.each(function(){
			$('select', this).each(function(index){
				var $select = $(this);
				$(this).addClass('jNiceHidden').wrap('<div class="jNiceSelect"></div>');
				var $wrapper = $(this).parent().css({zIndex: 100-index});
				$wrapper.prepend('<div><span class="jNiceField"><span class="jNiceText"></span></span><a href="#" class="jNiceOpen"></a></div><ul></ul>');
				var $ul = $('ul', $wrapper);
				$('option', this).each(function(i){
					$ul.append('<li class="' + this.className + '"><a href="#" index="'+ i +'">'+ this.text +'</a></li>');
				});
				$ul.hide().find('a').click(function(){
						$('a.selected', $wrapper).removeClass('selected');
						$(this).addClass('selected');
						/* Fire the onchange event */
						if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) {  $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); }
						$select[0].selectedIndex = $(this).attr('index');
						$('.jNiceText', $wrapper).html($(this).html());
						$('.jNiceSelect div').removeClass();
						$('.jNiceSelect div').addClass($(this).parent().get(0).className);
						$ul.hide();
						return false;
				});
				$('a:eq('+ this.selectedIndex +')', $ul).click();
			});

			/* Apply the click handler to the Open */
			$('a.jNiceOpen', this).click(function(){
														var $ul = $(this).parent().siblings('ul');
														if ($ul.css('display')=='none'){hideSelect();} /* Check if box is already open to still allow toggle, but close all other selects */
    													$ul.slideToggle();
														var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
														$ul.animate({scrollTop: offSet});
														return false;
												});

		});

		/* Hide all open selects */
		var hideSelect = function(){
			$('.jNiceSelect ul:visible').hide();
		};

		/* Check for an external click */
		var checkExternalClick = function(event) {
			if ($(event.target).parents('.jNiceSelect').length === 0) { hideSelect(); }
		};

		/* Apply document listener */
		$(document).mousedown(checkExternalClick);

		/* Add a new handler for the reset action */
		var jReset = function(f){
			var sel;
			$('.jNiceSelect select', f).each(function(){sel = (this.selectedIndex<0) ? 0 : this.selectedIndex; $('ul', $(this).parent()).each(function(){$('a:eq('+ sel +')', this).click();});});
		};
		this.bind('reset',function(){var action = function(){jReset(this);}; window.setTimeout(action, 10);});

	};

	/* Automatically apply to any forms with class jNice */
	$(function(){$('.jNice').jNice();	});

})(jQuery);

