// *******************************************************************
// *******************************************************************
// **
// ** Funciones para validation_forms.js (Sistema de validación Web)
// ** Autor y desarrollador: Fco. Javier Pérez Pacheco
// **
// ** validation_forms.js es un sistema para facilitar la validación de
// ** formularios dentro de una web.
// **
// ** El sistema debe funcionar en IE 5 y superiores, NetScape 6, Firefox 2.0
// ** y superiores y Mozilla 1 y superiores
// **
// ** FORMA DE TRABAJO
// **
// ** Esta módulo recoge los datos de validación de dos atributos
// ** que se deben añadir en los campos. Son:
// **
// ** vf_validation: Este atributo contiene una serie de letras y cada una
// ** de ellas hace referencia a una valición concreta. Estas son:
// **
// **       - "v": Comprueba si el campo está vació
// **       - "n[ '' | + | - | s ]": Comprueba si el campo es numérico
// **       - "c": Comprueba si el campo es un correo electrónico válido
// **       - "r[ '' | + | - | s ]": Comprueba si el campo es Real
// **       - "i": Comprueba si el campo es un NIF
// **       - "y": Comprueba si el campo es un CIF
// **       - "e[MIN-MAX]": Comprueba si el campo está entre MIN y MAX
// **       - "g[MIN-MAX]": Comprueba si el campo tiene entre MIN y MAX de caracteres
// **       - "d[Nombre_Campo]": Comprueba que dos campos tienen el mismo valor
// **       - "p[ o ]": Comprueba si existen caracteres no válidos en el campo. Separados por "o"
// **       - "x/EXPRESION_REGULAR/": Validad una expresión regular
// **
// ** vf_title: Este atributo contiene el nombre del campo que aparecerá en 
// ** el alert en el caso de que apareciese algún error.
// **
// *******************************************************************
// *******************************************************************

var sForm;
var sError = "";
var sErrorHeader = "";
var sErrorObligatory;
var sErrorCheckActived;
var sErrorNumber;
var sErrorNumber_s;
var sErrorNumber_p;
var sErrorNumber_n;
var sErrorReal;
var sErrorReal_s;
var sErrorReal_p;
var sErrorReal_n;
var sErrorEmail;
var sErrorNIF;
var sErrorCIF;
var sErrorBetween;
var sErrorConjuncion;
var sErrorDependent;
var sErrorWithoutCharacters;
var sErrorRange;
var sErrorRange_max;
var sErrorRange_min;
var sErrorRange_caracteres;
var sErrorDate;
			
function loadLanguage (sLanguage)
{
// ********************************************
// ** Esta función pone los textos en diferentes idiomas
// ** 
// ** sLanguage: Contiene el idioma
// ** 
// ********************************************

	switch (sLanguage) {
		case "en":
			sErrorHeader = "Next errors have ocurred: \n";
			sErrorObligatory = " is required.\n";
			sErrorCheckActived = " must be enabled.\n";
			sErrorNumber = " is not numeric.\n";
			sErrorNumber_s = " is not numeric.\n";
			sErrorNumber_p = " is not a positive number.\n";
			sErrorNumber_n = " is not a negative number.\n";
			sErrorReal = " is not a real number.\n";
			sErrorReal_s = " is not a real number.\n";
			sErrorReal_p = " is not a positive real number.\n";
			sErrorReal_n = " is not a negative real number.\n";
			sErrorEmail = " is not a correct e-mail.\n";
			sErrorNIF = " is not a correct NIF.\n";
			sErrorCIF = " is not a correct CIF.\n";
			sErrorBetween = " is not between ";
			sErrorConjuncion = " and ";
			sErrorDependent = " is different to ";
			sErrorWithoutCharacters = " there some characters that cannot be used.\n";
			sErrorRange = " must have between ";
			sErrorRange_max = " must have as maximum ";
			sErrorRange_min = " must have as minimum ";
			sErrorRange_caracteres = " characters";
			sErrorDate = " the date is not correct.\n";
		break
		default:
			sErrorHeader = "Se han producido los siguientes errores: \n";
			sErrorObligatory = " es obligatorio.\n";
			sErrorCheckActived = " debe estar activado.\n";
			sErrorNumber = " no es numérico.\n";
			sErrorNumber_s = " no es numérico.\n";
			sErrorNumber_p = " no es un número positivo.\n";
			sErrorNumber_n = " no es un número negativo.\n";
			sErrorReal = " no es número real.\n";
			sErrorReal_s = " no es número real.\n";
			sErrorReal_p = " no es número real positivo.\n";
			sErrorReal_n = " no es número real negativo.\n";
			sErrorEmail = " no es un correo válido.\n";
			sErrorNIF = " no es un NIF válido.\n";
			sErrorCIF = " no es un CIF válido.\n";
			sErrorBetween = " no se encuentra entre ";
			sErrorConjuncion = " y ";
			sErrorDependent = " es diferente a ";
			sErrorWithoutCharacters = " contiene caracteres que no son válidos.\n";
			sErrorRange = " debe tener entre ";
			sErrorRange_max = " debe tener como máximo ";
			sErrorRange_min = " debe tener como mínimo ";
			sErrorRange_caracteres = " caracteres";
			sErrorDate = " no tiene un formato de fecha válido.\n";
		break
	}
}

