// JavaScript Document
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
  return false;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
var p,i,x;  if(!d) d=document; 
if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}

if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function YY_checkform() { //v4.71
//copyright (c)1998,2002 Yaromat.com
  var a=YY_checkform.arguments,oo=true,v='',s='',err=false,r,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
  document.MM_returnValue = true;
  for (i=1; i<a.length;i=i+4){
    if (a[i+1].charAt(0)=='#'){r=true; a[i+1]=a[i+1].substring(1);}else{r=false}
    o=MM_findObj(a[i].replace(/\[\d+\]/ig,""));
	o1=MM_findObj(a[i+1].replace(/\[\d+\]/ig,""));
	v=o.value;t=a[i+2];

 if (o.type=='text'||o.type=='password'||o.type=='hidden'){
      if (r&&v.length==0){err=true}
      if (v.length>0)
      if (t==1){ //fromto
        ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){err=true}
      } else if (t==2){
		rx=new RegExp("^[A-Za-z0-9_ñÑ\.=-]+@[A-Za-z0-9_ñÑ\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v))err=true;
      } else if (t==3){ // date
        ma=a[i+1].split("#");at=v.match(ma[0]);
		if(at){
          cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
          dte=new Date(cy,cm,cd);
          if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){err=true};
        }else{err=true}
      } else if (t==4){ // time
        ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){err=true}
      } else if (t==5){ // check this 2
            if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!o1.checked){err=true}
      } else if (t==6){ // the same
            if(v!=MM_findObj(a[i+1]).value){err=true}
      }
    } else
    if (!o.type&&o.length>0&&o[0].type=='radio'){
          at = a[i].match(/(.*)\[(\d+)\].*/i);
          o2=(o.length>1)?o[at[2]]:o;
      if (t==1&&o2&&o2.checked&&o1&&o1.value.length/1==0){err=true}
      if (t==2){
        oo=false;
        for(j=0;j<o.length;j++){oo=oo||o[j].checked}
        if(!oo){s+='* '+a[i+3]+'\n'}
      }
    } else if (o.type=='checkbox'){
      if((t==1&&o.checked==false)||(t==2&&o.checked&&o1&&o1.value.length/1==0)){err=true}
    } else if (o.type=='select-one'||o.type=='select-multiple'){
      if(t==1&&o.selectedIndex/1==0){err=true}
    }else if (o.type=='textarea'){
      if(v.length<a[i+1]){err=true}
    }
    if (err){s+='* '+a[i+3]+'\n'; err=false}

}

//si pais = esp && provincia no seleccionada
  pa=MM_findObj('pais');
  pr=MM_findObj('provincia');
  if ((pa && pr) && ((pa.value == '192') && (pr.value == '0'))) s+='* Debe seleccionar una provincia\n';

  //validar nif
  dn=MM_findObj('dni');
  td=MM_findObj('tipo_documento');
  if (td && td.value == "dni" && dn.value !="" && !validarNIF(dn.value) && pa.value != '210') s+='* Debe introducir un DNI válido\n';

  dn=MM_findObj('nif');
  td=MM_findObj('tipodoc');
  if (td && td.value == "NIF" && dn.value !="" && !validarNIF(dn.value) && pa.value != '210') s+='* Debe introducir un DNI válido\n';

  if (s!=''){alert('La siguiente información está incompleta o contiene errores:\t\t\t\t\t\n\n'+s)}
  document.MM_returnValue = document.MM_returnValue && (s=='');

}


//validacion NIF
function validarNIF(nif)
{
	dni=nif.substring(0,nif.length-1)
	let=nif.charAt(nif.length-1)
	if (!isNaN(let)) return false;

	cadena="TRWAGMYFPDXBNJZSQVHLCKET"
	posicion = dni % 23
	letra = cadena.substring(posicion,posicion+1)
	if (letra!=let.toUpperCase()) return false;
	return true;
}




