

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Gestión de la altura de las columas en Sección
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Esta función devuelve el código HTML que pintará el enlace "Leer más", a partir del enlace pasado como parámetro.
function getLinkReadMore(enlace){
	return "<a href='" + enlace + "' class='leer' title='Leer M&aacute;s'>...</a>";
}

//Esta función quita la última palabra completa del texto.
function quitarUltimaPalabra(texto){
	if ((texto != null && texto.length > 0)){
		posicion = texto.lastIndexOf(" ", texto.length);
		texto = texto.substring(0, posicion);
	}
	return texto;
}
// Quitamos el borde de la ultima noticia secundaria
function quitarBorderBottom(noticias){
	if (noticias.length > 0){
		var ultimaSecundaria = noticias[noticias.length - 1];
		ultimaSecundaria.style.borderBottom = "none";
	}	
}
//Esta función recorre cada noticia contenida en noticias y las va reduciendo los caracteres.
//alturaMax: Indica la altura en pixels.
//longitudMax: Indica la longitud máxima de la noticia en caracteres.
//enlaces: Enlaces a los detalles de las noticias.
function reducirNoticias(noticias, capaPadre, alturaMax, longitudMax, enlaces, tipoComparacion, tagLess){

	jQuery.each(noticias, function(i) {
	   //Se procesará cada una de las noticias que vienen por parámetro
	   reducirNoticia(this, capaPadre, alturaMax, longitudMax, enlaces[i], tipoComparacion, tagLess);
	});		
}

//Esta función permite reducir la altura (o número de caracteres) de la noticia.
//Para ello irá eliminando caracteres de la capa hasta que la altura sea la alturaMax.
//Añadirá al final el enlace "Leer más"
//noticia: Capa de la que se irán eliminando caracteres.
//alturaMax: Indica la altura en pixels.
//longitudMax: Indica la longitud máxima de la noticia en caracteres.
//enlace: Enlace al detalle de la noticia.
function reducirNoticia(noticia, capaPadre, alturaMax, longitudMax, enlace, tipoComparacion, tagLess){
	dom_noticia = jQuery(noticia);								//Obtenemos el elemento que contendrá el texto a recortar
	enlaceLeerMas = getLinkReadMore(enlace);			//Obtenemos el enlace "Leer más"
	textoARecortar = getTexto(dom_noticia[0]);		//Obtenemos el texto que se irá recortando para ajustar la altura del elemento capaAlumno
   	
   	//Quitamos el código HTML de la noticia, así comparamos texto real.
	if (tagLess){
		textoARecortar = getTagLess(textoARecortar);
		setTexto(dom_noticia[0], textoARecortar);
		tagLess = !tagLess;	//Cambiamos el signo para que no lo haga de nuevo.		
	}
   	
  	//Recortarmos el texto, si se excede en la longitud máxima y su altura también.
  	if (capaPadre != null){
  		//Si hemos pasado la capa padre -> es porque queremos usarla para comparar las alturas
	  	if ((capaPadre.height() > alturaMax) || (textoARecortar.length > longitudMax)){
	
	  		dom_noticia[0] = setTexto(dom_noticia[0], textoARecortar + enlaceLeerMas); 		   	//Se incluye por defecto en enlace a "Leer más"	
	  		dom_noticia = recortarTexto(dom_noticia, capaPadre, alturaMax, longitudMax, enlaceLeerMas, tipoComparacion, tagLess);
	  	}  		
  	} else{
	  	if ((dom_noticia[0].clientHeight > alturaMax) || (textoARecortar.length > longitudMax)){
	
	  		dom_noticia[0] = setTexto(dom_noticia[0], textoARecortar + enlaceLeerMas); 		   	//Se incluye por defecto en enlace a "Leer más"	
	  		dom_noticia = recortarTexto(dom_noticia, capaPadre, alturaMax, longitudMax, enlaceLeerMas, tipoComparacion, tagLess);
	  	}  		
  	}

}

function getTagLess(texto){
	 var strTagLess = texto.replace(/(<([^>]+)>)/ig,"");
	 	 
	 return strTagLess; 
}

