// CONSTANTES con las expresiones regulares que vamos a usar. 
	
	//var XWnom="^([a-zA-ZñÑ'çÇ ]+(-){0,1}[a-zA-ZñÑ'çÇ ]*)+$";			// nom - Nombre genérico.
	var XWnom="^([a-zA-ZñÑ'çÇ ])+$";									// nom - Nombre genérico.
	var XWimp="^([0-9]+(([.]|[,])){0,1})([0-9]{0,2})$";			 		// imp - Importe.
	var XWine="^(([-][0-9]|[0-9])+(([.]|[,])){0,1})([0-9]{0,2})$";		// imp - Importe permite negativo.
	//var XWdes="^([^-=<>\'\"]+(-){0,1}[^-=<>\'\"]*)*$";				// des - Descripcion Generica. (todos los caracteres excepto (-,=,<,>,',")
	var XWdes="^([^=<>\'\"])*$";										// des - Descripcion Generica. (todos los caracteres excepto (=,<,>,',")
	//var XWdco="^([^-=<>\"]+(-){0,1}[^-=<>\"]*)*$";					// dco - Descripcion Generica + comilla. (todos los caracteres excepto (-,=,<,>,")
	var XWdco="^([^=<>\"])*$";											// dco - Descripcion Generica + comilla. (todos los caracteres excepto (=,<,>,")
	var XWdcc="^([^=<>])*$";											// dcc - Descripcion Generica + comilla + comillas dobles. (todos los caracteres excepto (=,<,>)
	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|true|false$";								// bol - Boolean (true o false).
	var XWfec="^([0-3]{1})([0-9]{1})/([0-1]{1})([0-9]{1})/([0-9]{4})$";	// fec - Fecha (del tipo dd/mm/aaaa). 
	//var XWafn="^([\\wñÑçÇ@ ]+(-){0,1}[\\wñÑçÇ@ ]*)+$";				// afn - Expresion alfanumerica (A-Z, a-z, 0-9, ñ, Ñ, ç, Ç, @ y -)
	var XWafn="^([\\wñÑçÇ@ ])+$";										// afn - Expresion alfanumerica (A-Z, a-z, 0-9, ñ, Ñ, ç, Ç, @ y -)
	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
	// Esta expresión es necesaria si en la aplicación se utilizan accesos a la BD sin PreparedStatement
	//var expReg5="-{2,}";												// No permitir dos menos juntos(--) evita SQL Injection 
// --------------------------------------------------------------------------------------
// 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 (val.match(expRegular)){
	    		return true;
	  	}else{
	    		return false;
	 	}
	 }else{
	 	return true;
	 }
}
// --------------------------------------------------------------------------------------
// Mejora el funcionamiento del replace simple ya que este solamente cambia 
// el primer caracter que encuentra de ese tipo. Éste cambia todos.
// --------------------------------------------------------------------------------------
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
// --------------------------------------------------------------------------------------
// 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 = replaceSubstring(campo,"_"," ");
	
	if (tipo=="XWnom"){
		mensaje="Failed to enter "+campo+". Only alphabetical characters are valid.";
	}else if (tipo=="XWdes"){
		mensaje="Failed to enter "+campo+". They are not valid the following characteristics: ',\",=,>,<,--";
	}else if (tipo=="XWdco"){
		mensaje="Failed to enter "+campo+". They are not valid the following characteristics: \",=,>,<,--";
	}else if (tipo=="XWimp"){
		mensaje="Failed to enter "+campo+". It must be a positive integer or a decimal, with a maximum of two decimal places.";
		mensaje+=" The separators are both decimal point as the comma. They are not allowed thousands separators.";
	}else if (tipo=="XWine"){
		mensaje="Failed to enter "+campo+". It must be an integer or a decimal, with a maximum of two decimal places.";
		mensaje+=" The separators are both decimal point as the comma. They are not allowed thousands separators.";
	}else if (tipo=="XWnum"){
		mensaje="Failed to enter "+campo+". It must be a positive integer";
	}else if (tipo=="XWord"){
		mensaje="Failed to enter "+campo+". It must be a value between -1 and 999.";
	}else if (tipo=="XWind"){
		mensaje="Failed to enter "+campo+". You must have the courage 'S' or 'N'.";
	}else if (tipo=="XWbol"){
		mensaje="Failed to enter "+campo+". You must have the courage 'true' or 'false'.";
	}else if (tipo=="XWfec"){
		mensaje="Failed to enter "+campo+". The format is correct: dd/mm/aaaa.";
	}else if (tipo=="XWafn"){
		mensaje="Failed to enter "+campo+". Only alphanumeric characters are valid and '-'.";
	}
	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),10);
		}
	} 
	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 data is larger than the defined, "+tamano+".";
		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="Parameter name Bad: "+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=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="Lack fill in the field "+vObligatorios[0];
		}else{
			mensajeResultado="You must fill in the fields Required. (*):\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("_"," ");
		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]+" failed the validation Format";
		}else{
			mensajeResultado="Fields that have not passed the validation Format:\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{
		alert(mensajeObligatorios+"\n\n"+mensajeFormato+"\n\n"+mensajeFuncional);
		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();
		return false;
	}
	return true;
}	 