/*
*-------------------------------
* ValidaForm
* version 1.01 (23/02/2010)
* Autor: Hernán Javier Hegykozi
* Contacto: hernanjh@gmail.com
*-------------------------------
*/
(function() {
		  
		this.ValidationForm = function() {
			this.ValidationForm = ValidationForm.copyProperties (ValidationForm, ValidationForm.Methods);
			return ValidationForm;
			
		};
}
).call(window);


ValidationForm.Methods = {

	/*Options*/
	idForm: null,
	objForm: null,
	charSplit: ';',
	cssClass: 'InputImage',
	backgroundColor: "#F4DFDF",
	mensaje: 'Por favor, verifique los siguientes errores:\t\n\t\n',
	valido: true,
	
	setOptions: function(options) {
		ValidationForm.copyProperties(this, options);
	},
	
	init: function (param)
	{
		this.setOptions(param);
		this.objForm = document.getElementById(this.idForm);
		
		this.ObjectList = [];
		
		for (var i=0; i < this.objForm.elements.length; i++)
		{		 	
			var vElem = this.objForm.elements[i];
			var vLang = vElem.lang.split(this.charSplit);

			this.objForm.elements[i].style.backgroundColor="";
			this.objForm.elements[i].className = this.Replace(this.objForm.elements[i].className, " "+this.cssClass, "");

			if (vLang != '' && this.isVisible(vElem))
				this.ObjectList.push({elem: vElem, lang: vLang});
		}
		
		return this.validate();
		
	},
	
	validate: function ()
	{
		if (this.ObjectList.length == 0)
			return true;
		
		for (var i = 0; i < this.ObjectList.length; i++)
		{
			if (this.ObjectList[i].elem.value != '' && this.ObjectList[i].lang.length > 1)
			{
				
				if (!this.validatetype(this.ObjectList[i]))
				{
					this.mensaje +=  "- Ingreso erroneo del campo: " + this.ObjectList[i].elem.title + "\t\n";
					if(this.valido)
					{
						this.ObjectList[i].elem.focus();
						this.valido = false; 
					}
					this.ObjectList[i].elem.style.backgroundColor = this.backgroundColor;
					this.ObjectList[i].elem.className = this.ObjectList[i].elem.className + " " + this.cssClass;
				}
				
			}
			else
			{	/*Si esta vacio me fijo que no sea obligatorio*/
				if (this.ObjectList[i].lang[0] == 'true' && (this.ObjectList[i].elem.value == '' || this.ObjectList[i].elem.value == '0'))
				{
					this.mensaje +=  "- Ingrese el campo: " + this.ObjectList[i].elem.title + "\t\n";
					if(this.valido)
					{
						this.ObjectList[i].elem.focus();
						this.valido = false; 
				  }
					this.ObjectList[i].elem.style.backgroundColor = this.backgroundColor;
					this.ObjectList[i].elem.className = this.ObjectList[i].elem.className + " " + this.cssClass;
				}
			}
		}
		
		if (!this.valido)
			alert(this.mensaje);
		return this.valido;

	},
	validatetype: function (obj)
	{
		if (obj.lang[1] == 'email') 
			return isEmail(obj.elem.value);
		
		if (obj.lang[1] == 'url') 
			return isUrl(obj.elem.value);
		
		if (obj.lang[1] == 'numeric') 
			return isNumeric(obj.elem.value);
		
		if (obj.lang[1] == 'entero') 
			return isEntero(obj.elem.value);
		
		if (obj.lang[1] == 'alfa') 
			return IsAlphanumeric(obj.elem.value);
		
		if (obj.lang[1] == 'date') 
			return isDate(obj.elem.value);
		
		if (obj.lang[1] == 'money') 
			return isMoney(obj.elem.value);
		
		if (obj.lang[1] == 'cuitcuil') 
			return isCUITCUIL(obj.elem.value);
		
		if (obj.lang[1] == 'free') 
			if (eval(obj.lang[2])) return true; else return false;			
		
	},
	
	/*-----------Functions Utils-------------*/
	isVisible : function  (elem)
	{
		var Visible = true;
		ElemPar = elem.parentNode;

		while (ElemPar) 
		{
			if ((ElemPar.tagName == "BODY") || (ElemPar.tagName == "HTML")) {
				break;
			}
			if ((ElemPar.style.display == "none") || (ElemPar.style.visibility == "hidden")) {
				Visible = false;
				break;
			}
			ElemPar = ElemPar.parentNode;
		}

		return Visible;
	},
	Replace: function (texto, bus, rem)
	{
		do { texto = texto.replace(bus,rem);} while(texto.indexOf(bus) >= 0);
		return texto;
	}
	
}