function validateForm(sF)
{
	validateFormLang(sF, 'es');
}

function validateFormLang(sF, sLanguage)
{
// ********************************************
// ** Esta función recoje todos los campos y según su tipo y la valición que tenga
// ** lo envía a la función correspondiente.
// ** 
// ** sForm: Contiene el name del formulario
// ** sLanguage: Contiene el idioma
// ** 
// ********************************************

	sForm = sF;

	loadLanguage (sLanguage);
	
	var cInput = document.getElementById(sForm).getElementsByTagName("input");
	for (i=0; i < cInput.length; i++) {
		var elemento = cInput[i];
		switch (elemento.type) {
			case "text":
				toSendValidationFunctions (elemento)
       				break
			case "hidden":
				toSendValidationFunctions (elemento)
       				break
			case "file":
				toSendValidationFunctions (elemento)
       				break
			case "checkbox":
				toSendValidationFunctionsCheck (elemento)
       				break
			case "password":
				toSendValidationFunctions (elemento)
       				break
			case "radio":
       				break
			case "submit":
       				break
			default:
       				break
		} // fin del switch

	}

	var cSelect = document.getElementById(sForm).getElementsByTagName("select");
	for (i=0; i < cSelect.length; i++) {
		var elemento = cSelect[i];
		toSendValidationFunctions(elemento);
	}

	var cTextArea = document.getElementById(sForm).getElementsByTagName("textarea");
	for (i=0; i < cTextArea.length; i++) {
		var elemento = cTextArea[i];
		toSendValidationFunctions(elemento);
	}

	if (sError != "") {
		sError = sErrorHeader + sError;
		alert (sError);
		document.follow = false;
	} else {
		document.follow = true;
	}

	sError = "";


}


