$().ready( function (){
	// bloquear cualquier enlace que tenga href=#
	$('a').click( function (evento){
		if($(this).attr("href") == '#') evento.preventDefault();
    });	
	
	// inicializamos el shadowbox
	Shadowbox.init();	
	
	// habilitamos el boton de imprimir pagina
	 $("#btn_imprimir").click(function(){ $("#CUERPO").jqprint(); });
	
	// mostramos los pies de foto de las imagenes
	 $('img.pie_foto').each(function(index){  					
		$(this).replaceWith('<div class="piedefoto" style="width:'+$(this).attr('width')+'px;'+(($(this).attr('style'))?$(this).attr('style'):'')+'"><img src="'+$(this).attr('src')+'" alt="'+$(this).attr('alt')+'" width="'+$(this).attr('width')+'" height="'+$(this).attr('height')+'"><br />'+$(this).attr('alt')+'</div>');   					
	 });
	 
	// cargamos los enlaces que se utilizan para apuntarse a los eventos
	 $('a.inscribirse_evento').each(function(index){  		
		$(this).click(function(){ 
			Shadowbox.open({player:'iframe',content:'inscripcionEvento.php?evento='+$(this).attr('title'), height:370, width:600});			
		});   					
	 });	
	 
	// cargamos los enlaces que se utilizan para apuntarse a las listas de correo
	 $('a.inscribirse_lista_correo').each(function(index){  		
		$(this).click(function(){ 
			Shadowbox.open({player:'iframe',content:'inscripcionEvento.php?lista='+$(this).attr('title'), height:370, width:600});			
		});   					
	 });	 
	
	 // controlamos el timeout del usuario si esta logado
	 if ($("#btn_desconectar").length > 0) {
		// setInterval("Usuario.avisoSesion()",1000000);
	 }
	 
	// para las transiciones de las imagenes 
	 transicionMenu.iniciar();
	 
	 
	// cargamos el combo de paises y lo habilitamos para cambiar de web
	 $.ajax({
			url: "includes/listadoWebs.ajax.php", timeout: 3000, type: "GET",
			error: function(objeto, quepaso, otroobj){alert("Se ha producido un error");},			
			success: function(datos){
				$("#websPaises").html(datos);														
			}
		});	 
	 $("#websPaises").change(function(){ document.location.href=$(this).val();});	 


});

var Usuario = {
	desconexion:null,	
	login:function(){
		if(document.formLogin.usuario.value.length == 0){
			alert('Debe especificar el usuario');
		}else if(document.formLogin.contrasena.value.length == 0){
			alert('Debe especificar la contraseña');
		}else{
			document.formLogin.submit();
		}	
	},
	desconectar:function(){ 
		document.location.href="home/desconectar,1";
	},
	avisoSesion:function(){
		this.desconexion = setTimeout("Usuario.desconectar()",10000);
		contenido = '<div style="background-color:#fff;text-align:center;height:90px;padding:5px;" class="destacado_naranja"><br />Esta a punto de caducar la sesi&oacute;n<br><br><a href="#" onclick="parent.Usuario.renovarSesion();" class="destacado_azul">Renovar la sesi&oacute;n</a></div>';
		Shadowbox.open({player:'html',content:contenido, height: 100, width: 300});	
	},
	renovarSesion:function(){
		clearTimeout(this.desconexion);
		Shadowbox.close();
	},
	cambiarPais:function(pais){
		$('#idwebsel > option').each(function(index) {
			if($(this).val() == pais){
				document.formLogin.action = $(this).text();
				document.formLogin.submit();
			}		    
		});		
	}
};

