/*
 * 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("option");        
		$.each(els, function(i,n) {
			str = $(n).val()
			lang_code = str.match(/[a-z]{2}/)
			rel = "<img src='/media/images/flags/" + lang_code + ".png'" + "/>";
			
			text = (rel || '') + (o.viewText ? $(n).text() : '');
			stropt += "<li rel='" + $(n).val() +"'>" + text + "</li>";
			if ($(n).attr("selected"))
				o.selectText = text;
		}); 

		el.after("<div id='" + name + "' class='jlb_class'><a id='a" + name + "' href='#'>" + o.selectText + '</a><ul id="jlb-list">' + stropt + "</ul></div>");
		
		$(".jlb_class").fadeIn("fast");

		// CLICK ON TITLE
		$("div#" + name + " a").click(function(){
			$(this).next().slideToggle("fast");
			return false;
		});

		// CLICK ON ELEMENT
		$("div#" + name + " ul li").click(function(){
			$(".jlb_class ul").slideUp(50);
			window.location.href = $(this).attr("rel");
		});

		// CLICK OUTSIDE
		$("body").click(function(){
			$(".jlb_class ul").slideUp("fast");
		});
	});
};

$(document).ready(function(){
	$("#lang").jListbox();
});