function toSendValidationFunctions (cField)
{
// ********************************************
// ** Esta función envía a la función correspondiente
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** 
// ********************************************

if (cField.getAttribute('vf_validation')!= undefined) { // comprueba si el campo de validación existe
	for (var i = 0; i < cField.getAttribute('vf_validation').length; i++) {
		temp = cField.getAttribute('vf_validation').substring(i, i + 1);
		
		switch (temp) {
			case "v": // Comprueba si el campo está vacío
				checkEmptyField(cField);
				break
			case "c": // Comprueba si el campo es un correo
				checkFieldEmail(cField);
				break
			case "n": // Comprueba si el campo es numérico
				comp = cField.getAttribute('vf_validation').substring(i + 1, i + 2);
				if ((comp == "+") || (comp == "-") || (comp == "s")) {
					checkNumberField(cField, comp);
					i++;
				}
				else {
					checkNumberField(cField, '');
				}
				break
			case "r": // Comprueba si el campo es real
				comp = cField.getAttribute('vf_validation').substring(i + 1, i + 2);
				if ((comp == "+") || (comp == "-") || (comp == "s")) {
					checkFieldReal(cField, comp);
					i++;
				}
				else {
					checkFieldReal(cField, '');
				}
				break
			case "e": // Comprueba si el campo es un número entre dos
				var sValidar = cField.getAttribute('vf_validation');
				var sEntre = "";
				comp = sValidar.substring(i + 1, i + 2);
				if (comp == "[") {
					i++;
					i++;
					for (; sValidar.substring(i, i + 1) != "]"; i++) {
						sEntre = sEntre + sValidar.substring(i, i + 1);
					}
				}
				//alert (sEntre);
				checkFieldBetween(cField, sEntre);
				break
			case "g": // Comprueba si el campo es un número entre dos
				var sValidar = cField.getAttribute('vf_validation');
				var sEntre = "";
				comp = sValidar.substring(i + 1, i + 2);
				if (comp == "[") {
					i++;
					i++;
					for (; sValidar.substring(i, i + 1) != "]"; i++) {
						sEntre = sEntre + sValidar.substring(i, i + 1);
					}
				}
				//alert (sEntre);
				checkFieldRangeOfCharacters(cField, sEntre);
				break
			case "x": // Comprueba si el campo es un número entre dos
				var sValidar = cField.getAttribute('vf_validation');
				var sExpresion = "";
				comp = sValidar.substring(i + 1, i + 2);
				if (comp == "/") {
					i++;
					i++;
					for (; sValidar.substring(i, i + 1) != "/"; i++) {
						sExpresion = sExpresion + sValidar.substring(i, i + 1);
					}
				}
				//alert (sExpresion);
				checkFieldRegularExpressions(cField, sExpresion);
				break
			case "p": // Comprueba si existen caracter no válidos
				var sValidar = cField.getAttribute('vf_validation');
				var sCharacters = "";
				comp = sValidar.substring(i + 1, i + 2);
				if (comp == "[") {
					i++;
					i++;
					for (; sValidar.substring(i, i + 1) != "]"; i++) {
						sCharacters = sCharacters + sValidar.substring(i, i + 1);
					}
				}
				//				alert (sCharacters);
				checkFieldWithoutCharacters(cField, sCharacters);
				break
			case "f": // Comprueba si la fecha es válida
				var sValidar = cField.getAttribute('vf_validation');
				var sCharacters = "";
				comp = sValidar.substring(i + 1, i + 2);
				if (comp == "[") {
					i++;
					i++;
					for (; sValidar.substring(i, i + 1) != "]"; i++) {
						sCharacters = sCharacters + sValidar.substring(i, i + 1);
					}
				}
				//				alert (sCharacters);
				checkFieldDate(cField, sCharacters);
				break
			case "d": // Comprueba dos campos dependientes
				var sValidar = cField.getAttribute('vf_validation');
				var sNombre = "";
				comp = sValidar.substring(i + 1, i + 2);
				if (comp == "[") {
					i++;
					i++;
					for (; sValidar.substring(i, i + 1) != "]"; i++) {
						sNombre = sNombre + sValidar.substring(i, i + 1);
					}
				}
				//				alert(sNombre);
				var cField2 = document.getElementById(sNombre);
				checkFieldDependent(cField, cField2);
				break
			case "i": // Comprueba si el campo es un NIF
				checkFieldNIF(cField);
				break
			case "y": // Comprueba si el campo es un CIF
				checkFieldCIF(cField);
				break
			default:
				break
		} // fin del switch
	}
}


}


function toSendValidationFunctionsCheck (cField)
{
// ********************************************
// ** Esta función envía a la función correspondiente para CheckBoxs
// ** Aunque esta función parezca que no es útil, si lo es en el caso
// ** de que se tengan que aceptar una Condiciones
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** 
// ********************************************

if (cField.getAttribute('vf_validation')!= undefined) { // comprueba si el campo de validación existe

	for (var i=0;i<cField.getAttribute('vf_validation').length;i++){
		temp=cField.getAttribute('vf_validation').substring(i,i+1)

		switch (temp) {
			case "v":
				checkEmptyFieldCheck (cField);
       				break
			default:
       				break
		} // fin del switch
	}

}

}


function checkEmptyFieldCheck (cField)
{
// ********************************************
// ** Esta función comprueba si el valor es nulo
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** 
// ********************************************

	if (cField.checked == false)
		sError = sError + "  - " + cField.getAttribute('vf_title') + sErrorCheckActived;

}


