/**
 * Find the element in the current HTML document with the given id, or if more
 * than one parameter is passed, return an array containing the found elements.
 * Any non-string arguments are left as is in the reply.
 * This function is inspired by the prototype library however it probably works
 * on more browsers than the original.
 * @see http://www.getahead.ltd.uk/dwr/util-general.html
 */
function $$()
{
    var elements = new Array();

    for (var i = 0; i < arguments.length; i++)
    {
        var element = arguments[i];
        if (typeof element == 'string')
        {
            if (document.getElementById) {
                element = document.getElementById(element);
            }
            else if (document.all) {
                element = document.all[element];
            }
        }
        if (arguments.length == 1) {
            return element;
        }
        elements.push(element);
    }
    return elements;
}

/**
 * Recupera la url actual, sin parametros
 */
function getUrl() {
	return location.href.substring(0, location.href.indexOf('?'));
}

/**
 * funcion para añadir eventos a objetos
 * param obj: objeto al que añadir el evento
 * param evType: tipo de evento
 * param fn: funcion a asignar al evento
 * ej: addEvent(window, 'load', foo);
 */
function addEvent(obj, evType, fn) {
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, false);
		return true;
	} else
	if (obj.attachEvent)
		return obj.attachEvent('on' + evType, fn);
	else
		return false;
}

/**
 * Comprueba si un campo es vacio o no
 */
function isVacio(valor) {
	return valor == null || valor == '' || valor == 'null';
}

/**
 * Elimina todos los hijos de un nodo
 * Ej: removeAllNodes('misFavoritos');
 */
function removeAllNodes(nodo) {
	ele = $(nodo);
	var child = ele.firstChild;
	var next;
	while (child != null) {
		next = child.nextSibling;
		ele.removeChild(child);
		child = next;
	}
}

/**
 * Oculta la sección de Programas del Consejo de la portada
 */
function hideProgramasConsejo() {
	var id = 'programasConsejo';
	actw = act_width(id);
	maxw = max_width(id);
	if (actw==maxw) {
		$(id).style.display="block";
		if (isVacio($(id).style.height))
			$(id).style.height = $(id).offsetHeight + 'px';
		var delay = Math.ceil(600/actw);
		var posBarra = $('barraDcha').offsetWidth - 24;
		var tamContenido = $('contenidoPortada').offsetWidth;
		for(i=0;i<=actw;i=i+4) {
			neww = actw-i;
			if (neww < 4) neww = 0;
			STO("$('"+id+"').style.width='"+neww+"px';" + 
			    "$('barraDcha').style.backgroundPosition='" + (posBarra - neww) + "px 0';" +
			    "$('contenidoPortada').style.width='" + (tamContenido+i) + "px';",
			    delay*i);
		}
		$('toggleProgramasConsejo').style.visibility = 'visible';
		$('barraDcha').style.backgroundImage = 'url("/contenidos/system/modules/com.fti.camaragijon/templates/res/css/imgs/barra_programas.png")';
	}
}
/**
 * Muestra la sección de Programas del Consejo de la portada
 */
function showProgramasConsejo() {
	var id = 'programasConsejo';
	actw = act_width(id);
	if (actw==0) {
		$('toggleProgramasConsejo').style.visibility = 'hidden';
		$(id).style.display="block";
		$(id).style.width="0px";
		maxw = max_width(id);
		var delay = Math.ceil(600/maxw);
		var posBarra = $('barraDcha').offsetWidth - 24;
		var tamContenido = $('contenidoPortada').offsetWidth;
		for(w=1;w<=maxw;w=w+4) {
			STO("$('"+id+"').style.width='"+w+"px';" +
			    "$('barraDcha').style.backgroundPosition='" + (posBarra - w) + "px 0';" +
			    "$('contenidoPortada').style.width='" + (tamContenido-w) + "px';",
			    delay*w);
		}
		$('barraDcha').style.backgroundImage = 'url("/contenidos/system/modules/com.fti.camaragijon/templates/res/css/imgs/colDcha.png")';
	}
}

/**
 * Alarga el contenido de las paginas hasta llegar al pie, que permance fijo
 * param id: identificadores de los bloques a alargar separados por '|'. Solamente alarga el primero que exista
 */
function alargaContenido(id)
{
	if ($('pie')) {
		var ids = id.split('|');
		for (i=0; i<ids.length; i++) {
	
			if ($(ids[i])) {
				var total = document.documentElement.clientHeight;
				var posCuerpo = $(ids[i]).offsetTop;
				var altoCuerpo = $(ids[i]).scrollHeight;
				var altoPie = $('pie').clientHeight;
				
				var newAltoCuerpo = total - posCuerpo - altoPie;
				
				if (altoCuerpo <= newAltoCuerpo)
				{
					$(ids[i]).style.height = newAltoCuerpo + 'px';
				}
				else {
					$(ids[i]).style.height = 'auto';
					$(ids[i]).style.paddingBottom = altoPie + 'px';
				}
				
				return;
			}
		}
	}
}


/**
 * Funcionalidad para mostrar/ocultar el menu de la cabecera del usuario autenticado
 */
