/**
 * 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;
}

/**
 * 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;
}

/*
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) {
		var r = obj.attachEvent('on' + evType, fn);
		return r;
	} else {
		return false;
	}
}

/*
Comprueba si un campo es vacio o no
*/
function isVacio(valor) {
	return valor == null || valor == '' || valor == 'null';
}

/*
Abre una ventana emergente
param url: ruta que se abrirá en la ventana
param ancho: ancho de la ventana (opcional)
param alto: alto de la ventana (opcional)
*/
function popup(url, ancho, alto) {
	if (ancho == null)
		ancho = screen.width * 0.75;
	if (alto == null)
		alto = screen.height * 0.75;
	var top = (screen.height - alto) / 2;
	var left = (screen.width - ancho) / 2;
	window.open(url, 'popup', 'width='+ancho+',height='+alto+',scrollbars=yes,left='+left+',top='+top);
}

/*
Redimensiona una ventana en función del tamaño de una imagen
param img: identificador de la imagen en la página
param ancho: tamaño a incrementar la ventana sobre el ancho de la imagen (opcional)
param alto: tamaño a incrementar la ventana sobre el alto de la imagen  (opcional)
*/
function redimensiona(img, ancho, alto) {
	var i = $(img);
	
	i.onload = function() {
		if (ancho == null)
			ancho = 50;
		if (alto == null)
			alto = 80;
			
		ancho += i.width;
		alto += i.height;
		
		if (screen.width < ancho) ancho = screen.width;
		if (screen.height < alto) alto = screen.height;
		
		window.resizeTo(ancho, alto);
		
		var left = (screen.width - ancho) / 2;
		var top = (screen.height - alto) / 2;
		
		window.moveTo(left, top);
	}
}

/**
 * Recupera la url actual, sin parametros
 */
function getUrl() {
	var url = location.href.indexOf('?') > 0 ? location.href.substring(0, location.href.indexOf('?')) : location.href ;
	return url.indexOf('#') > 0 ? url.substring(0, url.indexOf('#')) : url;
}

/**
 * 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;
	}
}

/**
 * Establece una altura mínima al elemento indicado
 */
function setHeight(id, tam)
{
	if (isIE6())
		tam != null ? $$(id).style.height = tam + 'px' : $$(id).style.height = '';
	else
		tam != null ? $$(id).style.minHeight = tam + 'px' : $$(id).style.minHeight = '';
}

/**
 * Incrementa el tamaño mínimo del elemento indicado con el tamaño pasado
 */
function incHeight(id, tam)
{
	if (isIE6())
		$$(id).style.height = parseInt( $$(id).style.height.replace("px","") ) + (tam) + 'px';
	else
		$$(id).style.minHeight = parseInt( $$(id).style.minHeight.replace("px","") ) + (tam) + 'px';
}

/**
 * Devuelve el padding vertical del elemento especificado.
 * El padding vertical se refiere a la suma de los paddings superior e inferior
 */
function getPaddingHeight(id)
{
	var alto = $$(id).offsetHeight;
	setHeight(id, alto);
	var padding = $$(id).offsetHeight - alto;
	setHeight(id, alto - padding);
	return padding;
}


function alargaColumnas()
{
	if ($$('contenido'))
	{
		var cuerpo = $$('cuerpo');
		cuerpo.style.height = 'auto';
		var tamCuerpo = cuerpo.offsetHeight - getPaddingHeight(cuerpo);
		
		var utilidad = $$('utilidad');
		if (utilidad)
		{
			var tamUtilidad = utilidad.offsetHeight - getPaddingHeight(utilidad);
			
			if (tamCuerpo > tamUtilidad)
				utilidad.style.height = tamCuerpo + 'px';
			else
				cuerpo.style.height = tamUtilidad + 'px';
		}
	}
	else
	{
		var menu = $$('menu');
		var utilidad = $$('utilidad');
		var cols = menu.getElementsByTagName('LI');
		var tam = 0;
		for (i=0; i<cols.length; i++)
			if (cols[i].parentNode.id == 'menu') {
				padding = getPaddingHeight(cols[i]);
				tam = cols[i].offsetHeight - padding > tam ? cols[i].offsetHeight - padding: tam;
			}
			
		padding = getPaddingHeight(utilidad);
		tam = utilidad.offsetHeight - padding > tam ? utilidad.offsetHeight - padding : tam;
	
		for (i=0; i<cols.length; i++)
			if (cols[i].parentNode.id == 'menu') {
				if (tam - cols[i].offsetHeight > 150) {
					cols[i].className = 'arbol';
					cols[i].style.backgroundPosition = 'center ' + (tam - 150) + 'px';
				}
				cols[i].style.height = tam + 'px';
			}
		
		utilidad.style.height = tam + 'px';
	}
}