function recortarTexto(dom_noticia, capaPadre, alturaMax, longitudMax, enlaceLeerMas, tipoComparacion, tagLess){
	//Habrá que ir validando la altura de la capaRecortable
	//Si se establece la altura por defecto entonces esta solo afectará a la capa recortable
	
	textoARecortar = getTexto(dom_noticia[0]);		//Obtenemos el texto que se irá recortando para ajustar la altura del elemento capaAlumno
	if (tagLess){
		//No debería ejecutarse esté código, ya que en la llamada tagLess se ejecuta y se niega.
		textoARecortar = getTagLess(textoARecortar);
		setTexto(dom_noticia[0], textoARecortar);
	}
		
	if (tipoComparacion == "AND"){
		
		if (capaPadre != null){
			while ((capaPadre.height() > alturaMax) && (textoARecortar.length > longitudMax)) {
				textoARecortar = quitarUltimaPalabra(textoARecortar);
		     
		    	//Añadimos el texto reducido más el enlace "Leer más" a la capa recortable,
		   	 	//de esta forma la altura de la capaCambiante se verá reducida.
		    	dom_noticia[0] = setTexto(dom_noticia[0], textoARecortar + enlaceLeerMas);
		  	}		
		} else {
			while ((dom_noticia[0].clientHeight > alturaMax) && (textoARecortar.length > longitudMax)) {
				textoARecortar = quitarUltimaPalabra(textoARecortar);
		     
		    	//Añadimos el texto reducido más el enlace "Leer más" a la capa recortable,
		   	 	//de esta forma la altura de la capaCambiante se verá reducida.
		    	dom_noticia[0] = setTexto(dom_noticia[0], textoARecortar + enlaceLeerMas);
		  	}					
		}

	} else{
		
		if (capaPadre != null){
			while ((capaPadre.height() > alturaMax) || (textoARecortar.length > longitudMax)) {
				textoARecortar = quitarUltimaPalabra(textoARecortar);
		     
		    	//Añadimos el texto reducido más el enlace "Leer más" a la capa recortable,
		   	 	//de esta forma la altura de la capaCambiante se verá reducida.
		    	dom_noticia[0] = setTexto(dom_noticia[0], textoARecortar + enlaceLeerMas);
		  	}
		} else {
			while ((dom_noticia[0].clientHeight > alturaMax) || (textoARecortar.length > longitudMax)) {
				textoARecortar = quitarUltimaPalabra(textoARecortar);
		     
		    	//Añadimos el texto reducido más el enlace "Leer más" a la capa recortable,
		   	 	//de esta forma la altura de la capaCambiante se verá reducida.
		    	dom_noticia[0] = setTexto(dom_noticia[0], textoARecortar + enlaceLeerMas);
		  	}				
		}

	}

  
	reconstruirHTML(textoARecortar, longitudMax);
	
	//Una vez hemos ajustado el texto, quitaremos la última palabra completa del texto que se ha ido recortando.
	//De esta forma no sale una palabra cortada por la mitad.
	textoARecortar = quitarUltimaPalabra(textoARecortar);
	  
	dom_noticia[0].innerHTML = textoARecortar + enlaceLeerMas;  
	
	var pes = dom_noticia[0].getElementsByTagName("p");

	if (pes.length > 0) {
		//Añadimos el estilo inline para juntar los puntos suspensivos con el último párrafo (p)
		var ultimoP = pes[pes.length-1];
		ultimoP.style.display = "inline"
	}
  
  	return dom_noticia;
}

//Esta función usa la librería cutstring.js para reconstruir el código HTML del parámetro textoARecortar.
//El parámetro longitudMax indica la longitud a partir de la cual la librería deberá recortar el texto.
function reconstruirHTML(textoARecortar, longitudMax){
	//Si el texto que queda despues de recortar la noticia es mayor, entonces le aplicamos el proceso con la longitud por defecto.
	if (textoARecortar.length > longitudMax){
		textoARecortar = cutKeepingHTML(textoARecortar, longitudMax);
	} else{
		//Le pasamos el proceso que corta manteniendo coherente el HTML
		//por si acaso hemos cortado un elemento mal.
		textoARecortar = cutKeepingHTML(textoARecortar, textoARecortar.length);
	}
	
	return textoARecortar;
}

