/*
..........................................................................
:: Menus desplegables de n-niveles                                      ::
..........................................................................
*/

$(document).ready(function() { // Prepara eventos del menú
    var menus = $("#menu ul ul");
	menus.hide();
    menus.parent()
	    .mouseout( function() { pliega(this)      })
        .mouseover(function() { rompePliega(this) })
	$("#menu a").focus( function() { despliega(this) })
	            .click( function() { despliega(this) });
    $("#menu li:last-child").addClass("ultimo");
});

function despliega(link) {
    $("#menu li > ul").parent().css({zIndex: 1});
	// ocultar los hermanos
	$(link).parent("li")
	    .siblings()
		    .children("a").removeClass("activo").siblings("ul").hide();
	//mostrar el que toca
    $(link).parent().css({
		zIndex: 1000
    }).children("ul:hidden").show(200).siblings("a").addClass("activo");
}

function pliega(padre) {
    padre.temporizador = setTimeout(function() {
		$(padre).children("a").removeClass("activo");
        $(padre).children("ul").hide(200);
    }, 600)
}

function rompePliega(padre) {
	if (!padre.temporizador) return false;
    clearTimeout(padre.temporizador);
}


/* Decoracion para menuDestacados */
$(function() {
	$('ul.menuDestacados li:has(img)').append('<div class="decoDestacados"></div>')
});

// DESPLEGABLES MULTIFUNCION
function asignPanelEvents(container) {
	// when container is passed as a parameter, the function will only assign
	// events depending on container:
	// if container is a DOM element, inside that DOM element
	// if container is a string, inside the element(s) matching the jQuery
	// selector
	
	// we find the showPanel buttons and links
	var $c     = container ? $(container) : document,
		$show  = $('a,button', $c).filter('.showPanel'),
		$panel = $('.panel',$c);
		
	$show.each( function(index) {
		// for each one of the $show buttons we find their hidePanel counterparts
		var $this      = $(this),
			$thisPanel = $panel.eq(index),
			$hide      = $this.siblings('.hidePanel').add( $thisPanel.find('a,button').filter('.hidePanel') );
			
		if ($thisPanel.hasClass('shown')) {
			if ($hide.length) {
				$this.hide();
			} else {
				$this.addClass('js-active');
			}
			$thisPanel.show();
			$hide.show();
		} else {
			$this.show();
			$thisPanel.hide();
			$hide.hide();
		}
		
		$this.click( function() {
			$thisPanel.slideToggle('fast');
			if ($hide.length) {
				$this.toggle();
				$hide.toggle();
			} else {
				$this.addClass('js-active');
			}
			return false;
		});
		
		$hide.click( function() {
			$this.click();
			return false;
		});
	});
}

function createTabs(container) {
	$('div.contenedorPestanyas', container || document).each( function() {
		var $c = $(this),
			$li = $c.children('ul').find('li'),
			$div = $c.children('div'),
			$shown = $div.filter('.shown');
		// preparamos el contenido
		// si hay un numero de elementos distinto a 1 (por algun error u omision)
		// los reseteamos y se lo ponemos solo al primero
		if (1 != $shown.length) {
			$shown.removeClass('shown');
			$shown = $div.eq(0).addClass('shown');
		}
		// ocultamos todos excepto el que toca
		$div.each( function(index) {
			if ($shown.attr('id') == this.id) {
				$li.eq(index).addClass('js-active');
			} else {
				$(this).hide();	
			}
		});
		
		// eventos para los li
		// estos deben tener el href que lleve al identificador de la pestanya que activan
		// para asegurarnos que la pagina es accesible sin javascript
		$li.click( function() {
			var $this = $(this),
				identificador = $this.children().attr('href').getAnchor();
				
			if ($this.hasClass('js-active')) {
				return false;
			}
			// reasignamos clases
			$li.removeClass('js-active');
			$this.addClass('js-active');
			$div.filter(':visible').slideUp('fast', function() {
				$(identificador).slideDown();
			});
			return false;
		});
		// eventos de hover para los li
		$li.hover( function() {
			$(this).addClass('js-hover');
		}, function() {
			$(this).removeClass('js-hover');
		});
	});
}

