/***************************************************************************
*
*	clsValidator  - Version 1.0
*	Copyleft: Horacio R. Valdez
*	website: www.hvaldez.com.ar/javascript/clsValidator/sp
*	Soporte: info@hvaldez.com.ar
*	Creado: 05.2004
*
**************************************************************************** 
* Este script es distribuido bajo la licencia GNU/LGPL
****************************************************************************
* Gracias a:
*	Canal #javascript en Undernet
*	foros del web (www.forosdelweb.com)
*
****************************************************************************
Propósito: validar campos y combos en un formulario HTML
****************************************************************************
Forma de uso:
	en documentos HTML:
	var objValidar = new clsValidar;

	todos los métodos se invocan de la misma manera
	objeValidator.nombreDelMetodo("campo","mensaje");	

	campo: nombre del campo que se quiere validar.
	mensaje: mensaje de error si cumple o no la validación.
	Ej. objValidar.Vacio("Usuario","Debe completar el nombre de usuario");


Métodos:
1.	objValidar.setEncabezado(valor)
	Objetivo: Setea el titulo del mensaje de error.
	Parámetros: String;
	Ej: objValidar.setEncabezado("[- Se encontraron errores en el formulario -] ");
	   
2.	objValidar.setErrorColor(valor);
	Objetivo: Setea el color de fondo para los campos con error;
	Parámetros: String;
	Ej: objValidar.setErrorColor("#FFF4F4");
	
3.	objValidar.Vacio(campo,msg);
	Objetivo: verifica si el campo es vacío. 
	Parámetros: campo String, msg String;
	Ej: objValidar.Vacio("Usuario","Debe completar el nombre de usuario");

4.	objValidar.Email(campo,msg);
	Objetivo: verifica si el email ingresado es válido. 
	Parámetros: campo String, msg String;
	Ej: objValidar.Email("email", "El email no es válido");	

5.	objValidar.Fecha(campo, msg);
	Objetivo: validar el formato de una fecha.
	Parámetros: campo String, msg String;
	Ej: objValidar.Fecha("fechaNacimiento","La fecha no es válida. Formato dd/mm/aaaa");

6.	objValidar.Iguales(campo1, campo2, msg);
	Objetivo: dado 2 campos verifica que estos sean iguales
	Parámetros: campo1 String, campo2 String, msg String;
	Ej: objValidar.Iguales("passwd1","passwd2","Los passwords son distintos");

7.	objValidar.Longitud(campo, longitud, msg);
	Objetivo: verifica que la longitud del campo sea mayor, menor o igual que un número 
	de caracteres dado
	Parámetros: campo String, longitud, integer, msg String;
	Ej: objValidar.Longitud("passwd1", ">", 8, "El password debe ser mayor a 8 caracteres"); 
		objValidar.Longitud("passwd1", "<", 6, "El password debe ser menor a 6 caracteres"); 
		objValidar.Longitud("passwd1", "=", 4, "El password debe ser igual a 4 caracteres");	

8. 	objValidar.Validar();
	Objetivo evaluar si hubieron errores en los campos del formulario. Devuelve TRUE si todo
	está ok y FALSE si hay errores.
	
9.	objValidar.getErrors();
	Objetivo: muestra en pantalla un informe con todos los errores que ocurrieron.
	Ej:
	
	if (objValidar.Validar()) document.frmContacto.submit() 	
	else objValidar.getErrors();
 
****************************************************************************/

function clsValidator() 
{

	/* Data members */
	this.msgError="";			// Return the msg error
	this.errorColor="";			//error color Format: #00708c
	this.error = false;			
	
	/* Methods */
	///////////////////////////////////////////////////////////
	function setEncabezado(head)	
	{
		this.head = head;
	}
	///////////////////////////////////////////////////////////

	function AgregarError() {
		this.error=true;
		this.msgError += "* "+arguments[0]+"\n";
		for (var i=1; i < arguments.length ; i++) 
		{
			document.getElementById(arguments[i]).style.backgroundColor=this.errorColor;
		}
	}
	///////////////////////////////////////////////////////////
	
	function EliminarError()
	{
		for (var i=0; i < arguments.length ; i++) 
		{
			document.getElementById(arguments[i]).style.backgroundColor="";
		}
	}
	///////////////////////////////////////////////////////////
	
	function setErrorColor(color)
	{
		this.errorColor = color;
	}

	///////////////////////////////////////////////////////////
	
	function Vacio(field,msg) 
	{
		this.EliminarError(field);
		if (document.getElementById(field).value.replace(/ /g, '') == "")
		{
			this.AgregarError(msg, field);
			return false
		}
		return true
	}
	///////////////////////////////////////////////////////////
	
	function Email(field,msg) 
	{
		this.EliminarError(field);
		var re  = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
		if (!re.test(document.getElementById(field).value)) {
			this.AgregarError(msg, field);
			return false
		}
		return true
	}
	///////////////////////////////////////////////////////////
	
	function Fecha(field, msg) 
	{
		this.EliminarError(field);
		var datePat = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})?$/;
		var matchArray = document.getElementById(field).value.match(datePat);
		var ok = true;

		if (matchArray == null) ok = false;
		else 
		{
			day = matchArray[1];
			month = matchArray[2];
			year = matchArray[3];

			if ((day < 1  || day > 31) || (month < 1 || month > 12) || (year < 1)) ok = false;
			if ((month ==2 || month == 4 || month == 6 || month ==9 || month ==11) && (day > 30)) ok = false;
			if (month == 2) 
			{
				bisiesto = (parseInt (year/4))*4
				if ((year != bisiesto) && (day > 28)) ok = false;
				if ((year == bisiesto) && (day > 29)) ok = false;
			}
		}
		if (ok) return true
		else
		{
			this.AgregarError(msg, field);
			return false;		
		}
	}
	///////////////////////////////////////////////////////////

	function Iguales(field1, field2, msg)
	{
		this.EliminarError(field1,field2);
		if(document.getElementById(field1).value != document.getElementById(field2).value)
		{
			this.AgregarError(msg, field1, field2);
			return false
		}
		return true	
	}
	///////////////////////////////////////////////////////////
	
	function Longitud(field, operator, length, msg)
	{

		this.EliminarError(field);
		if (operator == "=") operator = "==";
		if ( !(eval("document.getElementById(field).value.length "+operator+" length")) )
		{
			this.AgregarError(msg, field);
			return false
		}
		return true
	}
	///////////////////////////////////////////////////////////
	
	function Cantidad(field, operator, valor, msg)
	{

		this.EliminarError(field);
		if (operator == "=") operator = "==";
		if (eval("document.getElementById(field).value "+operator+" valor") )
		{
			this.AgregarError(msg, field);
			return false
		}
		return true
	}
	///////////////////////////////////////////////////////////
	function Validar() 
	{
		return !this.error;
	}
	///////////////////////////////////////////////////////////

	function getErrors() 
	{
			alert(this.head+"\n\n"+this.msgError);
	}
	///////////////////////////////////////////////////////////

	this.setEncabezado = setEncabezado;
	this.setErrorColor = setErrorColor;
	this.getErrors = getErrors;
	this.AgregarError = AgregarError;
	this.EliminarError = EliminarError;
	this.Vacio = Vacio;
	this.Email = Email;
	this.Fecha = Fecha;
	this.Iguales = Iguales;
	this.Longitud = Longitud;
	this.Validar = Validar;
	this.Cantidad = Cantidad;
	
}
//////////////////////////////////////////////////////////////////

