// JavaScript Document

// Funcion que se ejecuta cuando se cambia el tipo de persona,
// para mostrar los campos necesarios
function cambioTipoPago() {
	var f = window.document.forms[1];
	
	if (f.tipopago[0].checked ) {
		document.getElementById('domiciliacion').style.display = "none";
		document.getElementById('transferencia').style.display = "block";
	} else {
		document.getElementById('domiciliacion').style.display = "block";
		document.getElementById('transferencia').style.display = "none";
	}
}

function cambioAportacion() {
	var fo = window.document.forms[1];
	//document.getElementById('aportacionPersonalizada').style.display = "block";
	if ( fo.euros[4].value == "otro" && ((fo.euros[0].checked)||(fo.euros[1].checked)||(fo.euros[2].checked)||(fo.euros[3].checked) )) {
		document.getElementById('aportacionPersonalizada').style.display = "none";
	} else {
		document.getElementById('aportacionPersonalizada').style.display = "block";		
	}
	
}

function cambioTipoPagoDonativo() {
	var f = window.document.forms[1];
	
	if (f.tipopago[0].checked ) {
		document.getElementById('tarjetaCredito').style.display = "none";
		document.getElementById('transferenciaBancaria').style.display = "block";
	} else {
		document.getElementById('tarjetaCredito').style.display = "block";
		document.getElementById('transferenciaBancaria').style.display = "none";
	}
}

function revisarEstados() {
	var f = window.document.forms[1];
	
	if (f.tipopago[1].checked) {
		document.getElementById('tarjetaCredito').style.display = "block";
		document.getElementById('transferenciaBancaria').style.display = "none";
	} else {
		document.getElementById('tarjetaCredito').style.display = "none";
		document.getElementById('transferenciaBancaria').style.display = "block";
	}
	
	if (f.quesoy[0].checked ) {
		document.getElementById('persona').style.display = "block";
		document.getElementById('empresa').style.display = "none";
	} else {
		document.getElementById('persona').style.display = "none";
		document.getElementById('empresa').style.display = "block";
	}
}

function cambioQueSoy(){
	var f = window.document.forms[1];
	//alert(f.quesoy[1].checked);
	
	if (f.quesoy[0].checked ) {
		document.getElementById('empresa').style.display = "none";
		document.getElementById('persona').style.display = "block";
	} else {
		document.getElementById('empresa').style.display = "block";
		document.getElementById('persona').style.display = "none";
	}
}

function cambioValorDonativo() {
	var f = window.document.forms[1];
	document.getElementById("importe").value = "";

}

function cambioCheckDonativo() {
	var f = window.document.forms[1];
	f.euros[3].checked="checked";
	
}


