var XWnom="^[a-zA-ZñÑ'çÇ ]+$";								// nom - Nombre genérico.
var XWimp="^([0-9]+(([.]|[,])){0,1})([0-9]{0,2})$";			// imp - Importe.

var XWdes="¬(.*)[<>](.*)";							        // des - Descripcion Generica.

var XWtxt="^[a-zA-ZñÑ'çÇ 0-9.,:\\\\_/¿?´`!¡%&~=àèìòùáéíóúâêîôûãõÀÈÌÒÙÁÉÍÓÚÂÊÎÔÛÃÕ()-]+$";							// Campos de texto

var XWnum="^\\d+$";											// num - Numérico. (numero entero)
var XWord="^([0-9]{0,3})|([-][1])$";						// ord - Ordinal (entero de máximo 3 dígitos o el -1)
var XWind="^[S]|[N]$";										// ind - Indicador. (Solo vale "S" o "N" mayúsculas).
var XWbol="^true|false$";									// bol - Boolean (true o false).
var XWfec="^([0-3]{1})(\\d{1})/([0-1]{1})(\\d{1})/(\\d{4})$";	// fec - Fecha (del tipo dd/mm/aaaa). 
var XWcod="^[a-zA-Z0-9]+$";									// txt - Texto formado por letras y/o números.
var XWtip="^[I]|[L]|[G]|[S]$";								// tip - Caracter formado por una letra (Solo vale "I" o "L" o "G" o "S" mayúsculas).
var XWvec="^(\\d{1,5}#)+";									//vec - Valores numericos separados por un caracter (#) para generar vectores.

var XWurl = "^[\\w-./?%&~=]*$"; 							// url - Universal resource link
var XWpto = "\\d|[1][0]";									// pto - Puntos dados en una respuesta (valores del 0 al 10)

var XWmai = "^[\\w.\\-]+@(\\w+\\.)+\\w+";					// mai - Email

var XWstr="^([a-zA-Z0-9]{1,10}#)+";							// str - Valores alfanuméricos separados por un caracter (#) para generar vectores.

var expReg1="^XW([a-z]{3})([S]|[N])([0-9]{3})$";			// (XWaaaBddd), siendo a=letras minúsculas, B='S' o 'N', d=numeros enteros.  //ej: XWnomS009
var expReg2="^XW([a-z]{3})([0-9]{3})$";						// (XWaaaddd), siendo a=letras minúsculas, d=numeros enteros. //ej: XWnom010
var expReg3="^XW([a-z]{3})([S]|[N])$";						// (XWaaaB), siendo a=letras minúsculas, B='S' o 'N'. // ej: XWnomS
var expReg4="^XW([a-z]{3})$";								// (XWaaa), siendo a=letras minúsculas. // ej: XWnom


// --------------------------------------------------------------------------------------
// Devuelve true si el valor que le pasamos coincide con la expresion regular.
// --------------------------------------------------------------------------------------
function validaExpresion(val, regex) {

	if (val!="") {
		var expRegular = new RegExp(regex); // Expresion regular que se aplica.
		
		if(regex.indexOf("¬")==0){
			expRegular = new RegExp(regex.substring(1, regex.length))
			return ! val.match(expRegular);
			
		} else {
	  		return val.match(expRegular)
	  	} 
	  	
	 } else {
	 	return true;
	 }
}

// --------------------------------------------------------------------------------------
// Devuelve un string con un mensaje de error, según sea el tipo de dato a tratar.
// --------------------------------------------------------------------------------------
function dameMensaje(tipo, obj) {
	var mensaje="";
	var campo = obj.id;
	
	//campo = campo.replace("_"," ");
	campo = replaceSubstring(campo, "_", " ");
	
	
	if(tipo=="XWnom") {
		mensaje="Error when introducing "+campo+". Only alphabetical characters are valid.";
	} else if (tipo=="XWdes" || tipo=="XWtxt") {
		mensaje="Error when introducing "+campo+". Only alphabetical and digital characters are valid.";
	} else if (tipo=="XWimp") {
		mensaje="Error when introducing "+campo+". Must be a positive whole or a decimal, with maximum two decimals."; 
		mensaje+=" Decimal separators are both full stops and commas. Thousand separators are not allowed.";
	} else if (tipo=="XWnum") {
		mensaje="Error when introducing "+campo+". Must be a positive whole"; 
	} else if (tipo=="XWord") {
		mensaje="Error when introducing "+campo+". Must be a value between -1 and 999.";
	} else if (tipo=="XWind") {
		mensaje="Error when introducing "+campo+". Must have the value 'S' or 'N'.";
	} else if (tipo=="XWbol") {
		mensaje="Error when introducing "+campo+". Must have the value 'true' o 'false'.";
	} else if (tipo=="XWfec") {
		mensaje="Error when introducing "+campo+". The correct format is: day/month/year.";
	} else if (tipo=="XWcod") {
		mensaje="Error when introducing "+campo+". Characters between [a-zA-Z0-9] are not admitted.";
	} 
	
	return mensaje;
}