function checkEmptyField (cField)
{
// ********************************************
// ** Esta función comprueba si el valor es nulo
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** 
// ********************************************

	if (cField.value == "")
		sError = sError + "  - " + cField.getAttribute('vf_title') + sErrorObligatory;

}


function checkNumberField (cField, sRango)
{
// ********************************************
// ** Esta función comprueba si el valor es numérico
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** sRango: Puede tener 4 estados. Vacío para números obligatoriamente sin signo,
// ** 	"s" para números positivos y negativos, "+" para positivos y "-" para negativos
// ** 
// ********************************************

	switch (sRango) {
		case "": // Números obligatoriamente sin signo
			var erNumerico = /^\d*$/;
			var sCadena = sErrorNumber;
     		break
		case "s": // Números positivos y negativos
			var erNumerico = /^[+\-]?\d*$/;
			var sCadena = sErrorNumber_s;
     		break
		case "+": // Números positivos
			var erNumerico = /^[+]?\d*$/;
			var sCadena = sErrorNumber_p;
     		break
		case "-": // Números negativos
			var erNumerico = /^-\d*$/;
			var sCadena = sErrorNumber_n;
     		break
	}
	
	if (!erNumerico.test(cField.value))
		sError = sError + "  - " + cField.getAttribute('vf_title') + sCadena;
}

function checkFieldReal (cField, sRango)
{
// ********************************************
// ** Esta función comprueba si el valor es real
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** sRango: Puede tener 4 estados. Vacío para números obligatoriamente sin signo,
// ** 	"s" para números positivos y negativos, "+" para positivos y "-" para negativos
// ** 
// ********************************************

	switch (sRango) {
		case "": // Números reales obligatoriamente sin signo
			var erReal = /^\d*((\.)\d+)?$/;
			var sCadena = sErrorReal;
     		break
		case "s": // Números reales positivos y negativos
			var erReal = /^(([+\-]?\d+)|\d*)((\.)\d+)?$/;
			var sCadena = sErrorReal_s;
     		break
		case "+": // Números reales positivos
			var erReal = /^((\+?\d+)|\d*)((\.)\d+)?$/;
			var sCadena = sErrorReal_p;
     		break
		case "-": // Números reales negativos
			var erReal = /^(-(\d+(\.\d+)?|\d*(\.\d+)))?$/;
			var sCadena = sErrorReal_n;
     		break
	}
	
	if (!erReal.test(cField.value))
		sError = sError + "  - " + cField.getAttribute('vf_title') + sCadena;
}

function checkFieldEmail (cField)
{
// ********************************************
// ** Esta función comprueba si el valor es un correo
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** 
// ********************************************
	
	var erCorreo = /^(.+@.+\..+)?$/
	if (!erCorreo .test(cField.value))
		sError = sError + "  - " + cField.getAttribute('vf_title') + sErrorEmail;

}


function checkFieldNIF (cField)
{
// ********************************************
// ** Esta función comprueba si el valor es un NIF
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** 
// ********************************************
   var erNif=/^([0-9]{8}[A-Za-z])?$/;
   if (!erNif.test(cField.value))
   		sError = sError + "  - " + cField.getAttribute('vf_title') + sErrorNIF;
}

function checkFieldCIF (cField)
{
// ********************************************
// ** Esta función comprueba si el valor es un CIF
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** 
// ********************************************
   var erCif=/^([A-Za-z][0-9]{8})?$/;
   if (!erCif.test(cField.value))
      		sError = sError + "  - " + cField.getAttribute('vf_title') + sErrorCIF;
}

function checkFieldBetween (cField, sEntre)
{
// ********************************************
// ** Esta función comprueba si el valor se encuentra entre dos números
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** sEntre: Máximo y mínimo separados por un "-"
// ** 
// ********************************************

	if (cField.value != "") {
		var arEntre = sEntre.split('-');
		if (!((arEntre[0] <= cField.value) && (arEntre[1] >= cField.value)))
      		sError = sError + "  - " + cField.getAttribute('vf_title') + sErrorBetween + arEntre[0] + sErrorConjuncion + arEntre[1] + "\n";
	}
}