var contacto = {
	enviar:function(){
		document.formcontacto.lasrazones.value = '';	
		validado = true;  
		if(document.formcontacto.idioma.value.length == 0){
			$('#error_idioma').show();
			validado = false;
		}
		if(((document.formcontacto.email.value.search(/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/) != -1)||(document.formcontacto.email.value.search(/@[\w\-]+\./)) == -1)||(document.formcontacto.email.value.search(/\.[a-zA-Z]{2,4}$/) == -1)){
			$('#error_email').show();
			validado = false;
		}
		if(validado){
			$('#unarazon:checked').each(function(){document.formcontacto.lasrazones.value+=','+$(this).val();});			
			$.ajax({
		        url: "includes/contacto.inc.php", timeout: 30000, type: "POST",
		        error: function(objeto, quepaso, otroobj){alert("Se ha producido un error");},
				data: $('#formcontacto').serialize(),
		        success: function(datos){if(datos.length == 0){
		        	document.location.href="contactoOK";									
				}}
			});			
		}else{
			$("#contactoemail").keypress(function(){$('#error_email').hide();});
			$("#contactoidioma").keypress(function(){$('#error_idioma').hide();});
		}	
	},
	enviarContactoPress:function(){		
		validado = true;  		
		if(((document.formcontacto.email.value.search(/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/) != -1)||(document.formcontacto.email.value.search(/@[\w\-]+\./)) == -1)||(document.formcontacto.email.value.search(/\.[a-zA-Z]{2,4}$/) == -1)){$('#error_email').show();validado = false;}
		if(document.formcontacto.nombre.value==""){$('#error_nombre').show();validado = false;}
		
		if(validado){					
			$.ajax({
		        url: "includes/contactopress.inc.php", timeout: 30000, type: "POST",
		        error: function(objeto, quepaso, otroobj){alert("Se ha producido un error");},
				data: $('#formcontacto').serialize(),
		        success: function(datos){if(datos.length == 0){
		        	document.location.href="contactoPressOK";									
				}}
			});			
		}else{
			$("#contactoemail").keypress(function(){$('#error_email').hide();});	
			$("#nombre").keypress(function(){$('#error_nombre').hide();});			
		}	
	},
	enviarRegistroPress:function(){		
		validado = true;  		
		if(((document.formcontacto.email.value.search(/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/) != -1)||(document.formcontacto.email.value.search(/@[\w\-]+\./)) == -1)||(document.formcontacto.email.value.search(/\.[a-zA-Z]{2,4}$/) == -1)){$('#error_email').show();validado = false;}
		if(document.formcontacto.nombre.value==""){$('#error_nombre').show();validado = false;}
		if(document.formcontacto.apellido1.value==""){$('#error_apellido1').show();validado = false;}
		
		if(validado){					
			$.ajax({
		        url: "includes/registropress.inc.php", timeout: 30000, type: "POST",
		        error: function(objeto, quepaso, otroobj){alert("Se ha producido un error");},
				data: $('#formcontacto').serialize(),
		        success: function(datos){if(datos.length == 0){
		        	document.location.href="registroPressOK";									
				}}
			});			
		}else{
			$("#contactoemail").keypress(function(){$('#error_email').hide();});	
			$("#nombre").keypress(function(){$('#error_nombre').hide();});	
			$("#apellido1").keypress(function(){$('#error_apellido1').hide();});	
		}	
	}
};

