/*
	Customizable combobox functions.
	NOTE(20110106,jv) : the idea was that cbInit and cbSelect worked as 
	  method-like functions, but the way jquery wrappers are made and passed-by-reference
	  is somewhat complex, causing the functions to not work as intended. 
	  Fix later.
*/

var slideDown = false;


$(function() {
	var $cb= $('.cb-main');
	
	$cb.each(function(i, el)	{	cbInit($(el));	});
	
	//jQuery("#languages").ready(function(i, el) { alert(); });
	
	//cbSelect($("#languages"), 0)
});


function cbInit($cb)
{
	$cb.$sel= $cb.children('.cb-select');
	$cb.$list= $cb.children('ul');
	
	$cb.$list.hide();
	
	// --- Add input field ---
	log($cb.children('input').length);
	if($cb.children('input').length == 0)
		$cb.append('<input type="text"/>');
	
	$cb.$input= $cb.children('input').eq(0);
	$cb.$input.attr('name', $cb[0].id);
	
	// --- Add handlers ---
	$cb.$sel.click(function(e) {
		if (this.id == "languageSelector")
		{
			$(this).css("background-color", "#ccc");
		}
		if($cb.$list.is(":visible"))
			if (slideDown == true)
			{
				$cb.$list.hide();
			}
		else
			slideDown = false;
			$cb.$list.slideDown(500, function(){
				slideDown = true;
			});
	});
	
	$cb.$list.children('li').click(function(e) {
		cbSelect($cb, $(this).index());
		$("#languageSelector").css("background-color", "transparent");
	});
	
	$cb.mouseleave(function() {
		if (slideDown == true)
		{
			$cb.$list.hide();
		}
		$("#languageSelector").css("background-color", "transparent");
	});

	// Special for language
	if (($cb.attr("selectedIndex")) != "" && ($cb.attr("selectedIndex")) != undefined)
	{
		cbSelect($cb, $cb.attr("selectedIndex"));
	}
	//cbSelect($cb, 0);		Op verzoek van Nobby, 28/12/2010
}

function cbSelect($cb, i)
{
	var $next= $cb.$list.children('li').eq(i);
	
	$cb.$list.children('.active').removeClass('active');
	$next.addClass('active');
	$cb.$sel.text($next.text());
	$cb.$input.attr('value', $next.text());
	
	$cb.$list.hide();
	
	// TODO: write to hidden <select>
}

// NOTE: the way console.log works is apparently very browser specific. 
// Firefox: console.log.apply(this, args), but only if Firebug's open.
// IE: console.log is object, not function, so apply doesn't work.
// Safari: ???
// Opera: ???
// Because of the various potential problems, wrapping it in an exception block.
function log(format, args)
{
	try
	{
		console.log.apply(this, arguments);
	}
	catch(err) {}
}

// EOF

