/*
 * jListbox jQuery plugin
 *
 * Copyright (c) 2009 Giovanni Casassa (senamion.com - senamion.it)
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://www.senamion.com
 *
 */

jQuery.fn.jListbox = function(o) {

	o = jQuery.extend({
		selectText: "No option",
		viewText: true
	}, o);

	return this.each(function() {
		var el = $j(this);

		name = (el.attr('name') || el.attr('id') || 'internalName') + '_jlb';

		el.hide();
		stropt = "";
		var els = el.children("option");        
		$j.each(els, function(i,n) {
			text = ($j(n).attr("rel") || '') + ' ' + (o.viewText ? $j(n).text() : '');
			stropt += "<li class='"+$j(n).attr("selected")+"' rel='" + $j(n).val() + "'>" + text + "</li>";
			if ($j(n).attr("selected"))
				o.selectText = text;
		}); 

		el.after("<div id='" + name + "' class='jlb_class'><a id='a" + name + "' href='#'>" + o.selectText + "</a><ul>" + stropt + "</ul></div>");

		// CLICK ON TITLE
		$j("div#" + name + " a").click(function(){
			$j(this).next().slideToggle("fast");
			return false;
		});
		
		function closeallfirst() { $j(".jlb_class ul:visible").each(function(intIndex){$j(this).fadeOut("fast");}); }

		// CLICK ON ELEMENT
		$j("div#" + name + " ul li").click(function(){
			$j("div#" + name + " ul li").removeClass("true");	   
			$j("div#" + name + " ul li").removeClass("false");	   
			$j(this).addClass("true");						   
			listName = $j(this).parent().parent().attr('id');
			listName = listName.substr(0, listName.length - 4);
			$j('[name=' + listName + ']').val($j(this).attr("rel")).trigger('change');
			$j(this).parent().parent().children().eq(0).html($j(this).html());
		});
		
		$j("div#" + name + " ul li").mouseenter(function(){
			inx = $j(this).attr("rel");
			
			$j(".down .info").fadeIn("fast");
			$j("div.i").css('display', 'none');
			$j("div.i[rel="+inx+"]").css('display', 'block');
		});

		// CLICK OUTSIDE
		$j("body").click(function() {
			$j(".jlb_class ul").slideUp("fast");
		});
	});
};    