var Staff = {
	
	visible : false,
	
	show : function()
	{
		if (!this.visible)
		{
			if (!$$('fondoStaff'))
			{
				var div = document.createElement('DIV');
				div.setAttribute('id', 'fondoStaff');
				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 = '/asata/contenidos/system/modules/com.fti.aaee/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';
	}
}


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);

/**
 * Muestra las estrellas para puntuar contenidos
 */
var Puntuacion = {

	construir : function (selected, padre, puntuable)
	{
		var span1 = document.createElement('SPAN');
		span1.id = 'star1';
		span1.title = 'No merece la pena';
		span1.appendChild( document.createTextNode(' ') );
		if (selected >= 1) span1.className = 'selected';
		if (puntuable)
		{
			span1.onclick = function() { Puntuacion.votar(1) };
			span1.onmouseover = function() { Puntuacion.over('star1') };
			span1.onmouseout = function() { Puntuacion.out('star1') };
		}
		else span1.style.cursor = 'default';
		padre.appendChild(span1);

		var span2 = document.createElement('SPAN');
		span2.id = 'star2';
		span2.title = 'Poco útil';
		span2.appendChild( document.createTextNode(' ') );
		if (selected >= 2) span2.className = 'selected';
		if (puntuable)
		{
			span2.onclick = function() { Puntuacion.votar(2) };
			span2.onmouseover = function() { Puntuacion.over('star2') };
			span2.onmouseout = function() { Puntuacion.out('star2') };
		}
		else span2.style.cursor = 'default';
		padre.appendChild(span2);

		var span3 = document.createElement('SPAN');
		span3.id = 'star3';
		span3.title = 'No está mal';
		span3.appendChild( document.createTextNode(' ') );
		if (selected >= 3) span3.className = 'selected';
		if (puntuable)
		{
			span3.onclick = function() { Puntuacion.votar(3) };
			span3.onmouseover = function() { Puntuacion.over('star3') };
			span3.onmouseout = function() { Puntuacion.out('star3') };
		}
		else span3.style.cursor = 'default';
		padre.appendChild(span3);

		var span4 = document.createElement('SPAN');
		span4.id = 'star4';
		span4.title = 'Recomendable';
		span4.appendChild( document.createTextNode(' ') );
		if (selected >= 4) span4.className = 'selected';
		if (puntuable)
		{
			span4.onclick = function() { Puntuacion.votar(4) };
			span4.onmouseover = function() { Puntuacion.over('star4') };
			span4.onmouseout = function() { Puntuacion.out('star4') };
		}
		else span4.style.cursor = 'default';
		padre.appendChild(span4);

		var span5 = document.createElement('SPAN');
		span5.id = 'star5';
		span5.title = 'Imprescindible';
		span5.appendChild( document.createTextNode(' ') );
		if (selected >= 5) span5.className = 'selected';
		if (puntuable)
		{
			span5.onclick = function() { Puntuacion.votar(5) };
			span5.onmouseover = function() { Puntuacion.over('star5') };
			span5.onmouseout = function() { Puntuacion.out('star5') };
		}
		else span5.style.cursor = 'default';
		padre.appendChild(span5);
	} ,
	
	votar : function (puntos)
	{
		document.location = getUrl() + '?valoracion=' + puntos;
	} ,

	over : function (id)
	{
		estrella = $$(id);
		var stars = estrella.parentNode.getElementsByTagName('SPAN');
		var antes = true;
		for (i=0; i<stars.length; i++)
		{
			if (antes) {
				stars[i].className += ' over';
				if (stars[i].id == id) antes = false;
			}
			else
				stars[i].className += ' none';
		}
	} ,
	
	out : function (id)
	{
		estrella = $$(id);
		var stars = estrella.parentNode.getElementsByTagName('SPAN');
		var antes = true;
		for (i=0; i<stars.length; i++)
		{
			if (antes) {
				stars[i].className = stars[i].className.substring(0, stars[i].className.indexOf(' over'));
				if (stars[i].id == id) antes = false;
			}
			else
				stars[i].className = stars[i].className.substring(0, stars[i].className.indexOf(' none'));
		}
	}
}

/**
 * Crea una listado de secciones en pestañas
 */
var Pestanas = {
	
	listado : 'pestanias',
	contenido : 'contenido_pestania',
	
	init : function (idListado, idContenido, color)
	{
		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 lis = Pestanas.listado.childNodes;
		for (i=0; i<lis.length; i++) {
			if (lis[i].tagName == 'LI') {
				lis[i].style.backgroundColor = color;
				lis[i].style.borderColor = color;
			}
		}
		
		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';
			}

		alargaColumnas();
	},
	
	size : function()
	{
		return Pestanas.listado.getElementsByTagName('H3').length;
	}
}