/*
function paisprovincia(){
if (document.form.pais.value!="ESP" && document.form.pais.value!="OTR"){
    document.form.provincia.value="";
	document.form.provincia.disabled=true;
	}
else {
	document.form.provincia.disabled=false;
	}
}
*/
function valida_nombre_reenviar(mailto) {
	if (document.forms[0].nombre.value == "") {
		alert("Debes introducir tu nombre");
		document.forms[0].nombre.focus();
		return false;
	} else if (document.forms[0].email.value == "") {
		alert("Debes introducir tu email");
		document.forms[0].email.focus();
		return false;
	}
	if (!mailto) {
		if (document.forms[0].nombre1.value == "") {
			alert("Debes introducir el nombre de un/a amigo/a");
			document.forms[0].nombre1.focus();
			return false;
		} else if (document.forms[0].email1.value == "") {
			alert("Debes introducir el email de un/a amigo/a");
			document.forms[0].email1.focus();
			return false;
		}
	}
	return true;
}
function mailto() {
	if (valida_nombre_reenviar(true)) MM_openBrWindow('web/mailto.php?nombre='+document.forms[0].nombre.value,'mailto','width=1,height=1')
	return false;
}

function paisprovincia(){
if (document.form.pais.value != "192"){
	//alert("El campo provincia no debe ser rellenado");
	document.form.telefono.value = "";
	document.form.telefono.disabled = true;
	document.form.provincia.value = "0";
	document.form.provincia.disabled = true;
	if (document.form.prov) document.form.prov.value = "1";
	document.form.tipo_documento.selectedIndex = 1;
	}
else {
	document.form.provincia.disabled = false;
	if (document.form.prov) document.form.prov.value = "";
	document.form.telefono.disabled = false;
	document.form.tipo_documento.selectedIndex = 0;
	}
}

function validar_reenvio() {
	YY_checkform('form','nombre_from','#q','0','Tu nombre','email_from','#q','0','Tu email');
	if (document.MM_returnValue) {
		if (!Validate_Email_Address(eval("cont.document.forms[0].email_from.value"))) {
			alert("Por favor, revisa que la dirección de correo electrónico sea válida");
			cont.document.forms[0].email_from.focus();
			document.MM_returnValue = false;
		}
		document.MM_returnValue = document.MM_returnValue && validar_emails();
	}
}

function validar_emails() {
	for (i = 1;i<=3; i++) {
		email = eval("cont.document.forms[0].email"+i);
		nombre = eval("cont.document.forms[0].nombre"+i);
		
		if (nombre.value != "" & email.value == "") { alert("Por favor, introduce el email de tu amigo");email.focus();break;}
		if (email.value != "" & nombre.value == "") { alert("Por favor, introduce el nombre de tu amigo");nombre.focus();break;}
		if (email.value!="" && !Validate_Email_Address(email.value)) {
			alert("Por favor, revisa que la dirección de correo electrónico sea válida");
			email.focus();
			break;
		}
	}
	return (i==4);
}

function Validate_String(string, return_invalid_chars) {
	valid_chars = '1234567890-_.^~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    invalid_chars = '';
    if(string == null || string == '') return(true);
    //For every character on the string.   
	for(index = 0; index < string.length; index++) {
            ch = string.substr(index, 1);                        
            //Is it a valid character?
            if(valid_chars.indexOf(ch) == -1) {
              //If not, is it already on the list of invalid characters?
              if(invalid_chars.indexOf(ch) == -1) {
                //If it's not, add it.
                if(invalid_chars == '') invalid_chars += ch;
                else invalid_chars += ', ' + ch;
              }
            }
	}
    //If the string does not contain invalid characters, the function will return true.
    //If it does, it will either return false or a list of the invalid characters used
    //in the string, depending on the value of the second parameter.
    if(return_invalid_chars == true && invalid_chars != '') {
           		last_comma = invalid_chars.lastIndexOf(',');
           		if(last_comma != -1) invalid_chars = invalid_chars.substr(0, $last_comma) + 
	              ' and ' + invalid_chars.substr(last_comma + 1, invalid_chars.length);
           			return(invalid_chars);
    } else return(invalid_chars == ''); 
}