function initMiMenu() {
	$('mostrarMiMenu').onmouseover = muestraMenu;
	$('mostrarMiMenu').onmouseout = ocultaMenusRetardo;
	$('mimenu').onmouseover = cancelaOcultar;
	$('mimenu').onmouseout = ocultaMenusRetardo;
}
function muestraMenu() {
	$('mimenu').style.display = 'block';
}
function ocultaMenu() {
	$('mimenu').style.display = 'none';
}
var intervalTimeout;
function ocultaMenusRetardo() {
	intervalTimeout = setTimeout('ocultaMenu()', 500);
}
function cancelaOcultar() {
	clearInterval(intervalTimeout);
}

/**
 * Rellena el formulario indicado con los valores indicados.
 * Forma de uso:
 * var errores = {
 *   campo1 : 'valor1',
 *   campo2 : 'valor2';
 * }
 * rellenaFormulario('myFormId', 'errores');
 * param idForm: identificador del formulario
 * param newValues: nombre del objeto que contiene los nuevos valores
 */
function rellenaFormulario(idForm, newValues)
{
	var campos = $(idForm).elements;

	for (i=0; i<campos.length; i++)
	{
		if (campos[i].tagName == 'INPUT' && (campos[i].type == 'radio' || campos[i].type == 'checkbox')) {
			campos[i].checked = false;
			if (eval(newValues + '.' + campos[i].name)) 
			{
				var values = eval(newValues + '.' + campos[i].name).split('|');
				for (j=0; j<values.length; j++)
					if (campos[i].value == values[j]) campos[i].checked = true;
			}
		}
		else if (eval(newValues + '.' + campos[i].name)) 
			campos[i].value = eval(newValues + '.' + campos[i].name);
	}
}


/**
 * Huevo de pascua
 */
var developed = {

	f : false,
	t : false,
	i : false,
	
	press : function(e)
	{
		evt = e ? e : event;
		tcl = (window.Event) ? evt.which : evt.keyCode;
		switch (tcl) {
			case 70: this.f = true; break;
			case 84: this.t = true; break;
			case 73: this.i = true; break;
		}
		
		if (this.f && this.t && this.i) {
			Staff.show();
			this.f = false;
			this.t = false;
			this.i = false;
		}
	},
	
	release : function(e)
	{
		evt = e ? e : event;
		tcl = (window.Event) ? evt.which : evt.keyCode;
		switch (tcl) {
			case 70: this.f = false; break;
			case 84: this.t = false; break;
			case 73: this.i = false; break;
		}
	}
}
addEvent(document, 'keydown', developed.press);
addEvent(document, 'keyup', developed.release);


var Staff = {
	
	visible : false,
	
	show : function()
	{
		if (!this.visible)
		{
			if (!$('fondoStaff'))
			{
				var div = document.createElement('DIV');
				div.setAttribute('id', 'fondoStaff');
				div.style.height = document.body.clientHeight+'px';
				div.onclick = function() { Staff.close(); }
				document.body.appendChild(div);
			}
			else {
				$('fondoStaff').style.display = 'block';
			}
			
			if (!$('frameStaff'))
			{
				var frame = document.createElement('IFRAME');
				frame.setAttribute('id', 'frameStaff');
				frame.src = '/contenidos/system/modules/com.fti.camaragijon/templates/staff.html';
				frame.width = '600px';
				frame.height = '295px';
				frame.frameBorder = '0';
				frame.style.left = ((document.body.clientWidth - 500) / 2) + 'px';
				document.body.appendChild(frame);
				setTimeout('Staff.resize()', 200)
			}
			else {
				$('frameStaff').style.display = 'block';
			}
			
			this.visible = true;
		}
	},
	
	close : function()
	{
		if (this.visible)
		{
			$('fondoStaff').style.display = 'none';
			$('frameStaff').style.display = 'none';
			this.visible = false;
		}
	},
	
	resize : function()
	{
		$('frameStaff').height = ($('frameStaff').contentDocument.body.scrollHeight + 5) + 'px';
	}
}


/**
 * Crea una listado de secciones en pestañas
 */
var Pestanas = {
	
	listado : 'pestanias',
	contenido : 'contenido_pestania',
	
	init : function (idListado, idContenido)
	{
		Pestanas.listado = $$(idListado);
		Pestanas.contenido = $$(idContenido);
		
		Pestanas.listado.className += ' pestanias';
		var secciones = Pestanas.listado.childNodes;
		for (i=0; i<secciones.length; i++) {
			var trozos = secciones[i].childNodes;
			var siguiente = false;
			for (j=0; j<trozos.length; j++)
				if (trozos[j].tagName)
				{
					if (siguiente) {
						trozos[j].style.display = 'none';
						Pestanas.contenido.appendChild( trozos[j] );
						break;
					}
					siguiente = true;
				}
		}
		
		var h3s = Pestanas.listado.getElementsByTagName('H3');
		for (i=0; i<h3s.length; i++) {
			h3s[i].style.cursor = 'pointer';
		}
		Pestanas.muestra(0);
	},
	
	muestra : function (seccion)
	{
		var lis = Pestanas.listado.getElementsByTagName('LI')
		for (i=0; i<lis.length; i++) {
			if (i == seccion) lis[i].className = 'selected';
			else lis[i].className = '';
		}
		
		var c = -1;
		var secciones = Pestanas.contenido.childNodes;
		for (i=0; i<secciones.length; i++)
			if (secciones[i].tagName)
			{
				c++;
				if (c == seccion)
					secciones[i].style.display = 'block';
				else
					secciones[i].style.display = 'none';
			}
	},
	
	size : function()
	{
		return Pestanas.listado.getElementsByTagName('H3').length;
	}
}