/**
 * @author Héctor Laura García
 */
$(document).ready(function(){


	/****** CONTROL DEL ANCHO DEL PIE EN OPERA *************************/
	
	/*El ancho al 100% no funciona en Opera, queda un espacio en blanco. Hay que darle 102% pero para 
	  centrar el contenido, hay que posicionarlo absolutamente.*/
	if(jQuery.browser.opera)
	{
		$('#pie').css({'width':'102%', 'position':'relative'});
		$('div#pie div#contenedorPie').css({'position':'absolute', 'left':'49%', 'margin-left':'-475px'});
	}//fin if
	
	/****** FIN CONTROL DEL ANCHO DEL PIE EN OPERA *************************/
	
	
	/****** ABRIMOS TODOS LOS REL=EXTERNAL EN UNA NUEVA VENTANA ************/
	
	$('a[rel="external"]').attr('target','_blank');
	
	/****** FIN ABRIMOS TODOS LOS REL=EXTERNAL EN UNA NUEVA VENTANA ********/
	
	/****** ROTACIÓN DE IMAGENES DE LAS NOTICIAS DE LA CABECERA ***********/
	
	if ($("#noticiasSuperiorImg").length > 0 && $("#noticiasSuperiorImg img").length > 1) 
	{
		$("#noticiasSuperiorImg img").not('#f0').hide();
		
		window.setInterval('fotosAleatorias()', 3000);//cada 3 segundos
	}//fin if
	
	/****** FIN ROTACIÓN DE IMAGENES DE LAS NOTICIAS DE LA CABECERA *******/
	
	
	/****** ROLLOVER DE LAS 4 ÚLTIMAS NOTICIAS *******/
	
		$('#noticiasSuperiorNoticias h3 a').hover(function(){
		
			$(this).parent().next().css('color', '#3399ff');
			$(this).parent().next().css('background-position', 'left -14px');
		
		},
		function()
		{
			$(this).parent().next().css('color', '#FFF');
			$(this).parent().next().css('background-position', 'left top');			
		});
	
	/****** FIN ROLLOVER DE LAS 4 ÚLTIMAS NOTICIAS *******/
		
	
	/****** CLIK EN EL BOTON 'NOTICIAS ANTIGUAS' DE LA HOME ***********/
	
	var pag = 9;
	
	$('#btnNoticiasAntiguas').click(function()
	{
		$.getJSON("/includes/AJAX.inc.php", {metodo: 'getNoticias', pagina: pag}, function(resp) 
		{			
			if(resp != null) //nos aseguramos de que el valor devuelto sea distinto de null para evitarnos errores de javascript
			{
				$('#contenedorIzq .contImagen img').fadeOut();
				
				for(var i = 0; i < resp.id.length; ++i)	
				{
					$('#contenedorIzq .contImagen img').eq(i).attr('src', '../img/noticias/uploads/' + resp.imagen[i]);
					$('#contenedorIzq .contImagen img').eq(i).attr('alt', resp.titular[i]);
					$('#contenedorIzq .cartel').eq(i).text(resp.categoria[i]);
					$('#contenedorIzq .fecha').eq(i).text(resp.fecha_alta[i]);
					$('#contenedorIzq h4').eq(i).text(resp.titular[i]);					
					$('#contenedorIzq .intro').eq(i).text(resp.entradilla[i]);
					$('#contenedorIzq a').eq(i).attr('href', resp.enlace[i].replace('&amp;', '&'));
				}//fin for

				if(resp.id.length < 8)
					for(i=resp.id.length; i < 8; ++i)
						$('#contenedorIzq .noticiaIzq').eq(i).remove();	
				
				//segun cargan las imagenes, se van mostrando poco a poco
				$('#contenedorIzq .contImagen img').load(function() 
				{
					$(this).fadeIn();
				});
				
				pag += 9;
			}//fin if
		});
		
		return false;
	});
	
	/****** FIN CLIK EN EL BOTON 'NOTICIAS ANTIGUAS' DE LA HOME *******/
	
	
	/****** CLIK EN EL BOTON 'NOTICIAS ANTIGUAS' DE LA SECCIÓN FAMILIA ***********/
	
	var pagFamilia = 4;
	
	$('#btnOtrasNoticiasFamilia').click(function()
	{
		$.getJSON("/includes/AJAX.inc.php", {metodo: 'getNoticiasFamilia', pagina: pagFamilia}, function(resp) 
		{			
			if(resp != null) //nos aseguramos de que el valor devuelto sea distinto de null para evitarnos errores de javascript
			{
				$('#colCentro .noticiaCentro img.imgNoticia').fadeOut();

				for(var i = 0; i < resp.length; ++i)	
				{
					$('#colCentro .noticiaCentro img.imgNoticia').eq(i).attr('src', '../img/noticias/uploads/' + resp[i].imagen);
					$('#colCentro .noticiaCentro img.imgNoticia').eq(i).attr('alt', resp[i].titular);					
					$('#colCentro .noticiaCentro h4').eq(i).text(resp[i].titular);					
					$('#colCentro .noticiaCentro p').eq(i).text(resp[i].entradilla);
					$('#colCentro .noticiaCentro a').eq(i).attr('href', resp[i].enlace.replace('&amp;', '&'));
				}//fin for

				if(resp.length < 4)
					for(i = resp.length; i < 4; ++i)
						$('#colCentro .noticiaCentro').eq(i).fadeOut();			

				//segun cargan las imagenes, se van mostrando poco a poco
				$('#colCentro .noticiaCentro img.imgNoticia').load(function() 
				{
					$(this).fadeIn();
				});
				
				pagFamilia += 4;
			}//fin if
		});
		
		return false;
	});
	
	/****** FIN CLIK EN EL BOTON 'NOTICIAS ANTIGUAS' DE LA SECCIÓN FAMILIA *******/	
	
	
	/****** HOVER EN LOS BOTONES DE EVENTOS ***************************/
	
	$('.proxEventoDcha h4 a').hover(function(){
		//alert($(this).prev().prev().attr('class'));
		$(this).parent().parent().prev().find('p.fecha').css('color', '#3399ff');
	},
	function(){
		$(this).parent().parent().prev().find('p.fecha').css('color', '#000');
	});
	
	/****** FIN HOVER EN LOS BOTONES DE EVENTOS ***********************/
	
	
	/****** TRATAMIENTO DEL FORMULARIO DE ENVIO DE NEWSLETTER *********/
	
	$('#txtEmail').focus(function()
	{
		$(this).val('');
		$(this).unbind('focus');
	});
	
	
	$('#btnEnviarNews').click(function()
	{
		var msg;
		//[campo], [texto que aparecera], [tipo], [texto por defecto en el campo], [obligatorio]
		var datosEnviar = new Array($('#txtEmail'), 'e-mail', 'email', 'Your email', 1);
		
		var resp = kValida(datosEnviar);
		
		switch(resp[0])
		{
			case 0:
				$.getJSON("/includes/AJAX.inc.php", { metodo: "setEmailNewsletters", mail: $('#txtEmail').val() },
				  function(data){
				  
					msg = '<p id="msgNewsletter" class="' + data[0] + '">' + data[1] + '</p>';
					$('#formuNewsletter').append(msg);
					$('#txtEmail').val('');
				  });
					
				break;
				
			case 1:
				msg = '<p id="msgNewsletter" class="error">Debes introducir un e-mail.</p>';
				
				break;
				
			case 2:
				msg = '<p id="msgNewsletter" class="error">Debes introducir un e-mail válido.</p>';				
				break;
				
			default:
				msg = '<p id="msgNewsletter" class="error">Ha ocurrido un error. Por favor, inténtalo más tarde.</p>';
				break;			
		}//fin switch
		
		$('#msgNewsletter').remove();
		$('#formuNewsletter').append(msg);
	});
	
	/****** FIN TRATAMIENTO DEL FORMULARIO DE ENVIO DE NEWSLETTER *********/	
	
	
	/****** TRATAMIENTO DEL COMBO DE MESES DEL CALENDARIO *****************/
	
	$('select.calendarios_meses').change(function(){
		$('#formuCalendario').submit();									
	});
	
	/****** FIN TRATAMIENTO DEL COMBO DE MESES DEL CALENDARIO *************/
	
	
	/****** HOVER EN LOS DIAS DEL CALENDARIO ******************************/

	$('div#contenedorCalendario div#calend div.dia').hover(function(){
		$(this).css('background-color', '#f5f5f5');	
	},
	function(){
		$(this).css('background-color', '#FFF');
	});
	
	/****** HOVER EN LOS DIAS DEL CALENDARIO ******************************/
	
	
	/****** TRATAMIENTO DEL FORMULARIO DE ENVIO DE CONTACTO *********/
	
	$('#btnEnviarCont').click(function(){
		
		var msg;
		var bien = 0;
		//[campo], [texto que aparecera], [tipo], [texto por defecto en el campo], [obligatorio]
		var datosEnviar = new Array($('#txtNombre'), 'Nombre', '', '', 1,
									$('#txtEmailContacto'), 'e-mail', 'email', '', 1,
									$('#txtPregunta'), 'Pregunta', '', '', 1);
		
		var resp = kValida(datosEnviar);
		
		for(var i = 0; i < resp.length; i++)
		{
			$('label[for='+datosEnviar[i * 5].attr('id')+'] span').remove();
			
			switch(resp[i])
			{
				
				case 0:
					//msg = datosEnviar[i * 5].css({'border':'1px solid green'});
					++bien;				
					break;
					
				case 1:
					msg = datosEnviar[i * 5].css({'border':'1px solid red'});
					$('label[for='+datosEnviar[i * 5].attr('id')+']').append('<span class="error">Falta!</span>');			
					break;
				
				case 2:
					msg = datosEnviar[i * 5].css({'border':'1px solid red'});
					$('label[for='+datosEnviar[i * 5].attr('id')+']').append('<span class="error">Incorrecto!</span>');				
					break;				
				
				default:
					msg = datosEnviar[i * 5].css({'border':'1px solid red'});
					$('label[for='+datosEnviar[i * 5].attr('id')+']').append('<span class="error">Error!</span>');
					break;	
			}//fin switch		
		}//fin for				
		
		if(bien == 3)
			$('#formuContacto').submit();
		else
			return false;
	});
	
	/****** FIN TRATAMIENTO DEL FORMULARIO DE ENVIO DE CONTACTO *********/	
	

	/****** ROLLOVERS DE LOS BOTONES ************************************/
	
	$('#contenedorFamilia a').hover(function(){
		$(this).prev().find('h4').css('color', '#3399ff');
	},
	function(){
		$(this).prev().find('h4').css('color', '#FFF');
	});	
	
	/****** FIN ROLLOVERS DE LOS BOTONES ************************************/
	
	
	/****** LIGHTBOX DE LAS FOTOS DE CADA MIEMBRO ***************************/
	
	$('#thumbs a').lightBox();
	
	/****** FIN LIGHTBOX DE LAS FOTOS DE CADA MIEMBRO ***************************/
	
	
	/****** CARGA DE VIEDO ***************************/
	
	
	$('#colMedia a').click(function(){

		var arrayHref = $(this).attr('href').split('/');
		var idVideo = arrayHref[4];
		
		$('body').append('<div id="capaOscura"></div>');
		$('body').append('<div id="video"></div>');



		$.post("/includes/AJAX.inc.php", { metodo: "getVideo", id: idVideo },
		  function(data){
		    $('#video').append(data);
		    
		  }, "html");

		
		$('#capaOscura').height($('html').height());

		$('#capaOscura').fadeTo('fast', 0.80);
		$('#video').fadeIn('slow');

		$('#capaOscura').bind('click', function(){

			$('#capaOscura, #video').fadeOut('fast');
			$('#capaOscura, #video').remove();
		});
		
		return false;

	});
	
	
	/*
	$('#colMedia a').click(function(){
		
		//partimos la cadena del href para sacar el identificador del video
		var arrayHref=$(this).attr('href').split('/');
		var idVideo = arrayHref[4];
		
		$('body').append('<div id="capaOscura"></div>');
		$('#capaOscura').height($('html').height());

		$('#capaOscura').fadeTo('fast', 0.80);
		
		var x = (screen.width - 660) / 2;
		var y = (screen.height - 520) / 2; 
		
		//abrimos el pop up
		window.open('includes/videos.php?video=' + idVideo,'Video','width=660,height=520,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=' + x + ',top=' + y); 
		
		return false;
	});
	*/
	/****** FIN CARGA DE VIEDO ***************************/

});