// --------------------------------------------------------------------------------------
//  Devuelve un string con un mensaje si el objeto que le pasamos no supera la validación de formato.
// --------------------------------------------------------------------------------------
function validarFormato(obj) {

	var mensaje="";
	var valor = obj.value;
	var nombre = obj.name;
	var validado = false;
	var tamano = 0;
	
	if (nombre.length>9) {
		prefijo = nombre.substring(0,9);
		if (validaExpresion(prefijo,expReg1)) { 
			validado=true;		
			tamano = parseInt(nombre.substring(6,9), 10);
		}
	}

	if (nombre.length>8 && !validado) {
		prefijo = nombre.substring(0,8);
		if (validaExpresion(prefijo,expReg2)) { 
			validado=true;
			tamano = parseInt(nombre.substring(5,8));
		}
	} 

	if (nombre.length>6 && !validado) {
		prefijo = nombre.substring(0,6);
		if (validaExpresion(prefijo,expReg3)){ 
			validado=true;	
		}
	}

	if (nombre.length>5 && !validado) {
		prefijo = nombre.substring(0,5);
		if (validaExpresion(prefijo,expReg4)){ 
			validado=true;		
		}
	}	
	
	if (tamano>0 && valor.length>tamano) {
		mensaje="The length of the datum is longer than that defined.";
		return mensaje;		
	} else {
		if (validado) {
			// Nombre Parámetro Correcto.
			var tipo=nombre.substring(0,5);

			if (validaExpresion(valor,eval(tipo))) {
				return mensaje;
			} else {	
				//mal formado.
				var mensaje = dameMensaje(tipo,obj);
				return mensaje;
			}
		} else {
			mensaje="Incorrect parameter name: "+nombre;
			return mensaje;
		}
	}
}

// --------------------------------------------------------------------------------------
// Consideramos que un campo es obligatorio, si tiene una S, en la posición 6 del parámetro.
// Devolverá false en dos casos:
// a) Si es obligatorio y está vacio. 
// b) Si es obligatorio, es de tipo XWord (el que usamos para las combos) y tiene valor -1 (no seleccionado).
// --------------------------------------------------------------------------------------
function validarObligatorios(formulario) {
	var nombre="";
	var valor="";
	var prefijo="";
	var errores = 0;
	var vObligatorios=new Array();
	var mensajeResultado="";
	
	for (i=0; i<formulario.elements.length;i++) {
		nombre = formulario.elements[i].name;
		valor = formulario.elements[i].value;
		id=formulario.elements[i].id;
		
		
		//id=id.replace("_"," ");
		id = replaceSubstring(id, "_", " ");
		
		obj = formulario.elements[i];
		validada=false;
		
		// validamos si expresión regular es tipo 1 (XWnomS009) 
		if (nombre.length>9) {
			prefijo = nombre.substring(0,9);

			if (validaExpresion(prefijo,expReg1)) { 
				validada=true;

				if ( (nombre.substring(5,6))=="S" && ( valor=="" || ( (nombre.substring(0,5))=="XWord" && valor=="-1") ) ) { 
					vObligatorios[errores]=id;
					errores++;
				}
			}
		}

		// validamos si expresión regular es tipo3 (XWnomS).	
		if (nombre.length>6 && !validada) {
			prefijo = nombre.substring(0,6);
		
			if (validaExpresion(prefijo,expReg3)) { 
				if ( (nombre.substring(5,6))=="S" && ( valor=="" || ( (nombre.substring(0,5))=="XWord" && valor=="-1") ) ) {
					vObligatorios[errores]=id;
					errores++;
				}
			}
		}
	}//fin for.
	
	if (errores>0) {
		var restoMensaje="";
		for (i=0; i<vObligatorios.length;i++) {
			restoMensaje+=" -  "+vObligatorios[i]+"\n";
		}
		if (errores==1) {
			mensajeResultado="The field "+vObligatorios[0] + " still needs to be completed"
		} else {
			mensajeResultado="The fields must be completed. (*):\n"+restoMensaje;
		}
	}

	return mensajeResultado;
}


