var msg = null;
var browser = null;

 //-------------- suporte a ajax -------------------------------
try {
     ajax = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e) {
       try {
          ajax = new ActiveXObject("Msxml2.XMLHTTP");
       }
       catch(ex) {
          try {
             ajax = new XMLHttpRequest();
              }
	        catch(exc) {
               alert("Esse browser não tem recursos para uso do Ajax");
               ajax = null;
            }
         }
      }
	  
if (window.ActiveXObject) {browser = "ie";}
	 
//Validação Numero de registro
function validar_numero_registro(value){
	  len = value.length; 
	  temp = value.substring(0,len-2)
	  
	  dig1 = Digito(temp);
	  dig2 = Digito(dig1+temp);
	   
	  if ( ((dig1 + "" + dig2) == value.substring(len-2,len)) && (len > 10) )  {
		 return true;
      } else {
        alert ("Número do Registro inválido !!."); 
        return false;
	  }
}

function Digito(num){
	soma = 0;
	resto = 0;
	x = 2;
	tamanho = num.length; 
	//calculo D1
    for (var i=0; i <= tamanho; i++) {
	   y = num.substring(i,i+1);
	   soma = soma + ( y * x);
	   x = x + 1;
	} 
	resto = (soma % 11);
	if ((resto == 0)||(resto == 1)) dig = 0 ;
    if (resto >  1) dig = 11 - resto;
	return dig;
}

//Validação de CPF
function checar_cnpf(dados) {
 temp = dados.length;
 if (temp <= 11) {
//testar CNPF
x = 0;
soma = 0;
dig1 = 0;
dig2 = 0;
texto = "";
numcpf1 = "";
len = dados.length; x = len -1;
// var numcpf = "12345678909";
for (var i=0; i <= len - 3; i++) {
	y = dados.substring(i,i+1);
	soma = soma + ( y * x);
	x = x - 1;
	texto = texto + y;
}
dig1 = 11 - (soma % 11);
if (dig1 == 10) dig1=0 ;
if (dig1 == 11) dig1=0 ;
numcpf1 = dados.substring(0,len - 2) + dig1 ;
x = 11; soma=0;
for (var i=0; i <= len - 2; i++) {
	soma = soma + (numcpf1.substring(i,i+1) * x);
	x = x - 1;
}
dig2= 11 - (soma % 11);
if (dig2 == 10) dig2=0;
if (dig2 == 11) dig2=0;

if ((dig1 + "" + dig2) == dados.substring(len,len-2)) {
	
	return true;
}
alert ("Número do CPF inválido !!.");
//dados.focus();
return false;
	} else {
 // testar CNPJ


var dig1=0;
var dig2=0;
var x;
var Mult1 = '543298765432';
var Mult2 = '6543298765432';

for(x=0; x<=11; x++) {
	dig1 = dig1 +(parseInt(dados.slice(x,x+1)) * parseInt(Mult1.slice(x,x+1)));
 }
for(x=0; x<=12; x++) {
	dig2 = dig2 + (parseInt(dados.slice(x, x+1)) * parseInt(Mult2.slice(x,x+1)));
	}

 dig1 = (dig1 * 10)%11;
 dig2 = (dig2 * 10)%11;

if (dig1 == 10) {dig1 = 0;}
if (dig2 == 10) {dig2 = 0;}

if (dig1 != parseInt(dados.slice(12, 13))) {
	 alert("Número do CNPJ Inválido");	 
	 return false;
	 } else {
		 if (dig2 != parseInt(dados.slice(13, 14))) {
				alert("Número do CNPJ Inválido");			 
				return false;
		 } else {
				return true;
		 }
	 }
return true;
 }
}

//Validação do Código Renavam
function valida_fCodigoRenavamavam(numero)
{
    var campofCodigoRenavam;
    campofCodigoRenavam = numero.value;

    if (campofCodigoRenavam != "")
        {
        if (!mapeia(campofCodigoRenavam,"Renavam"))
                    return false;
        if (!CalcDigVer(campofCodigoRenavam))
                return false;
        }
   else
        {
            alert("Para efetivar a consulta, informe o Renavam.");
                        return false;
                }
   return true;
}


function mapeia(campo,nome)
{
        for (i=0;i<campo.length;i++)
        {
                aux = campo.substring(i,i+1);
                if (aux == "-" || aux ==".")
                {
                        alert("O "+nome+" deve ser informado sem ponto ou hífen.");
                        return false;
                }
                if ((aux>"9")||(aux<"0"))
                {
                        alert(nome+" inválido.");
                        return false;
                }
        }
 return true;   
}


function formatar(fCodigoRenavamavam)
{
   valorFormatado = "";
   for (i=0;i<9-(fCodigoRenavamavam.length);i++)
   {
      valorFormatado = valorFormatado + "0";
   }
   valorFormatado = valorFormatado + fCodigoRenavamavam;
   return valorFormatado;
}


function CalcDigVer(fCodigoRenavamavam)
{
        //Calculo do dígito verificador
        soma = 0;
        fCodigoRenavamav = formatar(fCodigoRenavamavam);
        for (i=(fCodigoRenavamav.length)-1,j=2;i>0;i--,j++)
   {
      aux = fCodigoRenavamav.substring(i-1,i);
      soma = soma + (j * aux);
   }
   digito = 11-(soma-((parseInt(soma/11))*11));
   if (digito == 10)
      digito = 0;
   if (digito == 11)
      digito = 0;
   aux = fCodigoRenavamav.substring(8,9);
   if (aux==digito)
      return true
   else
   {
      alert("Numero do Renavam Incorreto.");
      return false;
   }
   return true;
}


//Mostra textos de auxílio
function SetHelp(txt) { 
		help.innerText = txt; 
	}

