/***************************************************************************
*
*	clsValidator  - Version 1.1 BETA
*	Copyleft: Horacio R. Valdez
*	website: www.hvaldez.com.ar/javascript/clsValidator
*	Soporte: info@hvaldez.com.ar
*	Creado: 05.2004
* 	Modificado: 04.2006
*
**************************************************************************** 
* 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
****************************************************************************/

var Utilidades = {  Version: '1.1', Autor: 'Horacio R. Valdez' }
Utilidades.Validator = Class.create();
Utilidades.Validator.prototype =  {
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Contructor
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	initialize: function() 
	{ 
		this.msgError="";															
		this.errorColor="#FFC1C1";													
		this.head = "[- Se encontraron los siguientes errores en el formulario -]"; 
		this.formatoFecha = "EURO"													
		this.formatoHora = "12"														
		this.hayErrores = false;
		this.errorImg = "libs/clsValidator/images/error.gif";
		this.mode = "2";
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Propiedad que permite modificar el formato de la fecha.
	// Se expone como propiedad ya que si el formato no esválido utiliza el default.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	SetFormatoFecha: function(value) 
	{
		//TODO: poner la validacion
		this.formatoFecha = value;
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Propiedad que permite modificar el formato de la hora.
	// Se expone como propiedad ya que si el formato no esválido utiliza el default.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	SetFormatoHora: function (value)
	{
		//TODO: poner la validacion
		this.formatoHora = value;
	},
			
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Recibe como primer parámetro el mensaje de error y los parámetros subsiguientes son los
	// objetos que causan el error.
	// Pinta de color los objetos que causan errores.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	AgregarError: function AgregarError() 
	{
		this.hayErrores = true;
		this.msgError += "* "+arguments[0]+"\n";
		for (var i=1; i < arguments.length ; i++) 
		{
			$(arguments[i]).style.backgroundColor=this.errorColor;
			
			if(this.mode == "2")
			{
				this.ShowImage(arguments[i], arguments[0]);
			}
		}
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Recibe como parametros los objetos que debe despintar ya que no tienen errores.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	EliminarError: function ()
	{
		for (var i=0; i < arguments.length ; i++) 
		{
			$(arguments[i]).style.backgroundColor="";
			
			if(this.mode == "2")
			{
				this.RemoveImage(arguments[i]);
			}
		}
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Hace un alert con el error formateado
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	GetErrors: function () 
	{
		alert(this.head+"\n\n"+this.msgError);
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Indica si el campo es vacio o no. 
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	Vacio: function Vacio(field,msg) 
	{
		this.EliminarError(field);
		var retVal = true;
		
		if (document.getElementById(field).value.replace(/ /g, '') == "")
		{
			this.AgregarError(msg, field);
			retVal = false
		}
		return retVal;
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Indica si el e-mail ingresado es vālido. 
	// Devuelve TRUE si es vālido y FALSE si no lo es.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	Email: function (field,msg) 
	{
		this.EliminarError(field);
		var retVal = true;
		var email  = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
		if (!email.test(document.getElementById(field).value)) 
		{
			this.AgregarError(msg, field);
			retVal = false
		}
		return retVal;
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Dado el textbox1 y el textbox2, compara su contenido y devuelve TRUE si son iguales 
	// y FALSE si no lo son.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	Iguales: function (field1, field2, msg)
	{
		this.EliminarError(field1,field2);
		var retVal = true;
		if(document.getElementById(field1).value != document.getElementById(field2).value)
		{
			this.AgregarError(msg, field1, field2);
			retVal = false
		}
		return retVal;
	
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Dado un textboxcompara su contenido con la longitud y el operador indicado.  
	// Devuelve TRUE si machea la expresion y FALSE si no lo hace.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	Longitud: function (field, operator, length, msg)
	{
	
		this.EliminarError(field);
	
		var retVal = true;
		if (operator == "=") operator = "==";
		if ( !(eval("document.getElementById(field).value.length "+operator+" length")) )
		{
			
			this.AgregarError(msg, field);
			retVal = false
		}
		return retVal;
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Indica si el numero ingresado es un entero. 
	// Devuelve TRUE si lo es  y FALSE si no lo es.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	Entero: function (field, msg)
	{
		this.EliminarError(field);
		var retVal = true;
		if ( ! ( parseInt(document.getElementById(field).value) == document.getElementById(field).value ) )
		{
			this.AgregarError(msg, field);
			retVal = false
		}
		return retVal;
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Dado un textbox compara su contenido con el valor y el operador indicado.  
	// Devuelve TRUE si machea la expresion y FALSE si no lo hace.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	Valor: function (field, operator, valor, msg)
	{
		this.EliminarError(field);
		var retVal = true;
		if (operator == "=") operator = "==";
		if ( !(eval("document.getElementById(field).value "+operator+" valor")) )
		{
			this.AgregarError(msg, field);
			retVal = false;
		}
		return retVal;
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Setea la forma en que la clase funciona
	// Valores admitidos: 1 para hacer alert de los mensajes, 2 para usar imagenes
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	SetMode: function (mode)
	{
		//todo: validar consistencia
		this.mode =  mode;
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Setear la ruta a la img de error
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	SetErrorImg: function (path)
	{
		this.errorImg =  path;
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Pone la imagen de error y el mensaje junto al campo que fue validado
	// Nota: solo si esta actuando en modo img.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	ShowImage: function (name, msg)
	{
		//Creo la imagen
		var imgElement = document.createElement("img");
		imgElement.id = name+"_img";
		imgElement.src = this.errorImg;
		imgElement.border= "0";
		imgElement.style.cursor="hand";	
		imgElement.errText = msg;
		
		//Agrego los eventos
		imgElement.onmouseover=  function(e) {  domTT_activate(this, e||window.event, 'content', imgElement.errText, 'trail', true, 'fade', 'both', 'fadeMax', 87, 'styleClass', 'niceTitle') }
		imgElement.onmouseout= function(e) { domTT_mouseout(this, e||window.event); }
		//Inserto la imagen
		$(name).parentNode.appendChild(imgElement);
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Elimina la imagen de error y el mensaje junto al campo que fue validado
	// Nota: solo si esta actuando en modo img.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	RemoveImage: function (name)
	{
		var imgElement = $(name+"_img");
		if(imgElement != null) $(name).parentNode.removeChild(imgElement);
	},
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Indica si el una fecha ingresada es vālida y tiene el formato correcto. 
	// Devuelve TRUE si es vālida y FALSE si no lo es.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	Fecha: function (field, msg) 
	{
		
		this.EliminarError(field);
		var retVal = true;
		var datePat;
		var formatoCorrecto;
		
		switch(this.formatoFecha) {
			case 'ISO':
				datePat = /^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(\/|-|\.)(?:0?2\1(?:29))$)|(?:(?:1[6-9]|[2-9]\d)?\d{2})(\/|-|\.)(?:(?:(?:0?[13578]|1[02])\2(?:31))|(?:(?:0?[1,3-9]|1[0-2])\2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))\2(?:0?[1-9]|1\d|2[0-8]))$/;
				formatoCorrecto = "aaaa/mm/dd";
				break;
			case 'EURO': 
				datePat = "(((0[1-9]|[12][0-9]|3[01])([/])(0[13578]|10|12)([/])([1-2][0,9][0-9][0-9]))|(([0][1-9]|[12][0-9]|30)([/])(0[469]|11)([/])([1-2][0,9][0-9][0-9]))|((0[1-9]|1[0-9]|2[0-8])([/])(02)([/])([1-2][0,9][0-9][0-9]))|((29)(\.|-|\/)(02)([/])([02468][048]00))|((29)([/])(02)([/])([13579][26]00))|((29)([/])(02)([/])([0-9][0-9][0][48]))|((29)([/])(02)([/])([0-9][0-9][2468][048]))|((29)([/])(02)([/])([0-9][0-9][13579][26])))";
				formatoCorrecto = "dd/mm/aaaa";
				break;
			case 'ANSI':
				datePat = /^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$/;
				formatoCorrecto = "aaaa/mm/dd hh:mm:ss am/pm";
				break;
		}		
		
		var matchArray = document.getElementById(field).value.match(datePat);
		if (matchArray == null) 
		{
			msg += ' [formato: '+formatoCorrecto+']'
			this.AgregarError(msg, field);
			retVal = false;		
		}
		
		return retVal;
	},


	////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Indica si el una hora ingresada es vālida y tiene el formato correcto. 
	// Devuelve TRUE si es vālida y FALSE si no lo es.
	////////////////////////////////////////////////////////////////////////////////////////////////////////
	Hora: function (field, msg)
	{
		this.EliminarError(field);
		var retVal = true;
		var datePat;
	
		switch(this.formatoHora) 
		{
			case '24':
				datePat = /^([0-1][0-9]|2[0-3]):[0-5][0-9]$/;
				formatoCorrecto = "hh:mm";
				break;
				
			case '12':
				datePat = /^(1|01|2|02|3|03|4|04|5|05|6|06|7|07|8|08|9|09|10|11|12{1,2}):(([0-5]{1}[0-9]{1}\s{0,1})([AM|PM|am|pm]{2,2}))\W{0}$/;
				formatoCorrecto = "hh:mm am/pm";
				break;
		}
		var matchArray = document.getElementById(field).value.match(datePat);
		
		if (matchArray == null) 
		{
			msg += ' [formato: '+formatoCorrecto+']'
			this.AgregarError(msg, field);
			retVal = false;		
		}
		
		return retVal;
	}
};
