/*  Validation JavaScript framework, version 0.1.0
 *  (c) 2007-2008
 *
 *  Validation is freely system for validate the page's forms
 *
 *	Types of validations
 *
 *		-> required
 *			No params
 *				Check that the value form not is empty
 *
 *		-> requiredIf
 *			param FieldNameRequired the name of the field that said if the param is required
 *			param valueForRequired value of FieldNameRequired for the field was required
 *				Check that the field of form isn't empty if the value of field FielfNameRequired is valueForRequired
 *
 *		-> requiredIfNot
 *			param FieldNameRequired the name of the field that said if the param is required
 *			param valueForRequired value of FieldNameRequired for the field was required
 *				Check that the field of form isn't empty if the value of field FielfNameRequired is distint valueForRequired
 *
 *		-> cifNif
 *			No params
 *				Check that the value is a Cif or Nif
 *
 *		-> numeric
 *			No params
 *				Check that the value is a number
 *
 *		-> email
 *			No params
 *				Check tha the value is a email
 *
/*--------------------------------------------------------------------------*/


function validation(validationArray)  {

	var error = '';

	validationArray.each(function(field) {
		var fieldName = field[0];
		field[2].each(function(validationType)  {
			if(validationType[0] == 'required')  {
  				error += required(fieldName, field[1]);
  			} else if(validationType[0] == 'requiredIfNot')  {
  				error += requiredIfNot(fieldName, field[1], validationType[1], validationType[2]);
  			} else if(validationType[0] == 'requiredIf')  {
  				error += requiredIf(fieldName, field[1], validationType[1], validationType[2]);
  			} else if(validationType[0] == 'cifNif')  {
  				error += cifNif(fieldName);
  			} else if(validationType[0] == 'numeric')  {
  				error += numeric(fieldName, field[1]);
  			} else if(validationType[0] == 'email')  {
  				error += email(fieldName, field[1]);
  			}
		})
	});
		
	if('' == error)  {
		document.forms[0].submit();
	} else  {
		error = 'Se han encontrado los siguientes errores:\n' + error;
		alert(error);
		return false;
	}
}

function validation(validationArray, numForm)  {

	var error = '';

	validationArray.each(function(field) {
		var fieldName = field[0];
		field[2].each(function(validationType)  {
			if(validationType[0] == 'required')  {
  				error += required(fieldName, field[1]);
  			} else if(validationType[0] == 'requiredIfNot')  {
  				error += requiredIfNot(fieldName, field[1], validationType[1], validationType[2]);
  			} else if(validationType[0] == 'requiredIf')  {
  				error += requiredIf(fieldName, field[1], validationType[1], validationType[2]);
  			} else if(validationType[0] == 'cifNif')  {
  				error += cifNif(fieldName);
  			} else if(validationType[0] == 'numeric')  {
  				error += numeric(fieldName, field[1]);
  			} else if(validationType[0] == 'email')  {
  				error += email(fieldName, field[1]);
  			}
		})
	});
	if('' == error)  {
		document.forms[numForm].submit();
	} else  {
		error = 'Se han encontrado los siguientes errores:\n' + error;
		alert(error);
		return false;
	}
}

function required(fieldName, fieldText)  {
	return ($F(fieldName) == '')? 'El campo ' + fieldText + ' es obligatorio \n': ''
}

function requiredIf(fieldName, fieldText, fieldNameRequired, valueForRequired)  {
	return ($F(fieldNameRequired) == valueForRequired && $F(fieldName) == '')? 'El campo ' + fieldText + ' es obligatorio \n': ''
}

function requiredIfNot(fieldName, fieldText, fieldNameRequired, valueForRequired)  {
	return ($F(fieldNameRequired) != valueForRequired && $F(fieldName) == '')? 'El campo ' + fieldText + ' es obligatorio \n': ''
}

function cifNif(fieldName)  {
	var cif = $F(fieldName);
	if(cif == '') return cif;
	par = 0;
	non = 0;
	letras="ABCDEFGHKLMNPQS";
	let=cif.charAt(0);

        // Comprobamos para ver si es extrangero
        if(let == "X" || let == "x")  {
            cif = cif.substring(1,cif.length);
            let = cif.charAt(0);
        }

	if (!isNaN(let))  {
  		nif=cif;
  		return validateNif(nif)
  	}

	if (cif.length!=9)  {
  		return 'El Cif debe tener 9 dígitos\n';
  	}

	if (letras.indexOf(let.toUpperCase())==-1)  {
  		return "La letra del Cif no es válida\n";
  	}

	for (zz=2;zz<8;zz+=2)  {
  		par = par+parseInt(cif.charAt(zz));
  	}

	for (zz=1;zz<9;zz+=2)  {
  		nn = 2*parseInt(cif.charAt(zz));
  		if (nn > 9) nn = 1+(nn-10)
  			non = non+nn;
	}

	parcial = par + non;
	
	control = (10 - ( parcial % 10));
	
	if (control==10) control=0;

	if (control!=cif.charAt(8))  {
  		return "El Cif no es válido\n";
  	}
	return "";
}

function validateNif(abc)  {
	dni=abc.substring(0,abc.length-1);
	let=abc.charAt(abc.length-1);
	if (!isNaN(let))  {
  		return 'Al campo Nif le Falta la letra'
 	} else {
  		cadena="TRWAGMYFPDXBNJZSQVHLCKET"
  		posicion = dni % 23;
  		letra = cadena.substring(posicion,posicion+1);
  		if (letra!=let.toUpperCase())  {
                    return "Nif no válido\n";
   		}
 	}
	return "";
}

function numeric(fieldName, fieldText)  {
	var fieldValue = $F(fieldName);
	return (fieldValue != '' && isNaN(fieldValue))? 'El campo ' + fieldText + ' tiene que ser numérico \n': ''
}


function email(fieldName, fieldText) {

	var str = $F(fieldName);
	if(str == '')
		return ''
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr || str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr || str.indexOf(at,(lat+1))!=-1 || str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot || str.indexOf(dot,(lat+2))==-1 || str.indexOf(" ")!=-1){
		return 'El campo ' + fieldText + ', no contiene una dirección de correo valida';
	}
	
	return ''					
}
