campos = new Array();
nomes = new Array();
tipos = new Array();
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
var keyCode = (isNN) ? e.which : e.keyCode; 
var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
if(input.value.length >= len && !containsElement(filter,keyCode)) {
input.value = input.value.slice(0, len);
input.form[(getIndex(input)+1) % input.form.length].focus();
}

function containsElement(arr, ele) {
var found = false, index = 0;
while(!found && index < arr.length)
if(arr[index] == ele)
found = true;
else
index++;
return found;
}
function getIndex(input) {
var index = -1, i = 0, found = false;
while (i < input.form.length && index == -1)
if (input.form[i] == input)index = i;
else i++;
return index;
}
return true;
}

//============================================================================

/***
* Descrição.: formata um campo do formulário de
* acordo com a máscara informada...
* Parâmetros: - objForm (o Objeto Form)
* - strField (string contendo o nome
* do textbox)
* - sMask (mascara que define o
* formato que o dado será apresentado,
* usando o algarismo "9" para
* definir números e o símbolo "!" para
* qualquer caracter...
* - evtKeyPress (evento)
* Uso.......: <input type="textbox"
* name="xxx".....
* onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);">
* Observação: As máscaras podem ser representadas como os exemplos abaixo:
* CEP -> 99.999-999
* CPF -> 999.999.999-99
* CNPJ -> 99.999.999/9999-99
* Data -> 99/99/9999
* Tel Resid -> (99) 999-9999
* Tel Cel -> (99) 9999-9999
* Processo -> 99.999999999/999-99
* C/C -> 999999-!
* E por aí vai...
***/

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

if(document.all) { // Internet Explorer
nTecla = evtKeyPress.keyCode; }
else if(document.layers) { // Nestcape
nTecla = evtKeyPress.which;
}

sValue = objForm[strField].value;

// Limpa todos os caracteres de formatação que
// já estiverem no campo.
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( ":", "" );
sValue = sValue.toString().replace( " ", "" );
sValue = sValue.toString().replace( " ", "" );
fldLen = sValue.length;
mskLen = sMask.length;

i = 0;
nCount = 0;
sCod = "";
mskLen = fldLen;

while (i <= mskLen) {
bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/")|| (sMask.charAt(i) == ":"))
bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

if (bolMask) {
sCod += sMask.charAt(i);
mskLen++; }
else {
sCod += sValue.charAt(nCount);
nCount++;
}

i++;
}

objForm[strField].value = sCod;

if (nTecla != 8) { // backspace
if (sMask.charAt(i-1) == "9") { // apenas números...
return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
else { // qualquer caracter...
return true;
} }
else {
return true;
}
}
//Fim da Função Máscaras Gerais

//=================================================================================================================

var limit="30:00"
if (document.images){
var parselimit=limit.split(":")
parselimit=parselimit[0]*60+parselimit[1]*1
}
function begintimer(){
if (!document.images)
return
if (parselimit==1)
window.location="sessao_invalida.html"
else{ 
parselimit-=1
curmin=Math.floor(parselimit/60)
cursec=parselimit%60
if (curmin!=0)
curtime=curmin+" minutos e "+cursec+" segundos"
else
curtime=cursec+" segundos"
//window.status=curtime
window.document.form1.timespent.value = curtime
setTimeout("begintimer()",1000)
}
}
//-->

//===========================================================================================================

function max(txarea)
 
{
 
	total = 100;
	 
	tam = txarea.value.length;
	 
	str="";
	 
	str=str+tam;
	 
	Digitado.innerHTML = str;
	 
	Restante.innerHTML = total - str;
	 
	 
	if (tam > total){
	 
	aux = txarea.value;
	 
	txarea.value = aux.substring(0,total);
	 
	Digitado.innerHTML = total
	 
	Restante.innerHTML = 0
	}
}

//===========================================================================

	function verificaNum() {
		 if (!(event.keyCode > 45 && event.keyCode < 58)) {
			event.returnValue = false;
		}
	 }
//===========================================================================	 
//===========================================================================

	function verificaCaracterMoeda() {
		 if (!(event.keyCode > 46 && event.keyCode < 59 || event.keyCode == 44 )) {
			event.returnValue = false;
		}
	 }
//===========================================================================

