var oForm = new Array();
function ValidaFormulario(f,indice){
	var self = this;
	self.oAuto = new Array();
	self.capa = null;
	// variable del formulario
	self.f = f;
	// indice del formulario
	self.indice = indice;
	// nombre del estilo cuando el campo este normal
	self.noStyle = "";
	// nombre del estilo cuando el campo este enfocado --NO IMPLEMENTADO AUN
	self.focusElementStyle = "bordeazul";
	// nombre del estilo cuando cuando el elemento haga blur --NO IMPLEMENTADO AUN
	self.BlurElementStyle = "bordeazul";
	//** PARA EL MANEJO DE ERRORES **//
	self.focusElement = null;
    // nombre del atributo que se va a utilizar para el manejo de errores
	self.vattribute = "vtipo";
	// nombre del estilo del campo cuando se detecte un error
	self.ErrorStyle = "borderojo";
	// velocidad del parpadeo
	self.timeouterror = 500;
	// objeto que se va a utilizar para los campos en el evento onkeyup, ej. cuando solo sean numeros
	self.DoCaseChange = new Array();
	// campo en el que se detecto el error
	self.errorField = null;
	// esta variable en true muestra un tooltip cuando se detecta el error, caso contrario en un alert, en la funcion self.Alert()
	self.showerrortool = false;
	// secuencia de parpadeo deseado, para crear una nueva utilizar la funcion self.BlinkErrorSeq()
	self.errorSeq = [self.ErrorStyle,self.noStyle,self.ErrorStyle,self.noStyle,self.ErrorStyle,self.noStyle];
	// posicion de parpadeo en el array errorSeq
	self.errorIndex = 0;
	// capa de tooltip
	self.tooldiv = null;
	// capa del puntero del tooltip
	self.tooldivpointer = null;
	// checkbox a validar
	self._ckgroup = new Array();
	//intervalo en blink
	self.intervalo = null;
	//funcion para crear una nueva secuencia de parapadeo
	self.BlinkErrorSeq = function(estyle,nostyle,n){
		self.errorSeq = new Array();
		for(i=0;i<n;i++){
			if(i > 0 && (i%2)==0 ){
				self.errorSeq[i] = nostyle;
			}else{
				self.errorSeq[i] = estyle;
			}
			
		}
	}
	self.getRadioButtonSelectedValue = function(ctrl)
	{
	    for(i=0;i<ctrl.length;i++)
	        if(ctrl[i].checked) return ctrl[i].value;
	}

	//funcion para cuando se detecte un error en la validacion despliegue un alert o tooltio
	//dependiendo de la variable self.showerrortool = true;
	self.Alert = function(texto,obj){
		if(obj != null && obj != undefined && self.showerrortool){
			try{
				self.Show(obj,texto);
			}catch(ex){
				alert(texto);
			}
		}else{
			alert(texto);
		}
	}
	self.noescauto = function(){
		return !(window.event && window.event.keyCode == 27);
	}
	self.DisplayLayerHelp = function(autoIndice){
		var dp = this;
		dp.indice = autoIndice;
		dp.capacss = "autocompletecss";
		dp.datos = new Array();
		dp.actual = -1;
		dp.anterior = -1;
		dp.nresultados = 0;
		dp.cfield = null;
		dp.addOption = function(nombre,valor){
			dataIndex = dp.datos.length;
			dp.datos[dataIndex] = new Array();
			dp.datos[dataIndex]["nombre"] = nombre; 
			dp.datos[dataIndex]["valor"] = valor; 
		}
		dp.getTablaSize=function(){
			tabla = self.capa.getElementsByTagName("TABLE")[0];
			htabla = tabla.offsetHeight;
			return htabla;
		}
		dp.ListOptions = function(campo){
			cantidad = dp.datos.length;
			valor = campo.value;
			htm = "<table border=0 style='width:100%'>";
			dp.nresultados = 0;
			for(var i=0;i<cantidad;i++){
				cnombre = dp.datos[i]["nombre"];
				cvalue = dp.datos[i]["valor"];
				if(cnombre.toUpperCase().indexOf(valor.toUpperCase()) > -1){
					idn = "autoc_"+self.indice+"_"+dp.indice+"_"+dp.nresultados;
					textoID = "spntext_"+self.indice+"_"+dp.indice+"_"+dp.nresultados;
					onck = "onclick=\"oForm["+self.indice+"].oAuto["+dp.indice+"].DoAction(this,'"+idn+"');\"";
					htm += "<tr id='"+idn+"' class='fondo1' "+onck+" ><td ><span id='"+textoID+"'>"+cnombre+"</span></td></tr>";
					dp.nresultados++;
				}
			}
			htm += "</table>";
			return htm;
		}
		dp.DoAction = function(celda,trID){
			_separa = trID.split("_");
			ypos = _separa[_separa.length-1];
			celda = document.getElementById(trID);
			textoID = "spntext_"+self.indice+"_"+dp.indice+"_"+ypos;
			
			spn = document.getElementById(textoID);
			dp.cfield.value = spn.innerHTML;
			
		}
		dp.HideAll = function(){
			self.capa.style.display = "none";
			dp.actual = -1;
			dp.anterior = -1;
		}
		dp.Begin = function(campo){
			dp.cfield = campo;
			if(self.capa == null){
				self.capa = document.createElement("DIV");
				self.capa.id  = "cpacmpjake_" + dp.indice;
				self.capa.className = dp.capacss;
				document.body.appendChild(self.capa);
			}
			self.capa.style.display = "none";
			campo.setAttribute("AUTOCOMPLETE","OFF");
			campo.autocomplete = "off";
			self.AgregarEventos(campo,"keydown",function(evt){
				return self.noescauto();
			});
			self.AgregarEventos(campo,"blur",function(evt){
				//self.capa.style.display = "none";
				return false;
			});
			self.AgregarEventos(campo,"focus",function(evt){
				dp.HideAll();
				return false;
			});
			self.AgregarEventos(campo,"keypress",function(evt){
				evt = (evt) ? evt : window.event;
				tecla = evt.keyCode;
				switch(tecla){
					case 13:
						if(dp.actual > -1 && self.capa.style.display=="block"){
							textoID = "spntext_"+self.indice+"_"+dp.indice+"_"+dp.actual;
							spn = document.getElementById(textoID);
							self.capa.style.display = "none";
							campo.value = spn.innerHTML;
							return false;
						}
						break; 
				}
			});
			self.AgregarEventos(campo,"keyup",function(evt){
				evt = (evt) ? evt : window.event;
				tecla = evt.keyCode;
				window.status = "La tecla: " + tecla;
				if(tecla == 13)return false;
				if(self.capa.style.display == "none"){
					self.capa.style.display = "block";
					self.capa.style.width = (campo.offsetWidth*2) + 'px';
					self.capa.style.height = "100px";
					
					self.capa.style.top = (self.getTopPos(campo)+ campo.offsetHeight) + 'px';
					self.capa.style.left = (self.getLeftPos(campo)) + 'px';
					self.capa.scrollTop = 0;
					dp.actual = -1;
					dp.anterior = -1;
				}
				switch(tecla){
					case 27:
						self.capa.style.display = "none";
						return false;
						break;
					case 40:
						
						if(dp.actual < (dp.nresultados-1)){
							dp.actual++;
							htabla = dp.getTablaSize();
							idn = "autoc_"+self.indice+"_"+dp.indice+"_"+dp.actual;
							celda = document.getElementById(idn);
							self.capa.scrollTop = self.getTopPosElement(celda,"DIV");
							celda.className="fondo2";
							if(dp.anterior > -1){
								idn = "autoc_"+self.indice+"_"+dp.indice+"_"+dp.anterior;
								celdanterior = document.getElementById(idn);
								celdanterior.className="fondo1";
							}
							dp.anterior = dp.actual;
						}
						break;
					case 38:
						if(dp.actual > 0){
							dp.actual--;
							idn = "autoc_"+self.indice+"_"+dp.indice+"_"+dp.actual;
							celda = document.getElementById(idn);
							celda.className="fondo2";
							self.capa.scrollTop = self.getTopPosElement(celda,"DIV");
							if(dp.anterior > -1){
								idn = "autoc_"+self.indice+"_"+dp.indice+"_"+dp.anterior;
								document.getElementById(idn).className="fondo1";
							}
							dp.anterior = dp.actual;
						}
						break;
					default:
						dp.actual = -1;
						dp.anterior = -1;
						self.capa.innerHTML = dp.ListOptions(campo);
						break;
					
				}
				window.status = "La tecla: " + tecla;
				if(self.capa.style.display == "none"){
					self.capa.style.display = "block";
					self.capa.style.width = (campo.offsetWidth*2) + 'px';
					self.capa.style.height = "100px";
					
					self.capa.style.top = (self.getTopPos(campo)+ campo.offsetHeight) + 'px';
					self.capa.style.left = (self.getLeftPos(campo)) + 'px';

				}
			});
			self.AgregarEventos(document.documentElement,"click",function(event){
					event = (event) ? event : window.event;
					if(!oUtils.firefox){
						obj = event.srcElement
					}else{
						obj = event.target;
					}
					dp.HideAll();
					
			});
						  
		}
		
	}
	self.AgregarEventos =  function(obj,eventType,functionName,suffix)
	{ 
	  if(!suffix)suffix = '';
	  if(obj.attachEvent){ 
	    obj['e'+eventType+functionName+suffix] = functionName; 
	    obj[eventType+functionName+suffix] = function(){obj['e'+eventType+functionName+suffix]( window.event );} 
	    obj.attachEvent( 'on'+eventType, obj[eventType+functionName+suffix] ); 
	  } else 
	    obj.addEventListener(eventType,functionName,false); 	    
	}
	//Obtiene la posicion en Y de un objeto
	self.getTopPosElement = function(inputObj,objName)
	{		
		var returnValue = inputObj.offsetTop;
		while((inputObj = inputObj.offsetParent) != null){
			if(inputObj.tagName!='HTML'){
				if(inputObj.tagName==objName)break;
				returnValue += inputObj.offsetTop;
				
			}
		}
		return returnValue;
	}
	
	self.getTopPos = function(inputObj)
	{		
		var returnValue = inputObj.offsetTop;
		while((inputObj = inputObj.offsetParent) != null){
			if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
		}
		return returnValue;
	}
	//Obtiene la posicion en X de un objeto
	self.getLeftPos = function(inputObj)
	{
		var returnValue = inputObj.offsetLeft;
		while((inputObj = inputObj.offsetParent) != null){
			if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
		}
		return returnValue;
	}
	//Muestra un tooltip en el campo deseado
	self.Show = function(campo,texto){
		if(self.tooldiv == null){
				self.tooldiv =  document.createElement("DIV");
				self.tooldiv.id = "jaketolldiv";
				self.tooldiv.style.display = "none";
				self.tooldiv.className = "csstool";
				self.tooldivpointer =  document.createElement("DIV");
				self.tooldivpointer.innerHTML = "<img src='Admin/img/arrow2.gif' />";
				self.tooldivpointer.className = "csscursortool";
				document.body.appendChild(self.tooldiv);
				document.body.appendChild(self.tooldivpointer);
			}
			self.tooldiv.style.display = "block";
			self.tooldivpointer.style.display = "block";
			self.tooldiv.innerHTML =texto;
			ancho = campo.offsetWidth;
			alto = campo.offsetHeight;
			posx = (self.getLeftPos(campo) + ancho);
			posy = self.getTopPos(campo) + (alto/2);
			self.tooldivpointer.style.top = posy  + 'px';
			self.tooldivpointer.style.left = posx + 'px';
			msg_y = (posy + self.tooldivpointer.offsetHeight) - 1;
			self.tooldiv.style.left =  posx + 'px';
			self.tooldiv.style.top =  msg_y + 'px';
			campo.onblur = function(){
				self.tooldiv.style.display = "none";
				self.tooldivpointer.style.display = "none";
			}
	}
	/*Para los campos donde solo permite escribir cierto tipo de caracteres, ej 
		upper: Sólo mayúsculas
		lower: Sólo minúsculas
		alfanumUpper: solo caracteres alfanum. en mayúsculas
		
	*/
	self.CaseField = function(campo,tipo){
		var fn = this;
		fn.campo = campo;
		fn.tipo = tipo;
		fn.displayTooltip = false;
		fn.novalidkeys = "35,36,37,38,39,40,8";
		fn.tooldiv = null;
		fn.tooldivpointer = null;
		fn.toolText = "Mensaje de Sistema";
		fn.addAction = function(){};
		fn.Show = function(){
			self.Show(fn.campo,fn.toolText);
		}
		fn.Begin = function(){
			fn.campo.onkeyup = function(evt){
				evt = (evt) ? evt : window.event;
				tecla = evt.keyCode;
				window.status = self.ErrorStyle;
				if(fn.displayTooltip){
					fn.Show();
				}
				if(fn.novalidkeys.indexOf(evt.keyCode) == -1){
					if(tipo == "upper"){
						if(fn.campo.value.match(/[a-z]/g))
							fn.campo.value = fn.campo.value.toUpperCase();
					}if(tipo == "lower"){
						if(fn.campo.value.match(/[A-Z]/g))
							fn.campo.value = fn.campo.value.toLowerCase();
					}if(tipo == "number")
						if(fn.campo.value.match(/[^\d]/g))
							fn.campo.value = fn.campo.value.replace(/[^\d]/gi,"");
					if(tipo == "moneda")
						fn.campo.value = fn.campo.value.replace(/[^\d|^,|^.]/gi,"");
					if(tipo == "nombre"){
						texto = fn.campo.value.replace(/[^\s|^a-zA-Z]/gi,"");	
						texto = texto.replace(/^\s+/g, "");
						texto = texto.replace(/\s{2,}/gi," ");
						fn.campo.value = texto;
					}
					if(tipo == "alfanum"){
						if(fn.campo.value.match(/[^\w]/g))
							fn.campo.value = fn.campo.value.replace(/[^\w]/gi,"");
						
					}
					if(tipo == "alfanumUpper"){
						if(fn.campo.value.match(/[^\w]/g))
							fn.campo.value = fn.campo.value.replace(/[^\w]/gi,"");
						if(fn.campo.value.match(/[a-z]/g))
							fn.campo.value = fn.campo.value.toUpperCase();
						
					}
					if(tipo == "alfanumLower"){
						if(fn.campo.value.match(/[^\w]/g))
							fn.campo.value = fn.campo.value.replace(/[^\w]/gi,"");
						if(fn.campo.value.match(/[A-Z]/g))
							fn.campo.value = fn.campo.value.toLowerCase();
						
					}
					fn.addAction();	
				}
			}	
			
		}
		
	}
	self.getForm = function(){
		return self.f; 
	}
	self.BlankTextFields = function(){
		for(var i =0; i < self.f.elements.length; i++){
			campo = self.f.elements[i];
			if(campo.getAttribute("type").toLowerCase() == "text"){
				campo.value = "";
			}
		}
		self.f.elements[0].focus();
	}
	self.CleanStyles = function(){
		for(var i =0; i < self.f.elements.length; i++){
			campo = self.f.elements[i];
			campo.className = self.noStyle;
		}
	}
	// Funcion que realiza el parpadeo del error
	self.DisableErrorStyle = function(){
		if(self.errorIndex < self.errorSeq.length){
			clsName = self.errorSeq[self.errorIndex];
			self.errorField.className = clsName;
			self.errorIndex++;
			self.intervalo = setTimeout("oForm["+self.indice+"].DisableErrorStyle()",self.timeouterror);
		}else{
			self.errorField = null;
			self.errorIndex = 0;
		}
		return;
	}
	// Funcion que llama a self.DisableErrorStyle para iniciar el parpadeo
	self.SetErrorStyle = function(campo){
		campo.className = self.ErrorStyle;
		self.errorField = campo;	
		self.errorIndex = 0;
		self.DisableErrorStyle();
	}
	// Ejecuta la validacion del los campos que tengan el atributo de nombre self.vattribute
	self.isValidationOk = function(){};
	self.Execute = function(){
		if(self.intervalo != null){
			clearInterval(self.intervalo);
			self.errorIndex = 0;
		}
		_checkbox = new Array();
		_radio = new Array();
		_rdlastname = "";
		_cklastname = "";
		self.CleanStyles();
		for(var i =0; i < self.f.elements.length; i++){
			
			campo = self.f.elements[i];
			//campo.className = self.noStyle;
			attr = self.getFieldAttribute(campo);
			isvalid = true;
			if(!campo.type)continue;
			
			if(campo.type.toLowerCase() == "radio" || campo.type.toLowerCase() == "checkbox"){
				if(_rdlastname != campo.name && attr){
				    if(attr.toLowerCase().indexOf("selected")==0){
					    _radio[_radio.length] = campo.name;
					}
			    }
				_rdlastname = campo.name;
			}
			if(attr == null)continue;
			switch(attr){
				case "email":
					is_valid = self.ValidateEMail(campo.value);
					if(!is_valid){
						self.Alert("Correo electrónico no valido",campo);
						campo.select();
						campo.focus();
						self.SetErrorStyle(campo);
						return false;
					}
				break;
				case "rfc":
					is_valid = self.ValidateRFC(campo.value);
					if(!is_valid){
						self.Alert("RFC no valido",campo);
						try{
							campo.select();
							campo.focus();
							self.SetErrorStyle(campo);
						}catch(ex){}
						return false;
					}
				break;
				default:
					if(attr.indexOf("list") == 0){
						var nums = 1;
						opciones = campo.options.length;
						if(attr.indexOf("list_") > -1){
							separa = attr.split("_");
							nums = Number(separa[1]);
							if(nums < 1)nums = 1;
						}
						if(nums > opciones)nums = opciones;
						csel = 0;
						for(var op=0;op<opciones;op++){
							if(campo.options[op].selected == true)csel++;
							if(csel == opciones)break;
							
						}
						if(csel < nums){
							self.Alert("Favor de seleccionar " + nums + " elementos de la lista",campo);
							campo.focus();
							self.SetErrorStyle(campo);
							return false;
						}
					}
					else if(attr.indexOf("text") == 0){
						var nums = 1;
						if(attr.indexOf("text_") > -1){
							separa = attr.split("_");
							nums = Number(separa[1]);
							if(nums < 1)nums = 1;
						}
						if(campo.value.length < nums){
							self.Alert("Este campo debe tener al menos "+nums+" caracteres",campo);
							campo.focus();
							self.SetErrorStyle(campo);
							return false;
						}
						
					}
					else if(attr.indexOf("numero") == 0){
						var nums = 1;
						if(attr.indexOf("numero_") > -1){
							separa = attr.split("_");
							nums = Number(separa[1]);
							if(nums < 1)nums = 1;
						}
						if(campo.value.length < nums){
							self.Alert("Este campo debe tener al menos "+nums+" numeros",campo);
							campo.focus();
							self.SetErrorStyle(campo);
							return false;
						}else if(!self.ValidateNumber(campo.value)){
						    self.Alert("Este campo solo acepta numeros",campo);
							campo.focus();
							self.SetErrorStyle(campo);
							return false;
						}
						
					}
				break;
			}
			

		}
		for(var rd=0;rd < _radio.length; rd++){
		    var rdgp = self.f[_radio[rd]];
		    var vr = "";
		    var scount = 0;
		    for(var n=0;n<rdgp.length;n++){
		        var rdItem = rdgp[n];
		        if(rdItem.checked){
		            scount++;
		        }
		        if(vr=="" && rdItem.getAttribute("vtipo")!=""){
		            vr = rdItem.getAttribute("vtipo"); 
		        }
		    }
		    if(vr != ""){
		        if(vr.indexOf("selected") == 0){
						var nums = 1;
						if(vr.indexOf("selected_") > -1){
							separa = vr.split("_");
							nums = Number(separa[1]);
							if(nums < 1)nums = 1;
						}
						if(scount < nums){
							self.Alert("Este elemento debe tener al menos "+nums+" elementos seleccionados",rdgp[0]);
							return false;
						}
			    }
		    }
		}
		self.isValidationOk();
	}
	self.in_array = function(arreglo,palabra){
		if(arreglo == null || arreglo == undefined || arreglo.length < 1)return false;
		for(var ia = 0; ia<arreglo.length; ia++){
			if(palabra.toLowerCase().indexOf(arreglo[ia].toLowerCase()) > -1){
					return true;
			}
		}
			return false;
	}
	self.ValidateEMail = function(texto){
		regExpr = texto.match(/^[\w._-]{2,}@[\w._-]{2,}\.[\w_-]{2,4}$/);
		if(!regExpr){
			return false;		   
		}
		return true;
	}
	self.ValidateNumber = function(texto){
	    regExpr = texto.match(/^[0-9]{2,}$/);
		if(!regExpr){
			return false;		   
		}
		return true;
	}
	self.ValidateRFC = function(texto){
		rfc = texto;
		if(rfc.length == 10){
			if(!rfc.match(/^[a-zA-Z]{4}[\d]{6}$/)){
				return false;
			}else return true;
		}
		else if(rfc.length == 13){
			if(!rfc.match(/^[A-Z]{4}[\d]{6}[A-Z0-9]{3}$/)){
				return false;
			}else return true;
		}
		else{
			return false;
		}	
	}
	self.getFieldAttribute = function(formField){
		attr = null;
		try{
			attr = formField.getAttribute(self.vattribute);
		}catch(ex){}
		return attr;
	}
	self.CleanEndBeginSpace = function(campo){
		texto = campo.value;
		texto = texto.replace(/^\s+/g, "");
		texto = texto.replace(/\s+$/g, "");
		texto = texto.replace(/\s{2,}/gi," ");
		
	}
	self.CleanField = function(campo){
		texto = campo.value;
		texto = texto.replace(/^\s+/g, "");
		texto = texto.replace(/\s+$/g, "");
		texto = texto.replace(/<\/?[^>]*>/gi,"");
		texto = texto.replace(/\s{2,}/gi," ");
		return texto;
	}
}
