/*
 * 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 = jQuery(this);

		name = (el.attr('name') || el.attr('id') || 'internalName') + '_jlb';

		el.hide();
		stropt = "";
		var els = el.children("option");        
		els.each(function(i,n) {
			text = (jQuery(n).attr("rel") || '') + ' ' + (o.viewText ? jQuery(n).text() : '');
			stropt += "<li rel='" + jQuery(n).val() +"'><span class='padding'>" + text + "</span></li>";
			if (jQuery(n).attr("selected"))
				o.selectText = text;
		}); 

		el.after("<div id='" + name + "' class='a_jlb_class'><a id='a" + name + "' href='#'><span class='padding'>" + o.selectText + "</span></a><ul class='a_jlb_ul'>" + stropt + "</ul></div>");

		// CLICK ON TITLE
		jQuery("div#" + name + " a").click(function(){
			jQuery(this).next().slideToggle("fast");
			return false;
		});

		// CLICK ON ELEMENT
		jQuery("div#" + name + " ul li").click(function(){
			listName = jQuery(this).parent().parent().attr('id');
			listName = listName.substr(0, listName.length - 4);
			jQuery('[name=' + listName + ']').val(jQuery(this).attr("rel"));
			jQuery(this).parent().parent().children().eq(0).html(jQuery(this).html());
		});

		// CLICK OUTSIDE
		jQuery("body").click(function(){
			jQuery(".a_jlb_ul").slideUp("fast");
		});

		jQuery("div#" + name).addClass("a_jlb_working");
	});
};    

