var aTipos;         // Array;
var aCampos;        // Array;
var sOnEmptyMsg;    // String;
var sIfNoSelectMsg; // String;

aTipos  = new Array();

sOnEmptyMsg    = "El campo '%CAMPO%' no puede estar vacío.";
sIfNoSelectMsg = "Debe seleccionar una opción para el campo '%CAMPO%'.";

//#######################################################//
//########## FUNCIONES QUE EVALUAN UN CARACTER ##########//
//#######################################################//

function isLetter(c) {
	return (
		((c >= "a") && (c <= "z"))
		|| ((c >= "A") && (c <= "Z"))
		|| c == 'á' || c == 'é' || c == 'í' || c == 'ó' || c == 'ú'
		|| c == 'ñ' || c == 'ü'
		|| c == 'Á' || c == 'É' || c == 'Í' || c == 'Ó' || c == 'Ú'
		|| c == 'Ñ' || c == 'Ü'
		|| c == ' ' || c == '\''
	);
}

function isDigit(c) {
	return ((c >= "0") && (c <= "9"));
}

function isLetterOrDigit(c) {
	return (isLetter(c) || isDigit(c));
}

//####################################################################//
//########## FUNCIONES QUE EVALUAN UNA CADENA DE CARACTERES ##########//
//####################################################################//

function isLETRAS(s) {
	var i; // Integer

	for(i = 0; i < s.length; i++) {   
		if(!isLetter(s.charAt(i))) return false;
	}

	return true;
}

function isNUMEROS(s) {
	var i; // Integer

	for(i = 0; i < s.length; i++) {   
		if(!isDigit(s.charAt(i))) return false;
	}

	return true;
}

function isLETNUMS(s) {
	var i; // Integer

	for(i = 0; i < s.length; i++) {   
		if(!isLetter(s.charAt(i)) && !isDigit(s.charAt(i))) return false;
	}

	return true;
}

function isEMAIL(s) {
	return s.match(/^\w+([\.\-]\w+)*\@\w+([\.\-]\w+)*\.[a-z]{2,3}$/);
}

function isTELEFONO(s) {
	var i; // Integer

	for(i = 0; i < s.length; i++) {   
		if(!isDigit(s.charAt(i)) && s.charAt(i) != '-') return false;
	}

	return true;
}

function isCOMBO_SI_NO(s){
	alert(s);
}

//#####################################//
//########## OTRAS FUNCIONES ##########//
//#####################################//