var newsletter = {
	baja:function(){		
		$('.elformularionewsletter').hide();
		$('.elformulariocnewsletter').show();
	},	
	enviar:function(){
		validado = true;  
		if(((document.formNewsletter.email.value.search(/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/) != -1)||(document.formNewsletter.email.value.search(/@[\w\-]+\./)) == -1)||(document.formNewsletter.email.value.search(/\.[a-zA-Z]{2,4}$/) == -1)){$('#error_email').show();validado = false;}
		if(document.formNewsletter.nombre.value.length == 0){$('#error_nombre').show();validado = false;}
		if(validado){
			$.ajax({
				url: "includes/newsletter.inc.php", timeout: 3000, type: "POST",
				error: function(objeto, quepaso, otroobj){alert("Se ha producido un error");},
				data: $('#formNewsletter').serialize(),
				success: function(datos){				
					if(datos == 'OK'){
						document.location.href="newsletterOK";
					}else{
						alert('El email introducido ya esta registrado en nuestra newsletter');
					}														
				}
			});			
		}else{
			$("#newsletteremail").keypress(function(){$('#error_email').hide();});
			$("#newsletternombre").keypress(function(){$('#error_nombre').hide();});
		}	
	},
	cancelar:function(){		
		validado = true;  
		if(((document.formcNewsletter.email.value.search(/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/) != -1)||(document.formcNewsletter.email.value.search(/@[\w\-]+\./)) == -1)||(document.formcNewsletter.email.value.search(/\.[a-zA-Z]{2,4}$/) == -1)){$('#error_cemail').show();validado = false;}
		if(validado){
			$.ajax({
				url: "includes/newsletter.inc.php", timeout: 3000, type: "POST",
				error: function(objeto, quepaso, otroobj){alert("Se ha producido un error");},
				data: $('#formcNewsletter').serialize(),
				success: function(datos){if(datos.length == 0){
					document.location.href="newsletterCanceladoOK";									
				}}
			});			
		}else{
			$("#cnewsletteremail").keypress(function(){$('#error_cemail').hide();});			
		}
	}
};

var buscador = {
	busqueda_simple : true,	parametros:'', pagina:1, resultados:null,
	buscar:function(){	
		this.parametros = $('#buscarsimple').val();		
		if (this.parametros==""){
			this.parametros = $('#buscarsimpleAvanzado').val();
		}
		if (this.parametros==""){
			alert("Debe introducir un texto para realizar la busqueda");
			return;
		} else {
			$('#buscadorAvanzado').hide();		
			this.busqueda_simpre = true;
					
			this.realizar_busqueda();
		}
	},	
	busqueda_avanzada:function(){	
		$('#buscarsimple').val('');
		$('#buscarsimpleAvanzado').val('');
		$('#buscadorSimple').hide();	
		$('#buscadorAvanzado').show();	
		$('#resultadosBusqueda').html('');
		this.pagina=1;
	},
	realizar_busqueda:function(){
		$('#buscadorSimple').show();	
		$.ajax({
			url: "includes/buscadorresultados.ajax.php?pagina=" + buscador.pagina, timeout: 3000, type: "POST",
			error: function(objeto, quepaso, otroobj){alert("Se ha producido un error");},
			data: {buscar:buscador.parametros},
			success: function(datos){					
				$('#resultadosBusqueda').html(datos);									
			}
		});
	},
	realizar_busqueda_avanzada:function(){
		$.ajax({
			url: "includes/buscadorresultadosAvanzada.ajax.php?pagina=" + buscador.pagina, timeout: 3000, type: "POST",
			error: function(objeto, quepaso, otroobj){alert("Se ha producido un error");},
			data: $('#frmsocio').serialize(),
			success: function(datos){					
				$('#resultadosBusqueda').html(datos);									
			}
		});		
	},
	irpagina:function(pag){
		this.pagina = pag;
		this.realizar_busqueda();
	},
	detalle:function(id){
		this.resultados = $('#resultadosBusqueda').html();
		$.ajax({
			url: "includes/buscadorresultados.ajax.php", timeout: 3000, type: "POST",
			error: function(objeto, quepaso, otroobj){alert("Se ha producido un error");},
			data: {detalle:id},
			success: function(datos){					
				$('#resultadosBusqueda').html(datos);									
			}
		});
	},
	volver:function(){
		$('#resultadosBusqueda').html(this.resultados);
	}
};

paginaInicio = function(objk, dominio){
	 if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion)>3)){
          objk.style.behavior="url(#default#homepage)";
          objk.setHomePage(dominio);		 
     }else{
         alert("Su navegador no soporta esta opci�n");
     } 
};