//Impede que seja visualizado o código fonte da página
function verfonte() {
   if (event.button==2){
     window.alert("Não Disponível!");
	 }
}	 
document.onmousedown=verfonte



//Faz a verificação da placa
function verifica_placa(Placa1, Placa2) {
	if (Placa1.value=='' ) {
		alert('A placa deve ser informada por completa!');
		Placa1.focus();    		
		return false;
	}
	if (Placa2.value=='' ) {
		alert('A placa deve ser informada por completa!');
		Placa2.focus();
		return false;
	} 
	var regExp = /^([A-Za-z])+$/;
	if (!regExp.test(Placa1.value) ) {
		alert('A primeira parte da placa deve ter só letras!');
		Placa1.focus();
		return false ;
	}	
	var regExp = /^\d{4}$/;
	if (!regExp.test(Placa2.value) ) {
		alert('A segunda parte da placa deve conter 4 números!');
		Placa2.focus();
		return false ;
	}
	return true;		
}

/// veriicar a senha cripto 
function verifica_senha(senha) {
	if (senha.value=='' ) {
		alert('Digite a senha contida na imagem !!');
		senha.focus();    		
		return false;
	}
	 if (document.forms[0].password.value == null){
	 	alert ('erro na contra-senha !!');
		senha.focus();
		return false;
	 }
	 if(ajax) {
		 msg = null;
	     if (browser == "ie")	{ajax.open("GET", "/servicos/passw.php", false);}
			 else 				{ajax.open("POST", "/servicos/passw.php", true);}
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 ajax.onreadystatechange = function() {
         	if (ajax.readyState == 4) {
			   if(ajax.responseXML)  {	// O XML retornado pelo script server-side.  
//			        lerXML(ajax.responseXML);
			        var dados = ajax.responseXML.getElementsByTagName("resposta");  	      
				    if(dados.length > 0) {
			            var item = dados[0];
						msg =  item.getElementsByTagName("msg")[0].firstChild.nodeValue;
						if (browser != "ie"){
							alert (msg + ' !!');
							senha.focus();
							false;
							}
				    }  // end-if(dados.length > 0) {		
			   }  // end-if(ajax.responseXML)	
            }  //end-if(ajax.readyState == 4 )		
         }  //end-ajax.onreadystatechange = function() {
 	     var params = "&password=" + document.forms[0].password.value + "&senha=" + senha.value;
         ajax.send(params);
     } // end-if(ajax) {
  	  if (msg){  // A senha digitada não confere com a contra senha
	    alert (msg);
		senha.focus();
		return false;
	  }	
}


//redireciona form atraves da escolha do radio button
function redireciona_form3(){
    // verifica o renavam
	if (!valida_fCodigoRenavamavam(document.form3.fCodigoRenavam))
     {
	 return false;
	 }
	 	 
    for(i=0; i < document.form3.op.length; i++){ 
			if (document.form3.op[i].checked){
	          break;
			  }
	      }

	// consulta orgamento/licenciamento 2002
	if (document.form3.op[i].value == '0'){
	  	//enquanto estiver em manutencao
			//document.form3.action = "/servicos/boleto_licenciamento/grava_txt_con.php"
			document.form3.action = "/servicos/boleto_licenciamento/index.php";
		document.form3.submit();
			//window.open('http://www.arinternet.pr.gov.br');			
       return false;
       }
   	   //consulta veículo
          if (document.form3.op[i].value == '1') {
		   //enquanto estiver em manutencao
			 //document.form3.action = "/servicos/boleto_licen_ano_ant/grava_txt_con.php"
			 document.form3.action = "/servicos/boleto_licen_ano_ant/index.php"
		   document.form3.submit();
       	   return false;
        }
      //consulta infração
           if (document.form3.op[i].value == '2'){
             // document.form3.action = "/servicos/veiculo/ver_uf_pa2.php"
			  document.form3.action = "/servicos/veiculo/index2.php"
		      document.form3.submit();
		     //window.open('http://www.arinternet.pr.gov.br');
       	      return false;
           }
    return true;
}

// Tabulação automatica de caracteres
function autoTab(input,len, e) {
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
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;
}


// Função que permiti digitar somente letras e espaços

var mikExp = /[\d{9}$\\@\\\#%\^\&\é\ó\ê\ô\á\â\à\ú\í\´\*\(\)\[\]\+\_\{\}\`\~\=\|\.\-\/\§\%\¨\¬\!]/;
function submit_nomes(form) {
var espaco = " ";
if((form.value.length < 4)||(form.value.search(espaco) == -1)){
alert("Preencha o campo Nome Corretamente!!");
form.focus();
return false;
}
if(form.value.search(mikExp) == -1) {
//alert("Valor Correto!");
return true;
}
else {
alert("Não são permitidos os caracteres\n\r\n\r@ $ % ^ & * # ( ) [ ] \\ { + } ` ~ = | 0-9 \n\r\n\ no campo Nome!\n");
//form.select();
form.value = form.value.substr((form.value.length -1));
form.focus();
return false;
}
return false;
}

//Faz a validação do número da guia
function validaGuia(nNumeroGuia) {
	var regExp = /^\d{9,}$/;
	if (!regExp.test(nNumeroGuia.value) ) {
		alert('A número da guia deve ter 9 digitos numéricos!');
		nNumeroGuia.focus();
		return false ;
	} else {
		return true;
	}		
}

// function to restrict any non-numeric key pressing
function nn_Key()
{
if ((event.keyCode<48) || (event.keyCode>57))
event.keyCode = 0;
}


function teclas(oForm){
	alert('teste');
	alert(oForm.action);
 //document.onkeypress = redirect(oForm);
}

function ColourRoll(src, colour) {
 src.style.backgroundColor=colour;
}