function enviarFormularioDonativo(){
	var f = window.document.forms[1]
 	
	// En el caso de que esté señalada otra cantidad, comprobamos que haya un número en el input "importe"
	
		if (f.euros[3].checked) {
				
				// Primero compreobamos que haya introducido una cantidad
				if (f.importe.value==''){
					alert("Al elegir 'otro importe', tienes que introducir la cantidad que deseas aportar")
					f.importe.focus();
					return 
				}

				// En caso de que haya un valor comprobaremos que sea un entero
				var RegExPattern = /^\d+$/;
				if (!RegExPattern.test(f.importe.value)){
					alert("El importe debe ser numérico"+f.importe.value)
					f.importe.focus();
					return 
				}

		}

		
		if (f.quesoy[0].checked){
			// Comprobamos el campo apellidos
			if( f.apellidos.value=="" ) {
	
			  alert("El campo apellidos es obligatorio.")
	
			  f.apellidos.focus()
	
			  return 
	
			}
			
			// Comprobamos el campo nombre
			
			if( f.nombre.value=="" ) {
	
			  alert("El campo nombre es obligatorio.")
	
			  f.nombre.focus()
	
			return
		
			}
			
			
			if( f.nif.value=="" ) {
	
			  alert("El campo NIF es obligatorio.")
	
			  f.nif.focus()
	
			  return 
	
			}	
			
			// Si introducen un NIE (para extranjeros) en formato XNNNNNNNNL
	
			// tenemos que eliminar la X y añadir 0s a la izquierda hasta completar los 8 dígitos numéricos.
	
			// La validación posterior es la misma que la del NIF.
	
			if(f.nif.value.charAt(0) == 'X' || f.nif.value.charAt(0) == 'x' || f.nif.value.charAt(0) == 'Y' || f.nif.value.charAt(0) == 'y' || f.nif.value.charAt(0) == 'Z' || f.nif.value.charAt(0) == 'z') {		
	
				// quitamos la X
	
				var nieSinX = f.nif.value.substr(1,f.nif.value.length-1)
	
	
				// quitamos cualquier espacio que tenga
	
				while( nieSinX.indexOf(" ") != -1 ) {
	
					 nieSinX = nieSinX.replace(" ","")
	
				}
	
				// si la longitud numérica es inferior a 8, añadiremos 0s a la izda
	
				while(nieSinX.length-1 < 8) {
				
					nieSinX = '0' + nieSinX;
					
				}
				
				// Si la letra es 'x' sumamos 10000000
				if(f.nif.value.charAt(0) == 'X' || f.nif.value.charAt(0) == 'x') {
							
					ochoNumeros = nieSinX.substr(0,8) 
					
				}
				
				// Si la letra es 'y' sumamos 10000000
				if(f.nif.value.charAt(0) == 'Y' || f.nif.value.charAt(0) == 'y') {
							
					ochoNumeros = nieSinX.substr(0,8) + 10000000
					
				}
				
				// Si la letra es 'z' sumamos 20000000
				if(f.nif.value.charAt(0) == 'Z' || f.nif.value.charAt(0) == 'z') {
				
				
					ochoNumeros = nieSinX.substr(0,8) + 20000000
					
				}
				
	
				if (!valida_nif ( ochoNumeros ,  nieSinX.substr(8,1)) ) {
	
				alert("La letra del NIF es incorrecta.")
	
				f.nif.focus()
	
				return 
	
				}
	
			}else{
	
				// NIF español
	
				if ( f.nif.value.length > 0 && (! valida_nif ( f.nif.value.substr(0,8) ,  f.nif.value.substr(8,1))) ) {
	
				  alert("La letra del NIF es incorrecta.")
	
				  f.nif.focus()
	
				  return 
	
				}
	
			}
		}
		
		
		if (f.quesoy[1].checked){
			
			if( f.nombreempresa.value=="" ) {
	
			  alert("El campo 'nombre de empresa' es obligatorio.")
	
			  f.nombreempresa.focus()
	
			  return 
	
			}	
			
			if( f.cif.value=="" ) {
	
			  alert("El campo CIF es obligatorio.")
	
			  f.cif.focus()
	
			  return 
	
			}	
		}




		if(f.tfno1.value=="" && f.tfno2.value=="") {

			alert("Debes introducir al menos un teléfono de contacto")

			f.tfno1.focus()

			return 

		}

		// Comprobamos que el formato del teléfono es correcto
			var RegExPatternTelef = /^\d+$/;
				if (!RegExPatternTelef.test(f.tfno1.value)){
					alert("El teléfono debe ser numérico")
					f.tfno1.focus();
					return 
				}




		if(f.email.value=="") {

			alert("El campo email es obligatorio.")
			f.email.focus()

			return 
		}

	

		if(f.email.value!="" && !f.email.value.isEmail()) {

			alert("El email no está correcto.")
			f.email.focus()
			return 
		}



	

		if ( f.condiciones.checked == false ) {

			alert("Debes aceptar las condiciones de uso.")
			f.condiciones.focus()
			return

	}

	// En este punto todos los campos son correctos, por lo que vamos a poner en cantidad el valor correcto
	
	if (f.euros[3].checked) {
		// Cogemos el valor de Importe
		f.cantidad.value=f.importe.value+"00";
		alert("importe:"+f.importe.value);
	}else{
		// Cogemos el valor de euros (radiobuttons con valores concretos
		if (f.euros[0].checked)
			f.cantidad.value='2000';
		else if (f.euros[1].checked)
			f.cantidad.value='5000';
		else
			f.cantidad.value='10000';
		
	}
	
	/*alert("euros:"+f.cantidad.value+" nif:"+f.nif.value);*/
	
	
	f.submit()

}