var transicionMenu = {
	posicion:0, posicionprevia:-1, numero_imagenes:0,
	iniciar:function(){
		this.numero_imagenes = $('#frame > img').size();
		if(this.numero_imagenes>1){ // hay m�s de una imagen para hacer la transici�n
			this.posicion = 1;
			setInterval("transicionMenu.transicion()",5000);			
		}
	},
	transicion:function(){
		this.posicionprevia = this.posicion; 
		((this.posicion < this.numero_imagenes)?this.posicion++:this.posicion = 1);		
		var i = 0;
		$('#frame > img').each(function(i){
			i++;			
			if(i==transicionMenu.posicion)$(this).show();
			if(i==transicionMenu.posicionprevia)$(this).hide();
		});
	}
};

//-----------------------------------------------------------------------
//Eros Fratini - eros@recoding.it
//jqprint 0.3
//
//- 19/06/2009 - some new implementations, added Opera support
//- 11/05/2009 - first sketch
//
//Printing plug-in for jQuery, evolution of jPrintArea: http://plugins.jquery.com/project/jPrintArea
//requires jQuery 1.3.x
//
//Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
//------------------------------------------------------------------------

(function($) {
 var opt;

 $.fn.jqprint = function (options) {
     opt = $.extend({}, $.fn.jqprint.defaults, options);

     var $element = (this instanceof jQuery) ? this : $(this);
     
     if (opt.operaSupport && $.browser.opera) 
     { 
         var tab = window.open("","jqPrint-preview");
         tab.document.open();

         var doc = tab.document;
     }
     else 
     {
         var $iframe = $("<iframe  />");
     
         if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }

         $iframe.appendTo("body");
         var doc = $iframe[0].contentWindow.document;
     }
     
     if (opt.importCSS)
     {
         if ($("link[media=print]").length > 0) 
         {
             $("link[media=print]").each( function() {
                 doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' media='print' />");
             });
         }
         else 
         {
             $("link").each( function() {
                 doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' />");
             });
         }
     }
     
     if (opt.printContainer) { doc.write($element.outer()); }
     else { $element.each( function() { doc.write($(this).html()); }); }
     
     doc.close();
     
     (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).focus();
     setTimeout( function() { (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);
 }
 
 $.fn.jqprint.defaults = {
		debug: false,
		importCSS: true, 
		printContainer: true,
		operaSupport: true
	};

 // Thanks to 9__, found at http://users.livejournal.com/9__/380664.html
 jQuery.fn.outer = function() {
   return $($('<div></div>').html(this.clone())).html();
 };
})(jQuery);

//ISRA ------------
var pag={
	enviarLoginForo:function(){
		nick = $('#nick').val();
		password = $('#password').val();
		
		validado = true;
		
		if (nick==''){
			$('#error_nick').show();
			validado = false;	
		}
		if (password==''){
			$('#error_password').show();
			validado = false;	
		}
		
		if (validado){
			$.ajax({
		        url: "includes/forosLoginUsuario.php", timeout: 3000, type: "POST",
		        error: function(objeto, quepaso, otroobj){comun.alerta("Se ha producido un error");},
				data: {nick:nick,password:password},
		        success: function(datos){
					if (datos>0){
						document.location.href="foros";
					} else {
						$('#error_noexiste').show();
						return;
					}
				}
			});	
		} else {
			$("#nick").keypress(function(){$('#error_nick').hide();});	
			$("#password").keypress(function(){$('#error_password').hide();});
		}
	},
	desconectarForo:function(){
		$.ajax({
	        url: "includes/forosDesconectarUsuario.php", timeout: 3000, type: "POST",
	        error: function(objeto, quepaso, otroobj){comun.alerta("Se ha producido un error");},
			data: {},
	        success: function(datos){
				document.location.href="foros";
			}
		});	
	},
	enviarBuscador:function(pagina){	
		textBuscador = $('#textBuscador').val();
		if (textBuscador==''){
			alert("Debe especificar una palabra para la busqueda");
			return;
		}
		document.buscadorForo.pagina.value = pagina;
				
		document.buscadorForo.submit();	
		
	},
	enviarRegistro:function(){
		
		nick = $('#nick').val();
		password = $('#password').val();
		email = $('#email').val();
		validado = true;	
		
		if (nick==''){
			$('#error_nick').show();
			validado = false;	
		}
		if (password==''){
			$('#error_password').show();
			validado = false;	
		}
		if (email==''){
			$('#error_email').show();
			validado = false;	
		} else {
			if(((email.search(/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/) != -1)||(email.search(/@[\w\-]+\./)) == -1)||(email.search(/\.[a-zA-Z]{2,4}$/) == -1)){
				$('#error_email').show();
				validado = false;	
			}
		}
		if (validado){
			$.ajax({
		        url: "includes/forosComprobarNick.php", timeout: 3000, type: "POST",
		        error: function(objeto, quepaso, otroobj){comun.alerta("Se ha producido un error");},
				data: {nick:nick},
		        success: function(datos){				
					if (datos > 0){
						$('#error_repetido').show();
						return;
					} else {
						document.registroForo.submit();
					}
				}
			});		
		}else{
			$("#nick").keypress(function(){$('#error_nick').hide();});	
			$("#password").keypress(function(){$('#error_password').hide();});
			$("#email").keypress(function(){$('#error_email').hide();});
		}
			
	},
	enviarForo:function(){
		captcha = $('#captchaContacto').val();
		idforo = $('#idforo').val();
		titulo = $('#titulo').val();		
		texto = $('#texto').val();
		validado = true;
		
		if (titulo==''){
			$('#error_titulo').show();
			validado = false;			
		}
		if (texto==''){
			$('#error_texto').show();
			validado = false;			
		}
		if (validado){	
			if (idforo>1){
				$.post('includes/guardarMensaje.inc.php',{captcha:captcha,titulo:titulo,texto:texto,idforo:idforo},function(data){
					document.location.href="verForo/idforo," +idforo;	
				});	
			}
		}else{
			$("#titulo").keypress(function(){$('#error_titulo').hide();});	
			$("#texto").keypress(function(){$('#error_texto').hide();});
		}
	},
	validarPostal:function(){
		de_nombre = $('#de_nombre').val();
		de_mail = $('#de_mail').val();
		para_nombre = $('#para_nombre').val();
		para_mail = $('#para_mail').val();
		cuerpo_mail = $('#cuerpo_mail').val();
		validado = true;
		
		if (de_nombre==''){
			$('#error_denombre').show();
			validado = false;		
		}
		if(((de_mail.search(/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/) != -1)||(de_mail.search(/@[\w\-]+\./)) == -1)||(de_mail.search(/\.[a-zA-Z]{2,4}$/) == -1)){
			$('#error_demail').show();
			validado = false;		
		}
		if (para_nombre==''){
			$('#error_paranombre').show();
			validado = false;		
		}
		if(((para_mail.search(/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/) != -1)||(para_mail.search(/@[\w\-]+\./)) == -1)||(para_mail.search(/\.[a-zA-Z]{2,4}$/) == -1)){
			$('#error_paramail').show();
			validado = false;		
		}
		
		return validado;
	},
	enviarPostal:function(){		
		if (this.validarPostal()){
			document.postal.action = "enviarPostal";
			document.postal.submit();
		} else {
			$("#de_nombre").keypress(function(){$('#error_denombre').hide();});
			$("#de_mail").keypress(function(){$('#error_demail').hide();});
			$("#para_nombre").keypress(function(){$('#error_paranombre').hide();});
			$("#para_mail").keypress(function(){$('#error_paramail').hide();});
	
		}
	},
	vistaPrevia:function(){			
		if (this.validarPostal()){
			document.postal.submit();
		} else {
			$("#de_nombre").keypress(function(){$('#error_denombre').hide();});
			$("#de_mail").keypress(function(){$('#error_demail').hide();});
			$("#para_nombre").keypress(function(){$('#error_paranombre').hide();});
			$("#para_mail").keypress(function(){$('#error_paramail').hide();});
		}
	}
}