function checkFieldRangeOfCharacters (cField, sEntre)
{
// ********************************************
// ** Esta función comprueba el máximo y el mínimo de caracteres que puede tener un campo
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** sEntre: Máximo y mínimo de caracteres separados por un "-"
// ** 
// ********************************************

	var sCadena = "";
		var arEntre = sEntre.split('-');
		var longitud = cField.value.length;
		if (arEntre[0] == "*") {
			if (arEntre[1] < longitud)
				sCadena = sErrorRange_max + arEntre[1] + sErrorRange_caracteres;
		} else {
			if (arEntre[1] == "*") {
					if (arEntre[0] > longitud)
						sCadena = sErrorRange_min + arEntre[0] + sErrorRange_caracteres;
				} else {
					if ((arEntre[0] > longitud) || (arEntre[1] < longitud))
						sCadena = sErrorRange + arEntre[0] + sErrorConjuncion + arEntre[1] + sErrorRange_caracteres;
				}				
		}		
		if (sCadena != "")
      		sError = sError + "  - " + cField.getAttribute('vf_title') + sCadena + ".\n";

}


function checkFieldDependent (cField1, cField2)
{
// ********************************************
// ** Esta función comprueba si dos campos tienen el mismo valor
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField1: Este campo contiene el objeto 1
// ** cField2: Este campo contiene el objeto 2
// ** 
// ********************************************

	if (cField1.value != cField2.value)
     	sError = sError + "  - " + cField1.getAttribute('vf_title') + sErrorDependent + cField2.getAttribute('vf_title') + "\n";
}


function checkFieldWithoutCharacters (cField, sCharacters)
{
// ********************************************
// ** Esta función comprueba si el valor se encuentra entre dos números
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** sCharacters: Caracteres no posibles separados por un "o"
// ** 
// ********************************************

	if (cField.value != "") {
		bValido = true;
		var arCaracteres = sCharacters.split('o');
		for (ij=0; ij < cField.value.length; ij++) {
			sCar = cField.value.substring(ij,ij+1);
			for (j=0; j<arCaracteres.length; j++) {
				if (sCar == arCaracteres[j])
					bValido = false;
			}
		} 
		
		if (bValido == false)		
      		sError = sError + "  - " + cField.getAttribute('vf_title') + sErrorWithoutCharacters;
	}
}

function checkFieldRegularExpressions (cField, sExpresion)
{
// ********************************************
// ** Esta función valida la expresion regular de sExpresion
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** 
// ********************************************

   eval ("var erExpresion = /" + sExpresion + "/;")
   if (!erExpresion.test(cField.value))
      		sError = sError + "  - " + cField.getAttribute('vf_title') + " " + cField.getAttribute('vf_error') + "\n";
}


function checkFieldDate (cField, sCharacters)
{
// ********************************************
// ** Esta función comprueba si el valor se encuentra entre dos números
// ** 
// ** CAMPOS DE LA FUNCIÓN:
// ** 
// ** cField: Este campo contiene el objeto a validar
// ** sCharacters: Separador de dia, mes y año
// ** 
// ********************************************

	var dia, mes, anio;
	var erNumerico = /^\d*$/;

	if (cField.value != "") {
		bValido = true;
		var arFecha = cField.value.split(sCharacters);
		if (arFecha.length == 3) {
			if (arFecha[0].length == 1)
				dia = '0' + arFecha[0];
			else
				dia = arFecha[0];
			if (arFecha[1].length == 1)
				mes = '0' + arFecha[1];
			else
				mes = arFecha[1];
			anio = arFecha[2];
			if (!erNumerico.test(dia))
				bValido = false;
			if (!erNumerico.test(mes))
				bValido = false;
			if (!erNumerico.test(anio))
				bValido = false;
			if (bValido == true) {
				if ((anio % 4 == 0) && (mes == '02')) {
					compDia = 29;
				} else {
					if ((mes == '01') || (mes == '03') || (mes == '05') || (mes == '07') || (mes == '08') || (mes == '10') || (mes == '12'))
						compDia = 31;
					else
						compDia = 30;
					if (mes == '02')
						compDia = 28;
				}
				if (dia > compDia)
					bValido = false;
				if (mes > 12)
					bValido = false;
			}
		} else {
			bValido = false;
		}
		if (bValido == false)
      		sError = sError + "  - " + cField.getAttribute('vf_title') + sErrorDate;
	}
}