/*START SELECT BOX INITIALISING*/
$().ready(function() {
	$("#department").jListbox();
	});
/*END SELECT BOX INITIALISING*/

/*
 * 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);
		var selected="";
		name = (el.attr('name') || el.attr('id') || 'internalName') + '_jlb';

		el.hide();
		stropt = "";
		var els = el.children("option");        
		var f=0;
		$.each(els, function(i,n) {
			text = ($(n).attr("rel") || '') + ' ' + (o.viewText ? $(n).text() : '');
			if ($(n).attr("selected"))
			{
				o.selectText = text;
				selected="class='selected";
			}
			else
				selected="";
				f++;
			stropt += "<li rel='" + $(n).val() +"' "+selected+"' id='li_"+f+"'><span class='bordered'>" + text + "</span></li>";
		}); 
		el.after("<div id='" + name + "' class='jlb_class'><a id='a" + name + "' href='#'>" + o.selectText + "</a><ul id='dropdown'>" + stropt + "</ul></div>");

		// CLICK ON TITLE
		$("div#" + name + " a").click(function(){
			$(this).next().slideToggle("fast");
			return false;
		});

		// CLICK ON ELEMENT
		$("div#" + name + " ul#dropdown li").click(function(){
			listName = $(this).parent().parent().attr('id');
			li_id=($(this).attr('id'));
			count_li= $("ul#dropdown li").size();
			for ( i=1; i<=count_li; i++ ) {
				li_id_name="li_"+i;
				if (li_id==li_id_name)
					$("li#"+li_id).addClass('selected');
				else
					$("li#"+li_id_name).removeClass('selected');
			}
			listName = listName.substr(0, listName.length - 4);
			$('[name=' + listName + ']').val($(this).attr("rel"));
			$(this).parent().parent().children().eq(0).html($(this).html());
		});

		// CLICK OUTSIDE
		$("body").click(function(){
			$(".jlb_class ul#dropdown").slideUp("fast");
		});
	});
};    
