var _arrayForm  = "";
var _obrig		= "";
var _tipo		= "";
var _typeElem	= "";
var _contCampo	= "";
var _largCont	= "";
var _tamMax		= "";
var _tamRestante= "";
var _mostraTam	= "";
var _formName	= "";
var _id			= "";
var _ql 		= "\n";
var _tb 		= " ";
var _itemerro 	= "- ";
var _erroTit 	= "Verifique o(s) seguinte(s) erros:" + _ql+_ql;
var _erro	 	= "";
var _somStr		=  /[-.\/\\+0-9()#=_\$%*,¨!@~`&´\?\:\>\<|"'\]\{\}]/g;
var _somEmail	=  /[\/\\ +()#=\$%*,¨!~`&´\?\:\>\<|"'\]\{\}]/g;
var _somNum		=  /[-.\/\\+a-z A-Z*()#=_\$%¨!@~`&´\?\:\>\<|"'çéáíóúãõ,üàèìòùÏÜÖö^\]\{\}]/g;
var _somNumerico=  /[\/\\a-z A-Z*()#=_\$%¨!@~`&´\?\:\>\<|"'çéáíóúãõ,üàèìòùÏÜÖö^\]\{\}]/g;
var _somAlphNum	=  /[-.\/\\+*()#=_\$%¨!@~`&´\?\:\>\<|"'^\]\{\}]/g;
var _menosHtml	=  /[\<\>]/g;
function fVerificaErro()
{
	if(_erro!="")
	{
		alert(_erroTit + _erro);
		_erro = "";
		return false;
	}else
		return true;
}
function fErro(erro)
{
	_erro += _tb + _itemerro + erro + ";" +_ql ;
}
function fSetValue(valor)
{
  if(valor!='undefined')
  	_elem.value = valor;
}
function fVerificaTamMax()
{
	if(_tamMax != 0)
	{
		if(_largCont > _tamMax)
		{
			fSetValue(_contCampo.substr(0,_tamMax));
			return false;
		}
	}
	return true;
}

function fOnSubmit(objeto,nome)
{
        _arrayForm	= objeto;
		total		= _arrayForm.length;
		// Aplica a cada campo
		for (i=0;i<total;i++)
		{		
			_id				= _arrayForm[i][0];
			_tipo      		= _arrayForm[i][1];
			_obrig 	   		= _arrayForm[i][2];
			_contCampo		= document.getElementById(_id).value;
			_tamMax			= _arrayForm[i][3];
			_mostraTam		= _arrayForm[i][4];
			_typeElem		= document.getElementById(_id).type;
			_formName		= _arrayForm[i][5];
			// Se o campo for obrigatório
			if(_obrig && _formName == nome)
			{
				// Se for diferente de radiobutton e checkbox
				if(_typeElem!="radio" && _typeElem!="checkbox")
				{
					// Se o campo estiver vazio só avisa que não pode estar vazio
					if(_contCampo=="")
					{			
						// Se for do tipo select;
						if(_typeElem!="select-one")
							fErro("O campo "+_id.toUpperCase()+" deve ser preenchido.");
						// Se não for do tipo select;
						else if(_typeElem=="select-one")				
							fErro("Selecione uma opção no campo "+_id.toUpperCase()+".");
					}
					// Se o campo não estiver vazio valido o tipo de dado que deve ter
					else
					{	// Primeiro verifica o tamanho máximo
						if(fVerificaTamMax())
						{
							switch (_tipo)
							{
								case 1:  // Somente String;
									fVerificaString(_contCampo);
									break;
								case 2:  // Somente Alpha numérico;
									_contCampo  = _contCampo.replace(_somAlphNum,'');
									fSetValue(_contCampo);
									break;
								case 3:  // Qualquer caracter menos html;
									if(_contCampo.length<2)
									{
										fErro("O campo "+_id.toUpperCase()+" deve ter mais caracteres");
									}
									break;
								case 4:  // Qualquer caracter inclusive html;
									break;
								case 5:  // Somente número;
									break;
								case 6:  // email;
									fVerificaEmail(_contCampo);
									break;
								case 7:  // cnpj;
									if(!isCPFCNPJ(_contCampo,2))
									{
										fErro("O campo "+_id.toUpperCase()+" não é válido");
									}
									break;
								case 8:  // telefone;
									if(_contCampo.length<(_tamMax-1))
									{
										fErro("O campo "+_id.toUpperCase()+" está incompleto");
									}
									break;
								case 9:  // cep;
									break;
								case 10:  // cpf;
									break;
								default:
									alert("Tipo "+_tipo+" ainda não definido");
									break;
							}
						}
					 }
				}
			}
		}
		// se existir erro
		return fVerificaErro();
}
function fMostraTamMax(objeto)
{
    _arrayForm		= objeto;
	_typeElem		= _elem.type;
	if (fLocalizarNoArray(_arrayForm,_elem.id))
	{		
		_mostraTam		= objeto[_key][4];
		_contCampo		= _elem.value;
		_largCont		= _contCampo.length;
		_tamMax			= _arrayForm[_key][3];
		_tamRestante	= _tamMax - _largCont;
		_tipo      		= _arrayForm[_key][1];
		if(!fVerificaTamMax())
		{
				if(_largCont>=_tamMax)
					fSetValue(_contCampo.substr(0,_tamMax));
		}
		if(_mostraTam==1)
			document.getElementById("txt"+_elem.id).innerHTML = "| "+_largCont+" de "+ _tamMax +" caracteres |";
		
		if(_tipo == 8)
		{// telefone;
		_contCampo  = _contCampo.replace(_somNum,'');
			fSetValue(FncFormatar(_contCampo,"TELDDD"));
		}
		
	}
}
function fForm(objeto)
{
    _arrayForm		= objeto;
	_typeElem		= _elem.type;
	if (fLocalizarNoArray(_arrayForm,_elem.id)  && _evt.keyCode != 8 && _evt.keyCode != 32 && _evt.keyCode != 37 && _evt.keyCode != 39 && _evt.keyCode != 46 && _typeElem != "submit")
	{
		_id				= _arrayForm[_key][0];
		_tipo      		= _arrayForm[_key][1];
		_obrig 	   		= _arrayForm[_key][2];
		_contCampo		= _elem.value;
		_largCont		= _contCampo.length;
		//alert(document.getElementById(_id).value);
		_tamMax			= _arrayForm[_key][3];
		_tamRestante	= _tamMax - _largCont;
		_typeElem		= _elem.type;
		_formName		= _arrayForm[_key][5];
		
		fMostraTamMax(objeto);
		if(fVerificaTamMax())
		{
			switch (_tipo)
			{
				case 1:  // Somente String;
					_contCampo  = _contCampo.replace(_somStr,'');
					fSetValue(_contCampo);
					break;
				case 2:  // Somente Alpha numérico;
					_contCampo  = _contCampo.replace(_somAlphNum,'');
					fSetValue(_contCampo);
					break;				
				case 3:  // Qualquer caracter menos html;
					_contCampo  = _contCampo.replace(_menosHtml,'');
					fSetValue(_contCampo);				
					break;
				case 4:  // Qualquer caracter inclusive html;
					break;						
				case 5:  // Somente número;
					break;			
				case 6:  // email;
					_contCampo  = _contCampo.replace(_somEmail,'');
					fSetValue(_contCampo);
					break;				
				case 7:  // cnpj;
					_contCampo  = _contCampo.replace(_somNum,'');
					fSetValue(FncFormatar(_contCampo,"CNPJ"));
					break;			
				case 8:  // telefone;
					_contCampo  = _contCampo.replace(_somNum,'');
					fSetValue(FncFormatar(_contCampo,"TELDDD"));
					break;			
				case 9:  // cep;
					break;			
				case 10:  // cpf;
					break;
				default:
					alert("Tipo "+_tipo+" ainda não definido.");
					break;
			}
		}
	}
}
// Padrões: 'CNPJ','CPF','CEP','TEL','TELDDD','DATACOMP','DATAHORA'
function FncFormatar(num,padrao){
var	retorno = '';
num 		= somentenum(num);
largCont	= num.length;

switch(padrao)
{
	case 'CNPJ': // 99999999999999
		if(largCont <= 2)
			retorno = num.substr(0,2);
		else if(largCont > 2 && largCont <= 5)
			retorno = num.substr(0,2)+ '.' + num.substr(2,3);
		else if(largCont > 5 && largCont <= 8)
			retorno = num.substr(0,2) + '.' + num.substr(2,3) + '.' + num.substr(5,3);
		else if(largCont > 8 && largCont <= 12)
			retorno = num.substr(0,2) + '.' + num.substr(2,3) + '.' + num.substr(5,3) + '/' + num.substr(8,4);
		else if(largCont > 12)
			retorno = num.substr(0,2) + '.' + num.substr(2,3) + '.' + num.substr(5,3) + '/' + num.substr(8,4) + '-' + num.substr(12,2);
	break;
	case 'CPF': // 99999999999

		if(largCont <= 2)
			retorno = num.substr(0,3);
		else if(largCont > 2 && largCont <= 5)
			retorno = num.substr(0,3)+'.'+num.substr(3,3);
		else if(largCont > 5 && largCont <= 8)
			retorno = num.substr(0,3)+'.'+num.substr(3,3)+'.'+num.substr(6,3);
		else if(largCont > 8)
			retorno = num.substr(0,3)+'.'+num.substr(3,3)+'.'+num.substr(6,3)+'-'+num.substr(9,2);
	break;
	case 'CEP': // 99999999
		if(largCont > 0 && largCont <= 2)
			retorno = num.substr(0,2);
		else if(largCont > 2 && largCont <= 5)
			retorno = num.substr(0,2)+'.'+num.substr(2,3);
		else if(largCont > 5)
			retorno = num.substr(0,2)+'.'+num.substr(2,3)+'-'+num.substr(5,3);
	break;
	case 'TELDDD': // 9999999999
		if(largCont > 0 && largCont <= 2)
			retorno = '('+num.substr(0,2);
		else if(largCont > 2 && largCont <= 6)
			retorno = '('+num.substr(0,2)+') '+num.substr(2,4);
		else if(largCont > 6)
			retorno = '('+num.substr(0,2)+') '+num.substr(2,4)+'-'+num.substr(6,4);
	break;
	case 'DATACOMP': // 99999999
		if(largCont > 0 && largCont <= 2)
			retorno = num.substr(0,2);
		else if(largCont > 2 && largCont <= 4)
			retorno = num.substr(0,2)+'/'+num.substr(2,2);
		else if(largCont > 4)
			retorno = num.substr(0,2)+'/'+num.substr(2,2)+'/'+num.substr(4,4);
	break;		
	default:
		alert('Padrão ainda não definido');
		return null;
	break;
}
return retorno;
}
// Verifica se só tem string
function fVerificaString(valor)
{
	somStr = valor.replace(_somStr,'');
		// Se o tamanho o valor for diferente o conteúdo não tem só string
		if(valor.length != somStr.length)
		{
			fErro("O campo "+_id.toUpperCase()+" deve ter apenas letras");
		}
}
function fVerificaEmail(valor)
{
	if(!isEmail(valor))
	{
		fErro("O campo "+_id.toUpperCase()+" deve possuir um formato de email válido");
	}
}
// Valida email
function isEmail(text){
   var    arroba = "@",
          ponto = ".",
         posponto = 0,
         posarroba = 0;
   
    if (text =="") return false;
   
    for (var indice = 0; indice < text.length; indice++){
       if (text.charAt(indice) == arroba) {
          posarroba = indice;
            break;
       }
    }
   
   for (var indice = posarroba; indice < text.length; indice++){
      if (text.charAt(indice) == ponto) {
         posponto = indice;
           break;
      }
   }
   if (posponto == 0 || posarroba == 0) return false;
   if (posponto == (posarroba + 1)) return false;
   if ((posponto + 1) == text.length) return false;
   return true;
}
// Validar CPF e CNPJ, sendo pType = 1 para CPF e 2 CNPJ
function isCPFCNPJ(campo,pType){
   if(campo==""){return false;}

   var campo_filtrado = "", valor_1 = " ", valor_2 = " ", ch = "";
   var valido = false;
        
   for (i = 0; i < campo.length; i++){
      ch = campo.substring(i, i + 1);
      if (ch >= "0" && ch <= "9"){
         campo_filtrado = campo_filtrado.toString() + ch.toString()
         valor_1 = valor_2;
         valor_2 = ch;
      }
      if ((valor_1 != " ") && (!valido)) valido = !(valor_1 == valor_2);
   }
   if (!valido) campo_filtrado = "12345678912";

   if (campo_filtrado.length < 11){
      for (i = 1; i <= (11 - campo_filtrado.length); i++){campo_filtrado = "0" + campo_filtrado;}
   }

   if(pType <= 1){
      if ( ( campo_filtrado.substring(9,11) == checkCPF( campo_filtrado.substring(0,9) ) ) && ( campo_filtrado.substring(11,12)=="") ){return true;}
   }

   if((pType == 2) || (pType == 0)){
      if (campo_filtrado.length >= 14){
         if ( campo_filtrado.substring(12,14) == checkCNPJ( campo_filtrado.substring(0,12) ) ){ return true;}
      }
   }
   
   return false;
}

function checkCNPJ(vCNPJ){
   var mControle = "";
   var aTabCNPJ = new Array(5,4,3,2,9,8,7,6,5,4,3,2);
   for (i = 1 ; i <= 2 ; i++){
      mSoma = 0;
      for (j = 0 ; j < vCNPJ.length ; j++)
         mSoma = mSoma + (vCNPJ.substring(j,j+1) * aTabCNPJ[j]);
      if (i == 2 ) mSoma = mSoma + ( 2 * mDigito );
      mDigito = ( mSoma * 10 ) % 11;
      if (mDigito == 10 ) mDigito = 0;
      mControle1 = mControle ;
      mControle = mDigito;
      aTabCNPJ = new Array(6,5,4,3,2,9,8,7,6,5,4,3);
   }
   return( (mControle1 * 10) + mControle );
}

function checkCPF(vCPF){
   var mControle = ""
   var mContIni = 2, mContFim = 10, mDigito = 0;
   for (j = 1 ; j <= 2 ; j++){
      mSoma = 0;
      for (i = mContIni ; i <= mContFim ; i++)
         mSoma = mSoma + (vCPF.substring((i-j-1),(i-j)) * (mContFim + 1 + j - i));
      if (j == 2 ) mSoma = mSoma + ( 2 * mDigito );
      mDigito = ( mSoma * 10 ) % 11;
      if (mDigito == 10) mDigito = 0;
      mControle1 	= mControle;
      mControle 	= mDigito;
      mContIni 		= 3;
      mContFim 		= 11;
   }
   return( (mControle1 * 10) + mControle );
}
function somentestring(valor)
{
	return valor.replace(_somStr,'');
}
function somentenum(valor)
{
	return valor.replace(_somNum,'');
}
// Retorna apenas a parte numérica, retirando todos os outros caracteres
function somentenumerico(valor)
{
	return valor.replace(_somNumerico,'');
}
// Retorna apenas as parte inteira sem sinal
function somenteintposit(num)
{
	return Math.abs(parseInt(num));
}
function localizapattern(string,pattern)
{
	return string.search(pattern);
}
function _isEmpty(valor)
{
	return valor.length > 0 && valor != ""? false : true;
}
function montastringproibida(string,pattern)
{
	if(localizapattern(string,pattern)>=0)
		return pattern.source;
}
function retiracaracterespattern(string)
{
	return string.replace(/[\[\]\\]/g,'');
}
function verificaSomenteString(string)
{
	tamOriginal = string.length;
	tamFiltrado = string.replace(_somStr,'').length;
	if(tamOriginal != tamFiltrado)
		return false;
	else
		return true;	
}
function validaData(data)
{
   partes 	= data.split('/');	
   dia		= partes[0];
   mes		= partes[1];
   ano		= partes[2];
   data 	= new Date();
   anoAtual = data.getFullYear();
   if(((dia<1) || (dia>31))
	   || ((mes<1) || (mes>12))
	   || ((ano<anoAtual-110) || (ano>=anoAtual)))
	   return 0;
   else
   	   return 1;
}
function validaTEL(tel)
{
	rexp = /[^0-9]/g;
	numeros = tel.replace(rexp,'');
	if(numeros.length==10)
		return true;
	else
		return false;
}
function validaCEP(cep)
{
	rexp = /[^0-9]/g;
	numeros = cep.replace(rexp,'');
	if(numeros.length==8)
		return true;
	else
		return false;
}
function validaCPF(cpf)
{
	return isCPFCNPJ(cpf,1);
}