//===========================================================================	 
	 function verificaMoeda(objForm, strField) {
						var sValue;
						var mskLen;
						sValue = objForm[strField].value;
						mskLen = objForm[strField].value.length;
						nCount = 0;
						i = 0;
						while (i <= mskLen) {
							if (sValue.charAt(i) == ","){
								nCount = nCount +1;
							}
							i++;
						}
						
						if (nCount > 1){
							alert('O valor digitado é inválido');
							event.returnValue = false;
							objForm[strField].focus();
						}
	 }
//===========================================================================

        function LimpaCampo(campo_check,campo_texto){
            if(campo_check.checked == false){
               campo_texto.value = ""; 
               campo_texto.disabled = true;
            }else{
               campo_texto.disabled = false; 
               campo_texto.focus();
            }

        }

//===========================================================================

    function ChecaConteudo(campo_check,campo_texto,event){
        if(campo_check.checked == true && campo_texto.value == ''){
            alert('vazio');
            campo_texto.focus();
        }else{
        }
    }

//===========================================================================

    function Verifica_Preenche(documento,campo,nome_campo,event){
        if(documento[campo].value == ''){
            event.returnValue = false;
            alert('Prencha o campo '+nome_campo+'!');
            documento[campo].focus();
            return false;
        }
    }

//===========================================================================

//Exemplo de uso
//Onload da página => onLoad="VerificaCampo(this.form,'campos','cnpj,razao_social,nome');VerificaCampo(this.form,'nomes','cnpj,razão social,nome da empresa,');VerificaCampo(this.form,'tipos','simples,simples');"
//Caso a verificação seja de tipo combinado, o checkbox deve receber o valor do tipo de validação
//no caso "combinado" e o campo texto da combinação recebe valor "vazio" ,,
//exemplo: VerificaCampo(this.form,'campos','textfield,textfield2,textfield2,checkbox,textfield4,select')
//exemplo: VerificaCampo(this.form,'tipos','simples,simples,e-mail,combinado,,simples')

    function VerificaCampo(documento,nome,valor){
            if(nome == 'campos'){
                    campos = valor.split(',');
                    return;
            }else if(nome == 'nomes'){
                    nomes = valor.split(',');
                    return;
            }else if(nome == 'tipos'){
                    tipos = valor.split(',');			
                    return;
            }
    }		

//===========================================================================

    function Verifica(documento,campo,nomes,tipos){
            var a=0;
            for(i=0;i<tipos.length;i++){
                    if(tipos[i] == 'simples'){							//Verifico o tipo de validação que deve ser feita
                            if (documento[campo[i]].type == 'text'){				//Verifico se é do tipo texto
                                    if(documento[campo[i]].value == ''){			//Verifico se está vazio
                                            alert('Preencha o campo '+nomes[i]+'');
                                            documento[campo[i]].focus();
                                            return false;
                                    }
					}else if(documento[campo[i]].type == 'select-one' || documento[campo[i]].type == 'select-multiple'){ 	//Verifico se é do tipo select
								if(documento[campo[i]].value == ''){															//Verifico se está vazio
										alert('Selecione um valor para o '+nomes[i]+'');
										documento[campo[i]].focus();
										return false;
								}				
						  }
                    }else if(tipos[i] == 'arquivo'){								//Verifico o tipo de validação que deve ser feita
                            if (documento[campo[i]].type == 'file'){				//Verifico se é do tipo texto
                                    if(documento[campo[i]].value == ''){			//Verifico se está vazio
                                            alert('Preencha o campo '+nomes[i]+'');
                                            documento[campo[i]].focus();
                                            return false;
                                    }
                            }			
                    }else if(tipos[i] == 'senha'){								//Verifico o tipo de validação que deve ser feita
                            if (documento[campo[i]].type == 'password'){				//Verifico se é do tipo texto
                                    if(documento[campo[i]].value == ''){			//Verifico se está vazio
                                            alert('Preencha o campo '+nomes[i]+'');
                                            documento[campo[i]].focus();
                                            return false;
                                    }
                            }			
                    }else if(tipos[i] == 'areatexto'){								//Verifico o tipo de validação que deve ser feita
                            if (documento[campo[i]].type == 'textarea'){				//Verifico se é do tipo texto
                                    if(documento[campo[i]].value == ''){			//Verifico se está vazio
                                            alert('Preencha o campo '+nomes[i]+'');
                                            documento[campo[i]].focus();
                                            return false;
                                    }
                            }			
                    }else if(tipos[i] == 'e-mail'){								//Verifico o tipo de validação que deve ser feita
                            if (documento[campo[i]].type == 'text'){				//Verifico se é do tipo texto
                                    if(documento[campo[i]].value.indexOf('@') == -1){	//Verifico se contém o @ arroba
                                            alert('Este não é um e-mail válido '+documento[campo[i]].value+'');
                                            documento[campo[i]].focus();
                                            return false;
                                    }
                                    if(documento[campo[i]].value.indexOf('.') == -1){	//Verifico se contém o . arroba
                                            alert('Este não é um e-mail válido '+documento[campo[i]].value+'');
                                            documento[campo[i]].focus();
                                            return false;
                                    }
                            }			
                    }else if(tipos[i] == 'combinado'){
                            if (documento[campo[i]].type == 'checkbox'){
                                    if((documento[campo[i]].checked == true) && (documento[campo[i+1]].value == '')){
                                            alert('Este campo '+documento[i+1].value+' deve ser preeenchido, ou desmarque o campo ao lado!');
                                            documento[campo[i+1]].focus();
                                            i=i++;
                                            return false;						
                                    }
                            }			
                    }else if(tipos[i] == 'maxcaracteres'){
						var maximo;
						maximo=documento[campo[i]].rows * documento[campo[i]].cols;
						if (documento[campo[i]].value.length > maximo){
							alert('O campo '+nomes[i]+' permite no máximo '+maximo+' caracteres.');
							documento[campo[i]].focus();
							return false;						
                        }
                    }		
	
            }
    }

