
var DESPLEGABLE__INICIADO = false;

function DESPLEGABLE__iniciar()
{
	if(DESPLEGABLE__INICIADO) return;
	DESPLEGABLE__INICIADO = true;
	
	$(document).click(DESPLEGABLE__cerrarTodo);
	$("ul.desplegable").each(DESPLEGABLE__iniciarLista);
}

function DESPLEGABLE__cerrarTodo($e,$el)
{	
	$("ul.desplegable").each(function($i,$li)
	{
		$li = $($li);
		if($el == undefined)
		{
			$li.find("ul.desplegable").each(function($i,$e){$($e).parent().hide()});
			$li.parent().hide();
			return;
		}
		
		var mainList = $el.data("owner").parent().parent();
		
		if($el != $li.parent())
		{
			//if($el == undefined) $li.parent().hide();
			if(mainList[0] != $li.parent()[0])
			{
				$li.find("ul.desplegable").each(function($i,$e){$($e).parent().hide()});
				$li.parent().hide();
			}
		}
	});
}

function DESPLEGABLE__iniciarLista($e,$f)
{
	var lista = $($f);
	var owner = lista.prev();
	if(!owner.length) owner = lista.parent();
	lista = lista.wrap('<div class="DESPLEGABLE__LISTA" />').parent().hide();
	owner.data("hasSubMenu",true);
	owner.data("type","element-sublist");
	owner.data("subMenu",lista);
	owner.hover(DESPLEGABLE__abrirSub);
	owner.addClass("desplegador");
	lista.data("isSub",owner.parent().hasClass("desplegable"));
	lista.data("ownerWidth",owner.width());
	lista.data("owner",owner);
	lista.data("type","list");
}

function DESPLEGABLE__colocarLista($li,$sub)
{
	if($sub == undefined) $sub = false;
	var owner = $($li.data("owner"));

	if($li.data("isSub")) $sub = true;
	
	var contenedor = owner.parent();
	if(!contenedor.hasClass("desplegable")) contenedor = null;
	else contenedor = contenedor.parent();
	
	var left = owner.offset().left;
	var top = owner.offset().top;
	
	if(!$sub) top += 30;
	if(contenedor != null) 
	{
		var position = contenedor.position();
		left = contenedor.width() + 10;
		top = -666;
	}
	
	$li.css("left",left + "px");
	if(top > -666) $li.css("top",top + "px");
}

function DESPLEGABLE__abrirSub($e)
{
	$e.preventDefault();
	$e.stopPropagation();
	var el = $($e.currentTarget);
	var lista = el.data("subMenu");
	DESPLEGABLE__cerrarTodo(null,lista);
	DESPLEGABLE__colocarLista(lista);
	lista.show();
	
}