function createBloq(container) {
	$('a.linkBloq', container || document).each( function() {
		var $c = $(this),
			$li = $('.linkBloq'),
			$div = $('.bloqHidden'),			
			$shown = $div.filter('.shown');
		// preparamos el contenido
		// si hay un numero de elementos distinto a 1 (por algun error u omision)
		// los reseteamos y se lo ponemos solo al primero
		if (1 != $shown.length) {
			$shown.removeClass('shown');
			$shown = $div.eq(0).addClass('shown');
		}
		// ocultamos todos excepto el que toca
		$div.each( function(index) {
			if ($shown.attr('id') == this.id) {
				$li.eq(index).addClass('js-active');
			} else {
				$(this).hide();	
			}
		});
		
		
		
		// eventos para los li
		// estos deben tener el href que lleve al identificador de la pestanya que activan
		// para asegurarnos que la pagina es accesible sin javascript
		$li.click( function() {
			var $this = $(this),
				identificador = $this.attr('href').getAnchor();
				
			if ($this.hasClass('js-active')) {
				return false;
			}
			// reasignamos clases
			$li.removeClass('js-active');			
			$this.addClass('js-active');
			$div.filter(':visible').slideUp('fast', function() {
				$(identificador).slideDown();
			});
			
			return false;
		});
		
	});
	$(document.location.href.getAnchor()).eq(0).addClass('shown');
}

function slideDown(container) {
	cont=0;
	$('.slideConsejo').each( function() {				
		var $c = $(this),		
			$div = $('.slideConsejoInfo').eq(cont);
			//$shown = $div.filter('.shownSlide');
			//$div.addClass('js-active');	
			$div.hide();			
			
		$('.slideConsejo').click( function() {
			var $this = $(this);
				identificador = $this.attr('href').getAnchor();
				
			if ($this.hasClass('js-actiu')) {
				
				return false;
			}else{
			// reasignamos clases
			$('.slideConsejo').removeClass('js-actiu');
			$this.addClass('js-actiu');
			$('.slideConsejoInfo').filter(':visible').slideUp('fast');
			$(identificador).slideDown('fast');
				
			
			return false;
			}
		});
		
		cont++;		
		
	});
}


// funcion para extraer el texto a ordenar del tablesorter
function myTextExtraction(node) {
	var text = $(node).text();
	if (validarFecha(text)) {
		// reordenamos la fecha para tener anyo, mes y dia sin separacion
		text = [text.substring(6,8), text.substring(3,5), text.substring(0,2)].join('');
	}
	return text;
}

$().ready(function(){
	// si por la URL nos pasan un ID le ponemos la clase shown a ese en concreto
	var ancla = $(document.location.href.getAnchor());
	ancla.filter('.pestanya').addClass('shown').siblings('.pestanya').removeClass('shown');		
	$('table.sortable').tablesorter( {textExtraction:myTextExtraction} );
	createTabs();
	createBloq();
	asignPanelEvents();
	fontZoom();
	slideDown();
	
});

// extraer el ancla de una URL
String.prototype.getAnchor = function() {
	return this.indexOf('#') == -1 ? '' : this.substring(this.indexOf('#'));
}

/*
..........................................................................
:: Comprobar email válido                                               ::
..........................................................................
*/
function validarEmail( sTesteo ) {
    var reEmail = /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
    return reEmail.test(sTesteo);
}

/*
..........................................................................
:: Validar fecha                                                        ::
:: Formato correcto: dd/mm/aa                                           ::
..........................................................................
*/
function validarFecha( sFecha ) {
    var reFecha = /^(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:\d{2})$/;
    return reFecha.test( sFecha );
}

$(function(){$('a[href][rel*=external]').each(function(i){this.target = "_blank";});});

function fontZoom() {
  	// Reset Font Size
  	var originalFontSize = ($('html').css('fontSize'))-2;
  	
	if(readCookie('fontZoom')) {
  		var newFontSize=readCookie('fontZoom');
  		var newFontSizeNum= parseFloat(newFontSize,10);  
  		if (newFontSizeNum>30) newFontSizeNum = originalFontSize;			
  		$('#contenidos').css('font-size', newFontSizeNum);  		
  	}
    
  // Increase Font Size
  	$(".increaseFont").click(function(){
	    var currentFontSize = $('#contenidos').css('fontSize');	    
	    var currentFontSizeNum = parseFloat(currentFontSize, 10);
	    if (currentFontSizeNum>30) currentFontSizeNum = originalFontSize;	    
	    var newFontSize = currentFontSizeNum+2;
	    $('#contenidos').css('font-size', newFontSize);	    
	    saveCookie("fontZoom",newFontSize,666);
	    
	    return false;
  	});
  // Decrease Font Size
  	$(".decreaseFont").click(function(){
  		
	    var currentFontSize = $('#contenidos').css('fontSize');		      
	    var currentFontSizeNum = parseFloat(currentFontSize, 10);	    
	    if (currentFontSizeNum<4) currentFontSizeNum = originalFontSize;
	    var newFontSize = currentFontSizeNum-2;
	    $('#contenidos').css('font-size', newFontSize);
	    saveCookie("fontZoom",newFontSize,666);	    
	    return false;
  	});
}



function saveCookie(name,value,days) {	
	
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i<ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function deleteCookie(name) {
	saveCookie(name,"",-1);
}