//============================================================================================
function cpFCpnJ(CNUMB,CTYPE)
{
  if(!Verify(CNUMB.value, CTYPE))
  {
    alert(CTYPE+" inválido!");
    CNUMB.value = '';
    CNUMB.focus();
  }
  return;
}

function ClearStr(str, char)
{
  while((cx=str.indexOf(char))!=-1)
  {		
    str = str.substring(0,cx)+str.substring(cx+1);
  }
  return(str);
}

function ParseNumb(c)
{
  c=ClearStr(c,'-');
  c=ClearStr(c,'/');
  c=ClearStr(c,',');
  c=ClearStr(c,'.');
  c=ClearStr(c,'(');
  c=ClearStr(c,')');
  c=ClearStr(c,' ');
  if((parseFloat(c) / c != 1))
  {
    if(parseFloat(c) * c == 0)
    {
      return(c);
    }
    else
    {
      return(0);
    }
  }
  else
  {
    return(c);
  }
}

function Verify(CNUMB,CTYPE)
{
  CNUMB=ParseNumb(CNUMB)
  if((CNUMB == 0) || (CNUMB == 11111111111) || (CNUMB == 22222222222) || (CNUMB == 33333333333) || (CNUMB == 44444444444) || (CNUMB == 55555555555) || (CNUMB == 66666666666) || (CNUMB == 77777777777) || (CNUMB == 88888888888) || (CNUMB == 99999999999))
  {
    return(false);
  }
  else
  {
    g=CNUMB.length-2;
    if(TestDigit(CNUMB,CTYPE,g))
    {
      g=CNUMB.length-1;
      if(TestDigit(CNUMB,CTYPE,g))
      {	
        return(true);
      }
      else
      {
        return(false);
      }
    }
    else
    {
      return(false);
    }
  }
}

function TestDigit(CNUMB,CTYPE,g)
{
  var dig=0;
  var ind=2;
  for(f=g;f>0;f--)
  {
    dig+=parseInt(CNUMB.charAt(f-1))*ind;
    if (CTYPE=='CNPJ')
    { if(ind>8) {ind=2} else {ind++} }
    else
    { ind++ }
  }
  dig%=11;
  if(dig<2)
  {
    dig=0;
  }
  else
  {
    dig=11-dig;
  }
  if(dig!=parseInt(CNUMB.charAt(g)))
  {
    return(false);
  }
  else
  {
    return(true);
  }
}