function Validate_Email_Address(email_address)
{
 //Assumes that valid email addresses consist of user_name@domain.tld
 at = email_address.indexOf('@');
 dot = email_address.lastIndexOf('.');
 if(at == -1 || 
    dot == -1 || 
    dot <= at + 1 ||
    dot == 0 || 
    dot == email_address.length - 1)
    return(false);
 user_name = email_address.substr(0, at);
 domain_name = email_address.substr(at + 1, email_address.length);  
 if(Validate_String(user_name) === false || 
    Validate_String(domain_name) === false)
    return(false);     
 return(true);
}


//funcions hazte_socio
function validacuota()
{
  var convertedString = document.form.cuota.value.split(',');
  document.form.cuota.value = convertedString.join('.');
  if (document.form.cuota.value != ""){
	  if (isNaN(parseFloat(document.form.cuota.value))){
	  alert("El importe es incorrecto");
	  }
	  else {
		if (document.form.periodo[0].checked) document.form.importe.value = parseFloat(document.form.cuota.value) * parseInt(document.form.periodo[0].value);
		if (document.form.periodo[1].checked) document.form.importe.value = parseFloat(document.form.cuota.value) * parseInt(document.form.periodo[1].value);
		if (document.form.periodo[2].checked) document.form.importe.value = parseFloat(document.form.cuota.value) * parseInt(document.form.periodo[2].value);
	  if (document.form.importe.value < parseFloat("24")) {
	  	alert("La cuota mínima anual es de 24 €.");
		}
	  }
  }
  else {
  document.form.importe.value = "99999"
  }
}

function calculaimporte()
{
  document.form.importe.value = parseFloat(document.form.cuota.value) * parseInt(document.form.periodo.value)
	  if (document.form.importe.value < parseFloat("48")) {
	  	alert("La cuota mínima anual es de 48 €.");
		}

}

function limpiacantidad()
{
  document.form.importe.value = "99999";
  document.form.cuota.value = "";
  if (document.form.periodo) document.form.periodo.value = "12";
}
function iniFecha(dia, mes, anio) {
	for (i=0;i<document.form.dia.options.length;i++) {
		if (document.form.dia.options[i].value == dia) document.form.dia.options[i].selected = true;
	}
	for (i=0;i<document.form.mes.options.length;i++) {
		if (document.form.mes.options[i].value == mes) document.form.mes.options[i].selected = true;
	}
	for (i=0;i<document.form.anio.options.length;i++) {
		if (document.form.anio.options[i].value == anio) document.form.anio.options[i].selected = true;
	}
}

function almenosdosletras(inputString)
{
  var searchForNumbers = /\d/;
  if (searchForNumbers.test(inputString)) {	
  	alert("Por favor, revisa el texto. El campo contiene números");
	}
  else if (inputString.length > 0 && inputString.length < 2) {
    alert("Por favor, revisa el texto. El campo no contiene suficientes caracteres");
	}
}

function almenosncaracteres(inputString,longitud)
{
	if (inputString.length > 0 && inputString.length < longitud) {
    alert("Por favor, revisa el texto. El campo no contiene suficientes caracteres");
	}
}

function solonumeros(inputString)
{
//  var searchForLetras = /\D+\_+\W+\s+\S+/;
  var searchForLetras = /\D/;
  if (searchForLetras.test(inputString)) {	
  	alert("Por favor, revisa el texto. El campo debe contener sólo números");
	}
}

function stringToUppercase(inputString)
{
  return inputString.toUpperCase();
}

// Funcion que chequea los dos digitos de control
// Creada originalmente por Daniel Rodriguez y Joaquin
// Bravo y publicada en 
// http://programacion.com/html/articulo/tw_ccc/
function DigitoControl(cadena){
	var cifras = new Array(1,2,4,8,5,10,9,7,3,6);
    var chequeo = 0;
    for (var i=0; i < cifras.length; i++){
		chequeo += parseInt(cadena.charAt(i)) * cifras[i];
	}
    chequeo = 11 - (chequeo % 11);
	if (chequeo == 11) {chequeo = 0;}
	if (chequeo == 10) {chequeo = 1;}
    return chequeo;
}