function enviarFormularioHazteSocio(){
	var f = window.document.forms[1]
 	
		// Comprobamos el campo apellidos
		if( f.apellidos.value=="" ) {

		  alert("El campo apellidos es obligatorio.")

		  f.apellidos.focus()

		  return 

		}
		
		
		// Comprobamos el campo nombre
		
		if( f.nombre.value=="" ) {

		  alert("El campo nombre es obligatorio.")

		  f.nombre.focus()

		return
	
		}
		
		
		if (f.tipoVia.value==-1){
			alert("Debe seleccionar un tipo de vía.");
			f.tipoVia.focus();
			return
		}
		
		if( f.nombreVia.value=="" ) {

		  alert("El campo nombre de la vía es obligatorio.")

		  f.nombreVia.focus()

		  return 

		}	
		
		if( f.localidad.value=="" ) {

		  alert("El campo localidad es obligatorio.")

		  f.localidad.focus()

		  return 

		}

		if( f.provincia.value=="" ) {

		  alert("El campo provincia es obligatorio.")

		  f.provincia.focus()

		  return 

		}	

		if( f.cp.value=="" ) {

		  alert("El campo CP (código postal)  es obligatorio.")

		  f.cp.focus()

		  return 

		}
		
		if ( f.cp.value.length > 0 && ( f.cp.value.length != 5 || isNaN(f.cp.value) ) ) {

			alert("El código postal tiene que ser numérico de 5 dígitos")

			f.cp.focus()

			return

		}

		if(f.tfno.value=="") {

			alert("Debes introducir al menos un teléfono de contacto")

			f.tfno.focus()

			return 

		}

		// Comprobamos que el formato del teléfono es correcto
		var RegExPatternTelef = /^\d+$/;
		if (!RegExPatternTelef.test(f.tfno.value)){
			alert("El teléfono debe ser numérico")
			f.tfno.focus();
			return 
		}

		
	
		// En el caso de que esté señalada otra cantidad, comprobamos que haya un número en el input "importe"
	
		if (f.euros[4].checked) {
				
				// Primero compreobamos que haya introducido una cantidad
				if (f.importe.value==''){
					alert("Al elegir 'otro importe', tienes que introducir la cantidad que deseas aportar")
					f.importe.focus();
					return 
				}

				// En caso de que haya un valor comprobaremos que sea un entero
				var RegExPattern = /^\d+$/;
				if (!RegExPattern.test(f.importe.value)){
					alert("El importe debe ser numérico (sólo dígitos)"+f.importe.value)
					f.importe.focus();
					return 
				}

		}

		if (f.tipopago[1].checked){
				
					
			if( f.titular.value=="" ) {

			  alert("El campo titular de la cuenta es obligatorio.")

			  f.nif.focus()

			  return 

			}	
			
			
			if( f.nif.value=="" ) {

			  alert("El campo NIF es obligatorio.")

			  f.nif.focus()

			  return 

			}	
			
			// Si introducen un NIE (para extranjeros) en formato XNNNNNNNNL

			// tenemos que eliminar la X y añadir 0s a la izquierda hasta completar los 8 dígitos numéricos.

			// La validación posterior es la misma que la del NIF.

			if(f.nif.value.charAt(0) == 'X' || f.nif.value.charAt(0) == 'x' || f.nif.value.charAt(0) == 'Y' || f.nif.value.charAt(0) == 'y' || f.nif.value.charAt(0) == 'Z' || f.nif.value.charAt(0) == 'z') {		

				// quitamos la X

				var nieSinX = f.nif.value.substr(1,f.nif.value.length-1)


				// quitamos cualquier espacio que tenga

				while( nieSinX.indexOf(" ") != -1 ) {

					 nieSinX = nieSinX.replace(" ","")

				}

				// si la longitud numérica es inferior a 8, añadiremos 0s a la izda

				while(nieSinX.length-1 < 8) {
				
					nieSinX = '0' + nieSinX;
					
				}
				
				// Si la letra es 'x' sumamos 10000000
				if(f.nif.value.charAt(0) == 'X' || f.nif.value.charAt(0) == 'x') {
							
					ochoNumeros = nieSinX.substr(0,8) 
					
				}
				
				// Si la letra es 'y' sumamos 10000000
				if(f.nif.value.charAt(0) == 'Y' || f.nif.value.charAt(0) == 'y') {
							
					ochoNumeros = nieSinX.substr(0,8) + 10000000
					
				}
				
				// Si la letra es 'z' sumamos 20000000
				if(f.nif.value.charAt(0) == 'Z' || f.nif.value.charAt(0) == 'z') {
				
				
					ochoNumeros = nieSinX.substr(0,8) + 20000000
					
				}
				

				if (!valida_nif ( ochoNumeros ,  nieSinX.substr(8,1)) ) {

				alert("La letra del NIF es incorrecta.")

				f.nif.focus()

				return 

				}

			}else{

				// NIF español

				if ( f.nif.value.length > 0 && (! valida_nif ( f.nif.value.substr(0,8) ,  f.nif.value.substr(8,1))) ) {

				  alert("La letra del NIF es incorrecta.")

				  f.nif.focus()

				  return 

				}

			}
		
			// Tenemos que comprobar que haya metido bien los datos de la cuenta
			if(f.cc_entidad.value=="") {
				alert("El número de cuenta debe estar completo")
				f.cc_entidad.focus()
				return
			}
	
			if(f.cc_oficina.value=="") {
				alert("El número de cuenta debe estar completo")
				f.cc_oficina.focus()
				return
			}
	
			if(f.cc_dc.value=="") {
				alert("El número de cuenta debe estar completo")
				f.cc_dc.focus()
				return
			}
	
			if(f.cc_cuenta.value=="") {
				alert("El número de cuenta debe estar completo")
				f.cc_cuenta.focus()
				return
			}
			
			$entidad=f.cc_entidad.value;
			$oficina=f.cc_oficina.value;
			$cuenta=f.cc_cuenta.value;
			$dc=f.cc_dc.value;
			
			alert($entidad+$oficina);
			$parte1=$entidad+""+$oficina;
			$parte2=$cuenta;
			
			if (($entidad!="") && ($oficina!="") && ($dc!="") && ($cuenta!="") ){
				$resultado=CalculoCC($parte1,$parte2);
				if ($resultado!=$dc){
					alert("Número de cuenta bancaria incorrecta");
					f.cc_entidad.focus()
					return;
					
				}
			}



			
		
		}
		
		

		if ( f.condiciones.checked == false ) {

			alert("Debes aceptar las condiciones de uso.")
			f.condiciones.focus()
			return

		}

	

	f.submit()

}