// --------------------------------------------------------------------------------------
// Devuelve true si todos los campos de un formulario pasan la validación de formato.
// --------------------------------------------------------------------------------------
function validarFormatoFormulario(formulario) {


	errores = 0;
	var vFallos=new Array(); // Vamos guardando los campos mal validados.
	mensajeResultado="";
	
	for (i=0; i<formulario.elements.length;i++) {
		obj=formulario.elements[i];
		nombre=formulario.elements[i].name;
		id=formulario.elements[i].id;
		
		//id=id.replace("_"," ");
		id = replaceSubstring(id, "_", " ");
		
		prefijo="";

		//Solamente debemos validar aquellas variables que empiezan por XW.
		if (nombre.length>4) {
			prefijo=nombre.substring(0,2);

			if (prefijo=="XW") {
				if (validarFormato(obj)!="") {		
					vFallos[errores]=id;
					errores++;
				}
			}
		}
	}// fin for.	
	
	if (errores>0) {
		var restoMensaje="";
		for (i=0; i<vFallos.length;i++) {
			restoMensaje+=" -  "+vFallos[i]+"\n";
		}

		if (errores==1) {
			mensajeResultado="The field "+vFallos[0]+" has not passed the format validation";
		} else {
			mensajeResultado="Fields which have not passed the format validation:\n"+restoMensaje;
		}
	}

	return mensajeResultado;
}

function validarFuncionalFormulario(formulario) {
	errores = 0;
	var vFallos=new Array(); // Vamos guardando los campos mal validados.
	mensajeResultado="";
	
	for (i=0; i<formulario.elements.length;i++) {
		obj=formulario.elements[i];

		try{
			mensaje = validacionFuncional(obj);
			if (mensaje!=""){	//Ojo!! Esta función debe (si es necesario, implementarse en el JSP).	
				vFallos[errores]=mensaje;
				errores++;
			}
		} catch(any){}
	}// fin for.	
	
	if (errores>0) {
		var restoMensaje="";

		for (i=0; i<vFallos.length;i++) {
			restoMensaje+=" -  "+vFallos[i]+"\n";
		}
		
		if (errores==1) {
			mensajeResultado=vFallos[0];
		} else {
			mensajeResultado="Functional problems:\n"+restoMensaje;
		}
	}

	return mensajeResultado;
}


// --------------------------------------------------------------------------------------
// Función que se debe colocar en el guardar, y que comprueba que están rellenos los campos obligatorios,
// que tienen el formato correcto y que cumple las validaciones funcionales.
// -------------------------------------------------------------------------------------- 
function validarFormulario(formulario) {

	var mensajeObligatorios = validarObligatorios(formulario);
	var mensajeFormato = validarFormatoFormulario(formulario);
	var mensajeFuncional = validarFuncionalFormulario(formulario);
	if (mensajeObligatorios=="" && mensajeFormato=="" && mensajeFuncional=="") {
		return true;
	} else {
		var msgAlerta = "";
		if (mensajeObligatorios!=""){
			msgAlerta = msgAlerta + mensajeObligatorios;
		}
		if (mensajeFormato!=""){
			if (msgAlerta!=""){
				msgAlerta = msgAlerta +"\n\n"+ mensajeFormato;
			}
			else{
				msgAlerta = msgAlerta + mensajeFormato;
			}
		}
		if (mensajeFuncional!=""){
			if (msgAlerta!=""){
				msgAlerta = msgAlerta +"\n\n"+ mensajeFuncional;
			}
			else{
				msgAlerta = msgAlerta + mensajeFuncional;
			}
		}
		//alert(mensajeObligatorios+"\n\n"+mensajeFormato+"\n\n"+mensajeFuncional);
		alert(msgAlerta);
		return false;
	}
}

// --------------------------------------------------------------------------------------
// Función que se debe colocar en el onblur, y que hace tanto la validación de formato como la funcional.
// -------------------------------------------------------------------------------------- 
function validarDato(obj) {
	var mensajeFormato= validarFormato(obj);
	var mensajeTotal = mensajeFormato;
	var mensajeFuncional="";
	
	if (mensajeTotal=="") { //Ha pasado validación formato.
		try {
			mensajeFuncional= validacionFuncional(obj);
			if (mensajeFuncional!="") {
				try {
					inicializarDatos(obj); // Si se quiere implementar una función para la inicialización de los datos.
				} catch(any){}
			}

			mensajeTotal+=mensajeFuncional;

		}catch(any){}
	}
	
	if (mensajeTotal!="") {
		alert(mensajeTotal);
		obj.select();
	}
}
function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function