function validarFormulario(oForm) {
	var sField; // String
	var sTipo;  // String
	var oField; // Object
	var oFldRf; // Object

	for(sField in aCampos) {
		oField = oForm[sField];

		// Reemplazo las ' por /' por compatibilidad
		sNewVal = oField.value.replace(/\'/g,"\\\'");
		
		if (aCampos[sField]["dependecombo"]){
			// Si en el select hay un "Si"
			if (oForm[aCampos[sField]["dependecombo"]].value == "1"){
				if(sNewVal == null || sNewVal.length == 0) {
					alert(sOnEmptyMsg.replace(/%CAMPO%/, aCampos[sField]["titulo"]));
					oField.focus();
					return false;
				} else {
					if(oField.tagName == "SELECT" && sNewVal == 0) {
						alert(sOnEmptyMsg.replace(/%CAMPO%/, aCampos[sField]["titulo"]));
						oField.focus();
						return false;
					}
				}
			}
		}

		if(oField.tagName == "SELECT") {
			if(aCampos[sField]["obligatorio"]) {
				if(sNewVal == aCampos[sField]["valorvacio"]) {
					alert(sIfNoSelectMsg.replace(/%CAMPO%/, aCampos[sField]["titulo"]));
					oField.focus();
					return false;
				}
			}
		} else {
			if(sNewVal == null || sNewVal.length == 0) {
				if(aCampos[sField]["obligatorio"]) {
					alert(sOnEmptyMsg.replace(/%CAMPO%/, aCampos[sField]["titulo"]));
					oField.focus();
					return false;
				}
			} else {
				for(sTipo in aTipos) {
					
					if(sTipo == aCampos[sField]["tipo"]) {
						if(sTipo == "CONFIRM") {
							oFldRf = oForm[aCampos[sField]["referencia"]];

							if(sNewVal != oFldRf.value) {
								alert(aTipos[sTipo]["error"].replace(/%CAMPO%/, aCampos[sField]["titulo"]));
								oField.focus();
								oField.select();
								return false;
							}
						} else {

							if(!eval(aTipos[sTipo]["funcion"].replace(/%VALOR%/, sNewVal))) {
								alert(aTipos[sTipo]["error"].replace(/%CAMPO%/, aCampos[sField]["titulo"]));
								oField.focus();
								oField.select();
								return false;
							}
						}
					}
				}
			}
		}
	}

	return true;
}

function trySubmit() {
	var oForm;    // Object
	var oSbmtFlg; // Object
	var oElement; // Object

	var bObligatorio; // Boolean
	var sTitulo;      // String
	var sTipo;        // String
	var sValorVacio;  // String
	var sReferencia;  // String

	if(trySubmit.arguments.length == 0) return false;	
	oForm = document.getElementById(trySubmit.arguments[0]);

	aCampos = new Array();
	for(i = 0; i < oForm.elements.length; i++) {
		oElement = oForm.elements.item(i);
		if(oElement.getAttribute("vValidar")) {
			if(oElement.getAttribute("vTitulo")) sTitulo = oElement.getAttribute("vTitulo");
			else sTitulo = oElement.name;

			if(oElement.getAttribute("vTipo")) sTipo = oElement.getAttribute("vTipo");
			else sTipo = "NINGUNA";

			if(oElement.getAttribute("vObligatorio")) {
				if(oElement.getAttribute("vObligatorio") == "0") {
					bObligatorio = false;
				} else bObligatorio = true;
			} else bObligatorio = false;

			if(oElement.getAttribute("vValorVacio")) sValorVacio = oElement.getAttribute("vValorVacio");
			else sValorVacio = false;

			if(oElement.getAttribute("vReferencia")) sReferencia = oElement.getAttribute("vReferencia");
			else sReferencia = false;
				
			if(oElement.getAttribute("vDependeCombo")) sDependeCombo = oElement.getAttribute("vDependeCombo");
			else sDependeCombo = false;

			aCampos[oElement.name] = new Array();
			aCampos[oElement.name]["titulo"]      = sTitulo;
			aCampos[oElement.name]["tipo"]        = sTipo;
			aCampos[oElement.name]["obligatorio"] = bObligatorio;
			aCampos[oElement.name]["valorvacio"]  = sValorVacio;
			aCampos[oElement.name]["referencia"]  = sReferencia;
			aCampos[oElement.name]["dependecombo"]= sDependeCombo;
		}
	}
	
	if(validarFormulario(oForm)) {

		if(trySubmit.arguments.length > 1) {
			oSbmtFlg = document.getElementById(trySubmit.arguments[1]);

			if(trySubmit.arguments.length > 2) {
				oSbmtFlg.value = trySubmit.arguments[2];
			} else {
				oSbmtFlg.value = 1;
			}
		}
		
		/*oBlnEnviado = document.getElementById("blnFormEnviado");
		if (oBlnEnviado != null)
			oBlnEnviado.value = 1;*/
			
		
		return true;
	} else {
		return false;
	}
}

// TIPOS DE VALIDACIONES
aTipos = {
	"NINGUNA"  : {error : ""                                                          , funcion : "true"},
	"LETRAS"   : {error : "El campo '%CAMPO%' debe contener sólo letras."             , funcion : "isLETRAS('%VALOR%')"},
	"NUMEROS"  : {error : "El campo '%CAMPO%' debe contener sólo números."            , funcion : "isNUMEROS('%VALOR%')"},
	"LETNUMS"  : {error : "El campo '%CAMPO%' debe contener sólo letras y/o números." , funcion : "isLETNUMS('%VALOR%')"},
	"EMAIL"    : {error : "El campo '%CAMPO%' no tiene datos válidos."                , funcion : "isEMAIL('%VALOR%')"},
	"TELEFONO" : {error : "El campo '%CAMPO%' no tiene datos válidos."                , funcion : "isTELEFONO('%VALOR%')"},
	"CONFIRM"  : {error : "El campo '%CAMPO%' no coincide con el campo de referencia.", funcion : ""}
};
