/*
 * 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 = $(this);

		name = (el.attr('name') || el.attr('id') || 'internalName') + '_jlb';

		el.hide();
		stropt = "";
		var els = el.children();
		$.each(els, function(i,n) {
            text = ($(n).attr("rel") || '') + ' ' + (o.viewText ? $(n).text() : '');
            label = ($(n).attr("label") || '') + ' ' + (o.viewText ? $(n).text() : '');
            if($(n).attr("value")) {
                if ($(n).attr("selected")) {
                    o.selectText = label;
                    stropt += "<li rel='" + $(n).val() +"' class='jlb_option_selected'>" + text + "</li>";
                } else {
                    stropt += "<li rel='" + $(n).val() +"' class='jlb_option' style='cursor: pointer;'>" + text + "</li>";
                }                
            } else {
                stropt += "<li rel='123' class='jlb_optgroup'>" + text + "</li>";
                var els2 = $(n).children();
                $.each(els2, function(i2,n2) {
                    text = ($(n2).attr("rel") || '') + ' ' + (o.viewText ? $(n2).text() : '');
                    label = ($(n2).attr("label") || '') + ' ' + (o.viewText ? $(n2).text() : '');
                    if ($(n2).attr("selected")) {
                        o.selectText = label;
                        stropt += "<li rel='123' class='jlb_option_selected'>" + text + "</li>";
                    } else {
                        stropt += "<li rel='123' class='jlb_option' style='cursor: pointer;'>" + text + "</li>";
                    }
                });
            }
		}); 

		el.after("<div id='" + name + "' class='jlb_class'><a id='a" + name + "' href='#'>" + o.selectText + "</a><ul>" + stropt + "</ul></div>");

		// CLICK ON TITLE
		$("div#" + name + " a").click(function(){
			$(this).next().slideToggle("fast");
			return false;
		});
       
        // CLICK ON ELEMENT
        $("div#" + name + " ul li").click(function(){
            if ($(this).is (".jlb_option")) {
                listName = $(this).parent().parent().attr('id');
                listName = listName.substr(0, listName.length - 4);
                $('[name=' + listName + ']').val($(this).attr("rel"));
                $(this).parent().parent().children().eq(0).html("<div class='jlb_option'>"+$(this).html()+"</div>");
            }
        });

		// CLICK OUTSIDE
		$("body").click(function(){
			$(".jlb_class ul").slideUp("fast");
		});
	});
};    