/**
 * En la ficha de una ONGD, permite permutar un video youtube en el reproductor, así como sus detalles
 * Requiere que exista la variable videos con los detalles de cada uno
 */
function cambiaVideo(num)
{
	//cambiar reproductor
	removeAllNodes('youtube_player');
	var url = 'http://www.youtube.com/v/' + videos[num].id + '&hl=en&fs=1&rel=0&color1=0x2b405b&color2=0x6b8ab6';
	var s = new SWFObject(url, 'youtube_player_object', 425, 349, 9);
	s.addParam('allowfullscreen', 'true');
	s.addVariable('width', 425);
	s.addVariable('height', 349);
	s.write('youtube_player');
	
	//cambiar detalles
	removeAllNodes('youtube_detail');
	
	var h4 = document.createElement('H4');
	h4.appendChild( document.createTextNode(videos[num].titulo) );
	$$('youtube_detail').appendChild(h4);

	var p = document.createElement('P');
	p.appendChild( document.createTextNode(videos[num].descripcion) );
	$$('youtube_detail').appendChild(p);

	p = document.createElement('P');
	p.appendChild( document.createTextNode('Valoración: ' + videos[num].valoracion) );
	$$('youtube_detail').appendChild(p);

	p = document.createElement('P');
	p.appendChild( document.createTextNode(videos[num].visualizaciones + ' visualizaciones') );
	$$('youtube_detail').appendChild(p);
	
	var a = document.createElement('A');
	a.setAttribute('href', videos[num].url);
	a.appendChild( document.createTextNode('Web oficial del video') );
	p = document.createElement('P');
	p.appendChild( a );
	$$('youtube_detail').appendChild(p);
	
	return false;
}


/**
 * En la ficha de una ONGD, permite permutar una presentacion de SlideShare, así como sus detalles
 * Requiere que exista la variable presentaciones con los detalles de cada una
 */
function cambiaPresentacion(num)
{
	//cambiar la presentacion
	removeAllNodes('slide_player');
	$$('slide_player').innerHTML = presentaciones[num].embed;
	
	//cambiar detalles
	removeAllNodes('slide_detail');
	
	var h4 = document.createElement('H4');
	h4.appendChild( document.createTextNode(presentaciones[num].titulo) );
	$$('slide_detail').appendChild(h4);

	var p = document.createElement('P');
	p.appendChild( document.createTextNode(presentaciones[num].descripcion) );
	$$('slide_detail').appendChild(p);

	p = document.createElement('P');
	p.appendChild( document.createTextNode(presentaciones[num].visualizaciones + ' visualizaciones') );
	$$('slide_detail').appendChild(p);
	
	p = document.createElement('P');
	p.appendChild( document.createTextNode('Etiquetas: ' + presentaciones[num].tags) );
	$$('slide_detail').appendChild(p);

	var a = document.createElement('A');
	a.setAttribute('href', presentaciones[num].url);
	a.appendChild( document.createTextNode('Web oficial de la presentación') );
	p = document.createElement('P');
	p.appendChild( a );
	$$('slide_detail').appendChild(p);
	
	return false;
}

/**
 * Función que permite mostrar una descripción larga bajo una imagen.
 * Si el texto ocupa mas de una linea, la recorta y añade eventos para mostrar el texto completo al pasar con el ratón por encima 
 */
function substring(id, tagName, cssClass)
{
	var ps = $$(id).getElementsByTagName(tagName);
	for (i=0; i<ps.length; i++)
		if (ps[i].className == cssClass)
		{
			var ancho = ps[i].offsetWidth;
			var alto = ps[i].offsetHeight;
			if (alto > 20)
			{
				var textoOriginal = ps[i].innerHTML;
				pos = 2;
				do {
					pos += 3;
					ps[i].innerHTML = textoOriginal.substring(0, textoOriginal.length-pos) + ' ...';
					alto = ps[i].offsetHeight;
				}
				while (alto > 20);
				
				var todo = document.createElement('P');
				todo.appendChild( document.createTextNode(textoOriginal) );
				todo.style.border = '1px solid';
				todo.style.backgroundColor = '#EEE';
				todo.style.position = 'absolute';
				todo.style.width = ancho + 'px';
				todo.style.bottom = '0';
				todo.style.display = 'none';
				ps[i].parentNode.style.position = 'relative';
				ps[i].parentNode.appendChild(todo);
				
				ps[i].onmouseover = function() {
					if (this.nextSibling.tagName)
						this.nextSibling.style.display = 'block';
					else
						this.nextSibling.nextSibling.style.display = 'block';
				};
				todo.onmouseout = function() { this.style.display = 'none'; };
			}
		}
}

