/*
 *@Autor Andrés Omar Brizuela
 *@Year 2010
*/
var Validador = new Array();
	/**** POR DEFECTO VALIDADOR EXPREG ****/
		var PorDefectoRegExp = new Array();
		PorDefectoRegExp.push({nombre: "mail", regexp: /(^[0-9a-z]([0-9a-z_\.-]*)@([0-9a-z_\.-]*)([.][a-z]{3})$)|(^[0-9a-z]([0-9a-z_\.-]*)@([0-9a-z_\.-]*)([.][a-z]{2})$)|(^[a-z]([a-z_\.-]*)@([a-z_\.-]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i });
		PorDefectoRegExp.push({nombre: "numero", regexp: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/ });
		PorDefectoRegExp.push({nombre: "cadena", regexp: /(^-?\D\D*\.\D*$)|(^-?\D\D*$)|(^-?\.\D\D*$)/ });
		PorDefectoRegExp.push({nombre: "entero", regexp: /(^-?\d\d*$)/ });
	/**** FIN VALIDADOR EXPREG ****/
	/**** POR DEFECTO VALIDADOR FUNCIONES ****/
		var PorDefectoFuncion = new Array();
		PorDefectoFuncion.push({nombre: "rq", funcion: "validaRQ", parametros: false});
		PorDefectoFuncion.push({nombre: "multiplechoice", funcion: "validaMChoice", parametros: true});
		PorDefectoFuncion.push({nombre: "repetir", funcion: "validaReplica", parametros: true});
		PorDefectoFuncion.push({nombre: "fecha", funcion: "validaFecha", parametros: false});
		PorDefectoFuncion.push({nombre: "dia", funcion: "validaDia", parametros: false});
		PorDefectoFuncion.push({nombre: "mes", funcion: "validaMes", parametros: false});
		PorDefectoFuncion.push({nombre: "ano", funcion: "validaAno", parametros: false});
	/**** FIN VALIDADOR FUNCIONES ****/
	
var MensajesError = new Array();
	/**** POR DEFECTO MENSAJES DE ERROR ****/
		var PorDefectoMensajes = new Array();
		PorDefectoMensajes.push({nombre: "pordefecto", error: "Todos los campos son obligatorios."});
		PorDefectoMensajes.push({nombre: "multiplechoice", error: "Por favor respondé todas las preguntas."});
		PorDefectoMensajes.push({nombre: "repetir", error: "Los datos no coinciden."});
		PorDefectoMensajes.push({nombre: "fecha", error: "Ingrese una fecha correcta (ej.: dd/mm/aaaa)."});
		PorDefectoMensajes.push({nombre: "dia", error: "Ingrese un número de día correcto."});
		PorDefectoMensajes.push({nombre: "mes", error: "Ingrese un número de mes correcto"});
		PorDefectoMensajes.push({nombre: "ano", error: "Ingrese un número de año correcto"});
		PorDefectoMensajes.push({nombre: "mail", error: "Ingrese un mail correcto (ej.: ejemplo@ejemplo.com.ar)."});
		PorDefectoMensajes.push({nombre: "numero", error: "Tiene que ser un número."});
		PorDefectoMensajes.push({nombre: "cadena", error: "Tiene que ser texto."});
		PorDefectoMensajes.push({nombre: "entero", error: "El dato ingresado es invalido."});
	/**** FIN MENSAJES DE ERROR ****/

var FunPrintError = "PrintErrorDF";
var AutoDetectForm = false;
/**** FUNCIONES GENERAL ****/
	/*
	 *	Esta funcion elimina el espacio en blanco que hay adelante o atras del string enviado.
	 *	
	 *	@parametro	STRING
	 *	@return		STRING
	*/
	function trimAll(strValue){
		
		var objRegExp = /^(\s*)$/
		
		//Elimino espacios en blanco
		if(objRegExp.test(strValue)) {
		   strValue = strValue.replace(objRegExp, '')
		   if( strValue.length == 0){
		      return strValue
		   }
		}
		
		objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/
		if(objRegExp.test(strValue)) {
		   strValue = strValue.replace(objRegExp, '$2')
		}
		
		return strValue
	
	}
/**** FIN FUNCIONES GENERAL ****/
/**** FUNCIONES VALIDA ****/
	var RegExpFecha = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
	var RegExpEntero = /(^-?\d\d*$)/

	function validaRQ (input, form){
	   try{
            input.value = trimAll(input.value);
       }catch(err){
            
       }
		Value = input.value;
		
		switch (input.type){
			case "checkbox":
            case "radio":
				
				if(input.checked != true){
					return false
				}
				
				break;
			default:
				
				if(Value.length < 1){
					return false;
				}
				
				break;
				
		}

		return true;
	}
	
	function validaMChoice (input, form, parametro){
		var CantOption;
		var GrupoNombre;
		var TypeInput;
		
		/**/
		if(parametro != undefined && parametro != ""){
			CantOption = parseFloat(parametro); 
		}else{
			CantOption = parseFloat("1");
		}
		
		if(input.name != undefined && input.name != ""){
			GrupoNombre = input.name;
		}else{
			return false;
		}
		
		TypeInput = input.type;
		/**/
				
		OpcionElegida = 0;
		InputBusqueda = document.getElementsByName(GrupoNombre);
		
		for (contAux=0;contAux<InputBusqueda.length;contAux++){

			if(InputBusqueda[contAux].disabled == false && InputBusqueda[contAux].type == TypeInput){
				
				Checked = InputBusqueda[contAux].checked;				
				if(Checked == true){
					OpcionElegida++;
				}
								
			}
			
		}
			
		if(OpcionElegida >= CantOption){
			return true;
		}else{
			return false;
		}
	}

	function validaReplica(input, form, parametro){
		var idComparar;
		var Value;
		/**/
		if(parametro == undefined || parametro == ""){
			return false;
		}
		
		idComparar = parametro;
		Value = input.value;
		/**/
		
		InputCompara = document.getElementById(idComparar);
		if(InputCompara.value == Value){
			return true;
		}
		
		return false;
	}

	function validaFecha(input, form){

		var Value = input.value;

		if(!RegExpFecha.test(Value)){		
			return false;		
		}else{
			var strSeparator = strFecha.substring(2,3) 
			var arrayDate = strFecha.split(strSeparator) 

			var arrayValidaMes = {  '01' : 31,'03' : 31, 
			                    	'04' : 30,'05' : 31,
			                    	'06' : 30,'07' : 31,
			                    	'08' : 31,'09' : 30,
			                    	'10' : 31,'11' : 30,
									'12' : 31}

			var intDia = parseInt(arrayDate[0],10) 			
			var intMes = parseInt(arrayDate[1],10)
			var intAno = parseInt(arrayDate[2])

			if(arrayValidaMes[""+intMes+""] != null){
				if(intDia <= arrayValidaMes[arrayDate[1]] && intDia != 0){
			    	return true;
  				}
			}

			if (intMes == 2) {
   				if (intDia > 0 && intDia < 29) {
			    	return true;
			   	}else if (intDia == 29) {
			    	if ((intAno % 4 == 0) && (intAno % 100 != 0) || (intAno % 400 == 0)) {
			        	return true
			     	}
			   	}
			}
		}  

		return false;
	}
	
	function validaDia(input, form){		
		var Value = input.value;
		
		if(!RegExpEntero.test(Value)){
			return false;
		}else{
			if(Value.length > 2 || Value < 1 || Value > 31){
				return false;
			}
		}
		
		return true;
	}
	
	function validaMes(input, form){		
		var Value = input.value;
		
		if(!RegExpEntero.test(Value)){
			return false;
		}else{
			if(Value.length > 2 || Value < 1 || Value > 12){
				return false;
			}
		}
		
		return true;
	}
	
	function validaAno(input, form){		
		var Value = input.value;
		
		if(!RegExpEntero.test(Value)){
			return false;
		}else{
			if(Value.length != 4){
				return false;
			}
		}
		
		return true;
	}
/**** END FUNCIONES ****/

function Validar(objForm){
		
	for (cont=0;cont<objForm.length;cont++){
		
		ElementoForm = objForm.elements[cont];
		
		if(ElementoForm.disabled == false && ElementoForm.type != "hidden"){
			Condiciones = ElementoForm.getAttribute("validar");
            
			if(Condiciones != null){
				
				arrCondiciones = Condiciones.split("::");
				
				for(idCondicion in arrCondiciones){
				    if(/(^-?\d\d*$)/.test(idCondicion)){
					   /**/
    					Condicion = arrCondiciones[idCondicion];
    					/**/
       					arrCondicion = Condicion.split("_");
                        /**/
    					for(idConValida in Validador){
    					   if(/(^-?\d\d*$)/.test(idConValida)){
        						/**/
        						ConValida = Validador[idConValida];
        						/**/
        						if(arrCondicion[0] == ConValida.nombre){
        							if(ConValida.funcion != null){
        								ExecFun = ConValida.funcion+"(ElementoForm, objForm";
        								if(ConValida.parametros){
        								    strParametros = "";
        									for(idparametro in arrCondicion){
        									/**/
        									parametro = arrCondicion[idparametro];
        									/**/
        										if(parametro != arrCondicion[0]){
        											if(strParametros != ""){
        												strParametros = strParametros+",";
        											}
        											strParametros = strParametros+parametro;
        										}
        									}
        									ExecFun = ExecFun+",'"+strParametros+"'";
        								}
        								ExecFun = ExecFun+")";
        								
        								if(!eval(ExecFun)){
        									eval(FunPrintError+'("'+ConValida.nombre+'", ElementoForm)');
        									return false;
        								}
        							}else if(ConValida.regexp != null){
        							    if(ElementoForm.value != ""){
            								if(!ConValida.regexp.test(ElementoForm.value)){
            									eval(FunPrintError+'("'+ConValida.nombre+'", ElementoForm)');
            									return false;									
            								}
                                        }
        							}
        						}
                            }
    					}
    					
    				}
                }
				
			}
		}
		
	}
	
	return true;
}

function PrintErrorDF(nombreError, Elemento){
	
	for (idMensaje = 0; idMensaje < MensajesError.length; idMensaje++ ){
		/**/
		Mensaje = MensajesError[idMensaje];
		/**/
		if(Mensaje.nombre == nombreError){
			window.alert(Mensaje.error);
			Elemento.focus();
			return true;
		}		
	}
	
	for (idMensaje = 0; idMensaje < MensajesError.length; idMensaje++ ){
		/**/
		Mensaje = MensajesError[idMensaje];
		/**/
		if(Mensaje.nombre == "pordefecto"){
			window.alert(Mensaje.error);
			Elemento.focus();
			return true;
		}		
	}
	
}

function onLoadValidador(){
	
	if(AutoDetectForm != false){
		for(x=0; x<document.forms.length; x++){
			document.forms[x].setAttribute("onsubmit", "function(){return Validar(this)}");
		}
	}
	
}

function iniValidador(AutoProceso){
    if(AutoProceso != undefined){
        AutoDetectForm = AutoProceso;
    }

	for (idValoresValida in PorDefectoRegExp){
		/**/
		ValoresValida = PorDefectoRegExp[idValoresValida];
		/**/
		Validador.push(ValoresValida);       
	}
	for (idValoresValida in PorDefectoFuncion){
		/**/
		ValoresValida = PorDefectoFuncion[idValoresValida];
		/**/
		Validador.push(ValoresValida);	
	}
	
	for (idMensaje in PorDefectoMensajes){
		/**/
		Mensaje = PorDefectoMensajes[idMensaje];
		/**/
		MensajesError.push(Mensaje);
	}
	
	// ************ ON LOAD *********** //// Dean Edwards/Matthias Miller/John Resig
	// Para Mozilla/Opera9
	if (document.addEventListener) {
	  document.addEventListener("DOMContentLoaded", onLoadValidador, false);
	}
	// Safari
	if (/WebKit/i.test(navigator.userAgent)) { // sniff
	  var _timer = setInterval(function() {
	    if (/loaded|complete/.test(document.readyState)) {
	      onLoadValidador(); // call the onload handler
	    }
	  }, 10);
	}
	// Otro navegador
	window.onload = onLoadValidador;
	
}
iniValidador();