/**
* Esta función saca las fotos aleatoriamente en la parte superior de la home
*/
function fotosAleatorias()
{	
	var fotos = new Array();
	
	//Guardamos en el array todas las imagenes del contenedor
	//TODO: Conseguir pasar el array a la función sin tener que calcularlo cada vez que se entre
	$("#noticiasSuperiorImg img").each(function(i){
	
		fotos.push(this);
		
	});	
	
	//sacamos el valor aleatorio para la posición del array
	var aleatorio = parseInt(Math.random()*fotos.length);

	//$('#debug').append('<p>'+fotos[aleatorio].id+'</p>');
	
	//si la foto que queremos cargar es la que ya esta cargada, volvemos a llamar a la función
	if (fotos[aleatorio].id != $('#noticiasSuperiorImg img:visible').attr('id')) {
		$('#noticiasSuperiorImg img').fadeOut(2000);
		$('#' + fotos[aleatorio].id).fadeIn(2000);
	}//fin if
	else 
		fotosAleatorias();	
}


function kValida(datos)
{
	var respuesta = new Array();
	var long = datos.length;
	
	for(var i = 0; i < long; i += 5)
	{		
		datos[i].val($.trim(datos[i].val()));
		
		if(datos[i].val().length == 0 || datos[i].val() == datos[i+3] && datos[i+4] == 1)
			respuesta.push(1);
		else 
		{
			switch(datos[i+2])
			{
				case 'email':
					if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(datos[i].val()))
						respuesta.push(2);
					else
						respuesta.push(0);
					break;
				
				default:
					respuesta.push(0);
					break;
			}//fin switch
		}//fin else		
	}//fin for
	
	return respuesta;
}//fin función



/**
*	Cierra el velo cuando se cierra el popup
*/
function cierraVelo()
{
	$('#capaOscura').fadeOut('fast');
	$('#capaOscura').remove();
}