/*-- Utils --------------------------------------------*/
ValidationForm.copyProperties = function(dest, src) {
  for (var property in src) {
    dest[property] = src[property];
  }
  return dest;
};


function validarForm (idform)
{
	var nobj = new ValidationForm();
	return nobj.init({idForm: idform, charSplit:','});
}



//--------------------------------------------------
function isNumeric(Expression)
{
	var numberPat= /^[-+]?[0-9]+[.]?[0-9]*([eE][-+]?[0-9]+)?$/;
	var matchArray = Expression.match(numberPat); // is the format ok?
	
	if (matchArray == null) 
		return false;
	else
		return true;
}
function isEntero(Expression)
{
	var enteroPat= /^[0-9]+$/;
	var matchArray = Expression.match(enteroPat); // is the format ok?
	
	if (matchArray == null) 
		return false;
	else
		return true;
}
function IsAlphanumeric(Expression)
{
	Expression = Expression.toLowerCase();
	RefString = "abcdefghijklmnopqrstuvwxyz0123456789áéíóúñ ";

	if (Expression.length < 1) 
		return (false);

	for (var i = 0; i < Expression.length; i++) 
	{
		var ch = Expression.substr(i, 1)
		var a = RefString.indexOf(ch, 0)
		if (a == -1)
			return (false);
	}
	return(true);
}


function isEmail(emailStr) 
{
    var emailPat = /[\w-\.]{3,}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}/;

	var matchArray = emailStr.match(emailPat); // is the format ok?
	
	if (matchArray == null) 
		return false;
	else
		return true;
}

function isUrl(urlStr) 
{
    var urlPat = /^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)( [a-zA-Z0-9\-\.\?\,\/\\\+&%\$#_]*)?$/;
    //var urlPat = /^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)( [a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$/;
	//alert(urlStr);
	var matchArray = urlStr.match(urlPat); // is the format ok?
	
	if (matchArray == null) 
		return false;
	else
		return true;
}

//---VALIDA LA FECHA
function isDate(dateStr) {

	var datePat = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		return false;
	}
	month = matchArray[3]; // p@rse date into variables
	day = matchArray[1];
	year = matchArray[5];
	
	if (month < 1 || month > 12) { // check month range
		return false;
	}
	if (day < 1 || day > 31) {
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
			return false;
		}
	}
	return true; // date is valid
}


//Valida que sea Numerico y que tenga como mucho 2 decimales
function isMoney (moneyStr) 
{
	if (isNumeric(moneyStr))
	{
		var moneyPat = /^\d+(\.\d{1,2})?$/;
		var matchArray = moneyStr.match(moneyPat); // is the format ok?
		if (matchArray == null) 
			return false;
		else
			return true;
	}
	else
	{
		return false;	
	}
}


//Valida el Campo de CUIT / CUIL y el digito verificador
function isCUITCUIL(varCUIT)
{
	if ((varCUIT.length=11)&&(!isNaN(varCUIT)))
	{
		var StrCuit=varCUIT;
		var a = 0;
		var x=1 ;
		var n=0;
		var m=0;
		var blnResultado=false;
		for(x = 0; x < 11; x++) 
		{    
			n = parseInt(StrCuit.substr(x,1));
			n = n + 48;
			switch(x+1)
				{
					case 1:
						m = 5;
						break;
					case 2:
						m = 4;
						break;
					case 3:
						m = 3;
						break;
					case 4:
						m = 2;
						break;
					case 5:
						m = 7;
						break;
					case 6:
						m = 6;
						break;
					case 7:
						m = 5;
						break;
					case 8:
						m = 4;
						break;
					case 9:
						m = 3;
						break;
					case 10:
						m = 2;
						break;
					case 11:
						m = 1;
						break;
				}					
			a = a + n * m;
		}
		a = a % 11;
		if (a == 3)
		{
		    blnResultado = true;
		}    
		else
		{
		    blnResultado = false;
		}
	}
	else
	{
		blnResultado = false;
	}
return blnResultado;
}




//----Saca Espacion en blanco--
 function Trim(sText)
{
   
  return LTrim(RTrim(sText));
}

function LTrim(sText)
{
  var iLen = sText.length;
  var iPos = 0;
  for (var iIndex = 0; iIndex < iLen; iIndex++)
    if (sText.charAt(iIndex) == " ")
      iPos = iIndex + 1;
    else
      break;
  return sText.substring(iPos, iLen);
}

function RTrim(sText)
{
  var iEnd = sText.length;
  var iPos = iEnd;
  for (var iIndex = iEnd - 1; iIndex >= 0; iIndex--)
    if (sText.charAt(iIndex) == " ")
      iPos = iIndex;
    else
      break;
  return sText.substring(0, iPos);
}