// Funcion que comprueba que "valor" es un numero entero
function EsNumeroEntero(valor){
    var cadena = valor.toString();
	var longitud = cadena.length;
	if (longitud == 0){return false;}
	var ascii = null;
    for (var i=0; i<longitud; i++) {
		ascii = cadena.charCodeAt(i);
        if (ascii < 48 || ascii > 57){return false;}
    }
	return true;
}

// Funcion que valida el codigo de cuenta cliente
function ValidarCCC(entidad,oficina,dc,nc) {

	// Comprobamos que solo hemos introducido numeros
	if (!EsNumeroEntero(entidad)){
		alert("Debes introducir el número de entidad bancaria");
		return false;
	}
	if (!EsNumeroEntero(oficina)){
		alert("Debes introducir el número de oficina");
		return false;
	}
	if (!EsNumeroEntero(dc)){
		alert("Debes introducir los dos dígitos de control");
		return false;
	}
	if (!EsNumeroEntero(nc)){
		alert("Debes introducir el número de cuenta");
		return false;
	}
	// Comprobamos el primer digito de control
	var primer_control="00"+entidad+oficina;
	var primer_digito=DigitoControl(primer_control);
	if (primer_digito != dc.charAt(0)){
		alert("El código de cuenta cliente proporcionado no es válido");
		return false;
	}

	// Comprobamos el segundo digito de control
	var segundo_control=nc;
	var segundo_digito=DigitoControl(segundo_control);
	if (segundo_digito != dc.charAt(1)){
		alert("El código de cuenta cliente proporcionado no es válido");
		return false;
	}
}

function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=600,height=500');");
}
function ValidaNIF()
{
  document.form.NIF.value = document.form.NIF.value.toUpperCase();
  
  if (document.form.tipodoc.value == "NIF") {
//  else if (document.form.NIF.value == "") 
    
  var longitud = document.form.NIF.value.length
  var letraNIF = document.form.NIF.value.substring(longitud-1);
  var numeroNIF = document.form.NIF.value.substring(0,longitud-1);
   
  var letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
  var numero = numeroNIF%23;
  if (letraNIF != letras.substring(numero,numero+1)){
	  alert("Por favor, comprueba que has introducido correctamente el NIF, incluyendo la letra");
	  document.form.nombrebanco.focus();
	  }
  }
return;
}

function rellenafecha()
{
  document.form.fecha.value = document.form.mes.value + "/" + document.form.dia.value + "/" + document.form.anio.value;
  if (parseInt(document.form.anio.value) > 1986) {
	  MM_openBrWindow('pop_menor.php','Menor','scrollbars=yes,width=400,height=200');
  }
}

function YY_checkbanco()
{
	if (document.form.formapago[0].checked) {
		YY_checkform('socio','nombretitular','#q','0','Nombre del titular','entidad','#0001_9999','1','El código de la entidad bancaria en la que quieres domiciliar el pago de tu cuota \(consta de 4 dígitos\)','sucursal','#0000_9999','1','El número de la oficina bancaria en la que quieres domiciliar el pago de tu cuota \(consta de 4 dígitos\)','dc','00_99','1','Los dígitos de control no son válidos','cuenta','#0000000000_9999999999','1','El número de la cuenta bancaria en la que quieres domiciliar el pago de tu cuota \(consta de 10 dígitos sin contar los dígitos de control DC\)');
	}
}
function procesanombre(inputString) {
	almenosdosletras(inputString);
	if ((document.form.nombre.value != "" && document.form.apellido1.value != "") || document.form.sociedad.value != "" ) {
		document.form.nombresi.value = "1";
	}
	else {
		document.form.nombresi.value = "";
	}
	if (document.form.sociedad.value != "" ) {
		document.form.tipodoc.value = "CIF";
	}
	else {
		document.form.tipodoc.value = "NIF";
	}
}


//donativo
function YY_checkformapago(f) {
  document.MM_returnValue = true;
	if (!f.formapago[0].checked && !f.formapago[1].checked) {
		alert("Debe seleccionar una forma de pago");
		document.MM_returnValue = false;
	}

}

