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 !!.");
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("Número 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 ;
	}		
}

/// 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'){
	  	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') {
		   document.form3.action = "/servicos/boleto_licen_ano_ant/grava_txt_con.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.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;
}

//Validação de data
//Não vai ser mexido nessa função a pricipio por já está sendo usada em outros serviços
//como a comunicação de venda. Por isso vai ser feito uma cópia dela para uma nova função abaixo.
////////////////////////////////////////////////////////
function date_validate(hldForm)
{
   var chk    = 0;
   var maxDay = 0;
   var dd = hldForm.fDia.value; // day
   var mm = hldForm.fMes.value; // month
   var yyyy = hldForm.fAno.value; // year

// calling function to get maximum day for this month
maxDay = max_day(mm, yyyy);  

if((dd <= 0) || (dd > maxDay))
{ chk = 1;}
else if((mm <= 0) || (mm > 12))
{ chk = 1;}
else if((yyyy <= 0))
{ chk = 1;} 

if(chk == 1)
{ alert('Data inválida.');
	return false;}
else
{ return true;}
}

// function for calculating maximum day 
function max_day(mn, yr)
{
   var mDay;
if((mn == 4) || (mn == 6) || (mn == 9) || (mn == 11))
{ 
mDay = 30;
}
else if(mn == 2)
{
//calling leap year function 
mDay = isLeapYear(yr) ? 29 : 28;    
}
else
{
mDay = 31;
}
return mDay; 
}

// function to check leap year
function isLeapYear(yr)
{
if (yr % 2 == 0) 
   return true;
   return false;
}

////////////////////////////////////////////////////////


//Validação de data
////////////////////////////////////////////////////////
function date_validate_generic(dia, mes, ano)
{
   var chk    = 0;
   var maxDay = 0;
   var dd = dia.value; // day
   var mm = mes.value; // month
   var yyyy = ano.value; // year

// calling function to get maximum day for this month
maxDay = max_day(mm, yyyy);  

if((dd <= 0) || (dd > maxDay))
{ chk = 1;}
else if((mm <= 0) || (mm > 12))
{ chk = 1;}
else if((yyyy <= 0))
{ chk = 1;} 

if(chk == 1)
{ alert('Data inválida.');
	return false;}
else
{ return true;}
}

// function for calculating maximum day 
function max_day(mn, yr)
{
   var mDay;
if((mn == 4) || (mn == 6) || (mn == 9) || (mn == 11))
{ 
mDay = 30;
}
else if(mn == 2)
{
//calling leap year function 
mDay = isLeapYear(yr) ? 29 : 28;    
}
else
{
mDay = 31;
}
return mDay; 
}

// function to check leap year
function isLeapYear(yr)
{
if (yr % 2 == 0) 
   return true;
   return false;
}
////////////////////////////////////////////////////////


//Validação de data de um único campo
////////////////////////////////////////////////////////
function date_validate_generic2(dia, mes, ano)
{
   var chk    = 0;
   var maxDay = 0;
   var dd = dia; // day
   var mm = mes; // month
   var yyyy = ano; // year

// calling function to get maximum day for this month
maxDay = max_day(mm, yyyy);  

if((dd <= 0) || (dd > maxDay))
{ chk = 1;}
else if((mm <= 0) || (mm > 12))
{ chk = 1;}
else if((yyyy <= 0))
{ chk = 1;} 

if(chk == 1)
{ alert('Data inválida.');
	return false;}
else
{ return true;}
}

// function for calculating maximum day 
function max_day(mn, yr)
{
   var mDay;
if((mn == 4) || (mn == 6) || (mn == 9) || (mn == 11))
{ 
mDay = 30;
}
else if(mn == 2)
{
//calling leap year function 
mDay = isLeapYear(yr) ? 29 : 28;    
}
else
{
mDay = 31;
}
return mDay; 
}

// function to check leap year
function isLeapYear(yr)
{
if (yr % 2 == 0) 
   return true;
   return false;
}
////////////////////////////////////////////////////////



// Função que permiti digitar somente letras e espaços

var mikExp = /[\d{9}$\\@\\\#%\^\&\é\ó\ê\ô\á\â\à\ú\í\´\*\(\)\[\]\+\_\{\}\`\~\=\|\.\-\/\§\%\¨\¬\!]/;
function dodacheck(val) {
var strPass = val.value;
var strLength = strPass.length;
var lchar = val.value.charAt((strLength) - 1);
if(lchar.search(mikExp) != -1) {
var tst = val.value.substring(0, (strLength) - 1);
val.value = tst;
   }
}
function submit_nomes(form) {
if(form.value.length < 1) {
alert("O preenchimento do campo é obrigatório!!");
form.focus();
return false;
}
if(form.value.search(mikExp) == -1) {
//alert("Valor Incorreto!");
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.focus();
return false;
}
//alert("Campo Preenchido!");
return false;
}

// Função que permiti digitar somente letras e espaços
var mikExp = /[\d{9}$\\@\\\#%\^\&\é\ó\ê\ô\á\â\à\ú\í\´\*\(\)\[\]\+\_\{\}\`\~\=\|\.\-\/\§\%\¨\¬\!]/;
function submit_nomes2(form) {
var espaco = " ";
if((form.value.length < 4)||(form.value.search(espaco) == -1)){
alert("Preencha nome e sobrenome!!");
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\ neste campo!\n");
//form.select();
form.value = form.value.substr((form.value.length -1));
form.focus();
return false;
}
return false;
}


// Screen save Voltar
// Inicio
var x, y, xold, yold, xmove, ymove;
document.onmousemove = FindXY;
function FindXY(loc) {
x = (document.layers) ? loc.pageX : event.clientX;
y = (document.layers) ? loc.pageY : event.clientY;
xmove = x - xold;
ymove = y - yold
if ((xmove <  2) && (ymove < -2)) ResetTimer();
if ((xmove <  2) && (ymove >  2)) ResetTimer();
if ((xmove >  2) && (ymove <  2)) ResetTimer();
if ((xmove < -2) && (ymove <  2)) ResetTimer();
if ((xmove >  2) && (ymove >  2)) ResetTimer();
if ((xmove >  2) && (ymove < -2)) ResetTimer();
if ((xmove < -2) && (ymove >  2)) ResetTimer();
if ((xmove < -2) && (ymove < -2)) ResetTimer();
xold = x;
yold = y;
}

var TimeOut = 20;   
var TimeRemain = 0;  
var RefreshRate = 1; 
function Voltar(){
 ResetTimer();
 if (TimeOut && RefreshRate)
    setTimeout("CheckFim();",RefreshRate * 1000);
}
function ResetTimer(){
 TimeRemain = TimeOut;
 //document.form1.field1.value = TimeRemain; 
}
function CheckFim(){
 TimeRemain -= (RefreshRate);
 if (TimeRemain > 0){
   // document.form1.field1.value = TimeRemain; 
	  setTimeout("CheckFim();",RefreshRate * 1000);
    } else{
		 window.location = "frame_down.php";
		}
}
// Fim