//Obtiene el innerHTML del objetoDOM
function getTexto(objetoDOM){
	if (objetoDOM != null)
		return objetoDOM.innerHTML;
	else return "";
}

//Escribe el texto pasado por parámetro en innerHTML del objetoDOM
function setTexto(objetoDOM, texto){
	if (objetoDOM != null){
		objetoDOM.innerHTML = texto;
		return objetoDOM;
	} else return objetoDOM;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Esta función usa la librería cutstring.js
//Esta función permite cortar el texto y completando el HTML,
//de forma que no deje tags HTML incompletas.
//textoACortar: Es el texto que se va a cortar.
//porDonde: indica por donde se cortará el texto. Índice de la posición a partir de la que cortará el texto.
//Si en la posición de corte encuentra un tag HTML que se verá afectado, adelantará la posición de corte.
//La función devuelve el texto cortado.
function cutKeepingHTML(textoACortar, porDonde){
	output = new CutString(textoACortar, porDonde);
	return output.cut();
}
		    
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		    
/** 
#  * Copyright (c) 2008 Pasyuk Sergey (www.codeasily.com) 
#  * Licensed under the MIT License: 
#  * http://www.opensource.org/licenses/mit-license.php 
#  *  
#  * Splits a <ul>/<ol>-list into equal-sized columns. 
#  *  
#  * Requirements:  
#  * <ul> 
#  * <li>"ul" or "ol" element must be styled with margin</li> 
#  * </ul> 
#  *  
#  * @see http://www.codeasily.com/jquery/multi-column-list-with-jquery 
#  */  
jQuery.fn.makeacolumnlists = function(settings){
	settings = jQuery.extend({
		cols: 2,				// set number of columns
		colWidth: 0,			// set width for each column or leave 0 for auto width
		equalHeight: false, 	// can be false, 'ul', 'ol', 'li'
		startN: 1				// first number on your ordered list
	}, settings);

	if(jQuery('> li', this)) {
		this.each(function(y) {
			var y=jQuery('.li_container').size(),
		    	height = 0, 
		        maxHeight = 0,
				t = jQuery(this),
				classN = t.attr('class'),
				listsize = jQuery('> li', this).size(),
				percol = Math.ceil(listsize/settings.cols),
				contW = t.width(),
				bl = ( isNaN(parseInt(t.css('borderLeftWidth'),10)) ? 0 : parseInt(t.css('borderLeftWidth'),10) ),
				br = ( isNaN(parseInt(t.css('borderRightWidth'),10)) ? 0 : parseInt(t.css('borderRightWidth'),10) ),
				pl = parseInt(t.css('paddingLeft'),10),
				pr = parseInt(t.css('paddingRight'),10),
				ml = parseInt(t.css('marginLeft'),10),
				mr = parseInt(t.css('marginRight'),10),
				col_Width = Math.floor((contW - (settings.cols-1)*(bl+br+pl+pr+ml+mr))/settings.cols);
			if (settings.colWidth) {
				col_Width = settings.colWidth; 
			}
			var colnum=1,
				percol2=percol;
			jQuery(this).addClass('li_cont1').wrap('<div id="li_container' + (++y) + '" class="li_container"></div>');
			for (var i=0; i<=listsize; i++) {
				if(i>=percol2) { percol2+=percol; colnum++; }
				var eq = jQuery('> li:eq('+i+')',this);
				eq.addClass('li_col'+ colnum);
				if(jQuery(this).is('ol')){eq.attr('value', ''+(i+settings.startN))+'';}
			}
			jQuery(this).css({cssFloat:'left', width:''+col_Width+'px'});
			for (colnum=2; colnum<=settings.cols; colnum++) {
				if(jQuery(this).is('ol')) {
					jQuery('li.li_col'+ colnum, this).appendTo('#li_container' + y).wrapAll('<ol class="li_cont'+colnum +' ' + classN + '" style="float:left; width: '+col_Width+'px;"></ol>');
				} else {
					jQuery('li.li_col'+ colnum, this).appendTo('#li_container' + y).wrapAll('<ul class="li_cont'+colnum +' ' + classN + '" style="float:left; width: '+col_Width+'px;"></ul>');
				}
			}
			if (settings.equalHeight=='li') {
				for (colnum=1; colnum<=settings.cols; colnum++) {
				    jQuery('#li_container'+ y +' li').each(function() {
				        var e = jQuery(this);
				        var border_top = ( isNaN(parseInt(e.css('borderTopWidth'),10)) ? 0 : parseInt(e.css('borderTopWidth'),10) );
				        var border_bottom = ( isNaN(parseInt(e.css('borderBottomWidth'),10)) ? 0 : parseInt(e.css('borderBottomWidth'),10) );
				        height = e.height() + parseInt(e.css('paddingTop'), 10) + parseInt(e.css('paddingBottom'), 10) + border_top + border_bottom;
				        maxHeight = (height > maxHeight) ? height : maxHeight;
				    });
				}
				for (colnum=1; colnum<=settings.cols; colnum++) {
					var eh = jQuery('#li_container'+ y +' li');
			        var border_top = ( isNaN(parseInt(eh.css('borderTopWidth'),10)) ? 0 : parseInt(eh.css('borderTopWidth'),10) );
			        var border_bottom = ( isNaN(parseInt(eh.css('borderBottomWidth'),10)) ? 0 : parseInt(eh.css('borderBottomWidth'),10) );
					mh = maxHeight - (parseInt(eh.css('paddingTop'), 10) + parseInt(eh.css('paddingBottom'), 10) + border_top + border_bottom );
			        eh.height(mh);
				}
			} else 
			if (settings.equalHeight=='ul' || settings.equalHeight=='ol') {
				for (colnum=1; colnum<=settings.cols; colnum++) {
				    jQuery('#li_container'+ y +' .li_cont'+colnum).each(function() {
				        var e = jQuery(this);
				        var border_top = ( isNaN(parseInt(e.css('borderTopWidth'),10)) ? 0 : parseInt(e.css('borderTopWidth'),10) );
				        var border_bottom = ( isNaN(parseInt(e.css('borderBottomWidth'),10)) ? 0 : parseInt(e.css('borderBottomWidth'),10) );
				        height = e.height() + parseInt(e.css('paddingTop'), 10) + parseInt(e.css('paddingBottom'), 10) + border_top + border_bottom;
				        maxHeight = (height > maxHeight) ? height : maxHeight;
				    });
				}
				for (colnum=1; colnum<=settings.cols; colnum++) {
					var eh = jQuery('#li_container'+ y +' .li_cont'+colnum);
			        var border_top = ( isNaN(parseInt(eh.css('borderTopWidth'),10)) ? 0 : parseInt(eh.css('borderTopWidth'),10) );
			        var border_bottom = ( isNaN(parseInt(eh.css('borderBottomWidth'),10)) ? 0 : parseInt(eh.css('borderBottomWidth'),10) );
					mh = maxHeight - (parseInt(eh.css('paddingTop'), 10) + parseInt(eh.css('paddingBottom'), 10) + border_top + border_bottom );
			        eh.height(mh);
				}
			}
		    jQuery('#li_container' + y).append('<div style="clear:both; overflow:hidden; height:0px;"></div>');
		});
	}
}

jQuery.fn.uncolumnlists = function(){
	jQuery('.li_cont1').each(function(i) {
		var onecolSize = jQuery('#li_container' + (++i) + ' .li_cont1 > li').size();
		if(jQuery('#li_container' + i + ' .li_cont1').is('ul')) {
			jQuery('#li_container' + i + ' > ul > li').appendTo('#li_container' + i + ' ul:first');
			for (var j=1; j<=onecolSize; j++) {
				jQuery('#li_container' + i + ' ul:first li').removeAttr('class').removeAttr('style');
			}
			jQuery('#li_container' + i + ' ul:first').removeAttr('style').removeClass('li_cont1').insertBefore('#li_container' + i);
		} else {
			jQuery('#li_container' + i + ' > ol > li').appendTo('#li_container' + i + ' ol:first');
			for (var j=1; j<=onecolSize; j++) {
				jQuery('#li_container' + i + ' ol:first li').removeAttr('class').removeAttr('style');
			}
			jQuery('#li_container' + i + ' ol:first').removeAttr('style').removeClass('li_cont1').insertBefore('#li_container' + i);
		}
		jQuery('#li_container' + i).remove();
	});
}