function CalculoCC($IentOfi,$InumCta)
{
	$APesos = Array(1,2,4,8,5,10,9,7,3,6); // Array de "pesos"
	$DC1=0;
	$DC2=0;
	$x=8;
	while($x>0) {
		$digito=$IentOfi[$x-1];
		$DC1=$DC1+($APesos[$x+2-1]*($digito));
		$x = $x - 1;
	}
	$Resto = $DC1%11;
	$DC1=11-$Resto;
	if ($DC1==10) $DC1=1;
	if ($DC1==11) $DC1=0;              // Dígito control Entidad-Oficina

	$x=10;
	while($x>0) {
		$digito=$InumCta[$x-1];
		$DC2=$DC2+($APesos[$x-1]*($digito));
		$x = $x - 1;
	}
	$Resto = $DC2%11;
	$DC2=11-$Resto;
	if ($DC2==10) $DC1=1;
	if ($DC2==11) $DC1=0;         // Dígito Control C/C

	$DigControl=$DC1+""+$DC2;   // los 2 números del D.C.
	//$DigControl="";
	return $DigControl;
}



function valida_nif (numero, letra)
{
        var letras = new Array("T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E");

        if ( isNaN(numero) )
        	return false;

        var num = Number(numero);
		
		var indice = 0;
        
        if(num<23) indice = num;
   		else indice = numero-(parseInt(num/23)*23);
   		
        if (letra.toUpperCase() != letras[indice])
        {
                //alert ("Por favor, introduzca un documento de identificación correcto");
                return false;
        }
        return true;
}

String.prototype.isEmail = function(){	
var str;
str=this;
/*alert(str);*/
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str)){
		return true
	}else{
		return false
	}
}


