﻿function FiltraValor(campo)
{
	var s = "";
	var cp = "";
	achei = false;
	vr = eval("document.Form1."+campo+".value");
	tam = vr.length;
      if (tam > 0)
      {
		for (i = 0; i < tam ; i++) 
      	{  
	            ch = vr.substring(i,i + 1)
			if (ch != "."  && ch != "," )
	            {
				if (ch>="0" && ch<="9") s = s + ch;
	            }
      	      else
			{
				achei = true;
			}
		}
		if (!achei) 
		{  
			s=s+"00";
		}
		s=s.substring(0,s.length-2)+"."+s.substring(s.length-2,s.length)
		eval("document.Form1."+campo+".value=s");
	}
}

function soNumeros(event)
{
    var browser = navigator.appName
    if(browser == "Microsoft Internet Explorer")
    {
        if(event.keyCode>=48 && event.keyCode<=57)
        {
	        return true;
        }
        else
        {
	        return false;
        }
    }
    else
    {
        return true;
    }
}

function validaDataDiaMesAno(event, valor)
{
    var browser = navigator.appName
    if(browser == "Microsoft Internet Explorer")
    {
        if((event.keyCode>=96 && event.keyCode<=105) || (event.keyCode>=48 && event.keyCode<=57) || (event.keyCode>=12 && event.keyCode<=13) || (event.keyCode == 8)
        || (event.keyCode>=118 && event.keyCode<=123)|| (event.keyCode>=16 && event.keyCode<=20) || (event.keyCode>=32 && event.keyCode<=40)
        || (event.keyCode>=91 && event.keyCode<=93) || (event.keyCode == 27) || (event.keyCode>=144 && event.keyCode<=145) || (event.keyCode==116) ||     
        (event.keyCode==113) || (event.keyCode>=44 && event.keyCode<=46))
        {
	        if((valor.length == 2) || (valor.length == 5) || (valor.length == 10))
	        {
	            if(valor.length == 2)
	            {
	                if(valor>=1 && valor<=31)
	                {
	                    return valor + "/";
	                }
	                else
	                {
	                    return "";
	                }
	            }
	            else
	            {
	                if(valor.length == 5)
	                {
	                    var mes = valor.substring(3, 5);
	                    if(mes>=1 && mes<=12)
	                    {
	                        return valor + "/";
	                    }
	                    else
	                    {
	                       return valor.substring(0, 3);
	                    }
	                }
	                else
	                {
	                    if(valor.length == 10)
	                    {
	                        var ano = valor.substring(6, 10);
	                        if(ano>=1900 && ano<=2020)
	                        {
	                            return valor;
	                        }
	                        else
	                        {
	                            return valor.substring(0, 6);
	                        }
	                    }    
	                }
	            }
    		    
	        }
	        else		
	        {
		        return valor;
	        }
        }
        else
        {
	        return valor.substring(0, valor.length - 1);
        }
    }
    else
    {
        return valor;
    }
}

function validaHoraMinuto(event, valor)
{
    var browser = navigator.appName
    if(browser == "Microsoft Internet Explorer")
    {
        if((event.keyCode>=96 && event.keyCode<=105) || (event.keyCode>=48 && event.keyCode<=57) || (event.keyCode>=12 && event.keyCode<=13) || (event.keyCode == 8)
        || (event.keyCode>=118 && event.keyCode<=123)|| (event.keyCode>=16 && event.keyCode<=20) || (event.keyCode>=32 && event.keyCode<=40)
        || (event.keyCode>=91 && event.keyCode<=93) || (event.keyCode == 27) || (event.keyCode>=144 && event.keyCode<=145) || (event.keyCode==116) ||     
        (event.keyCode==113) || (event.keyCode>=44 && event.keyCode<=46))
        {
	        if((valor.length == 2) || (valor.length == 5))
	        {
	            if(valor.length == 2)
	            {
	                if(valor>=0 && valor<=23)
	                {
	                    return valor + ":";
	                }
	                else
	                {
	                    return "";
	                }
	            }
	            else
	            {
	                if(valor.length == 5)
	                {
	                    var minuto = valor.substring(3, 5);
	                    if(minuto>=0 && minuto<=59)
	                    {
	                        return valor;
	                    }
	                    else
	                    {
	                       return valor.substring(0, 3);
	                    }
	                }
	                
	            }
    		    
	        }
	        else		
	        {
		        return valor;
	        }
        }
        else
        {
	        return valor.substring(0, valor.length - 1);
        }
    }
    else
    {
        return valor;
    }
}

function validaDataMesAno(event, valor)
{
    var browser = navigator.appName
    if(browser == "Microsoft Internet Explorer")
    {
        if((event.keyCode>=96 && event.keyCode<=105) || (event.keyCode>=48 && event.keyCode<=57) || (event.keyCode>=12 && event.keyCode<=13) || (event.keyCode == 8)
        || (event.keyCode>=118 && event.keyCode<=123)|| (event.keyCode>=16 && event.keyCode<=20) || (event.keyCode>=32 && event.keyCode<=40)
        || (event.keyCode>=91 && event.keyCode<=93) || (event.keyCode == 27) || (event.keyCode>=144 && event.keyCode<=145) || (event.keyCode==116) ||     
        (event.keyCode==113) || (event.keyCode>=44 && event.keyCode<=46))
        {
	        if(valor.length == 2)
	        {
	            if(valor>=1 && valor<=12)
	            {
		            return valor + "/";
		        }
		        else
		        {
		            return "";
		        }
	        }
	        if(valor.length == 7)
	        {
	            var ano = valor.substring(3, 7);
	            if(ano>=1900 && ano<=2020)
	            {
	                return valor;
	            }
	            else
	            {
	                return valor.substring(0, 3);
	            }
	        }
	        else		
	        {
		        return valor;
	        }

        }
        else
        {
	        return valor.substring(0, valor.length - 1);
        }
    }
    else
    {
        return valor;
    }
}

function FiltraValorVirgula(form, campo)
{	
	var s = "";
	var cp = "";
	achei = false;
	vr = eval("document.Form1."+campo+".value");
	tam = vr.length;
      if (tam > 0)
      {
		for (i = 0; i < tam ; i++) 
      	{  
	            ch = vr.substring(i,i + 1)
			if (ch != "."  && ch != "," )
	            {
				if (ch>="0" && ch<="9") s = s + ch;
	            }
      	      else
			{
				achei = true;
			}
		}
		if (!achei) 
		{  
			s=s+"00";
		}
		s=s.substring(0,s.length-2)+","+s.substring(s.length-2,s.length)
		eval("document.Form1."+campo+".value=s");
	}
}

function FiltraData(form, campo)
{
	var s = "";
	var cp = "";
	vr = eval("document.Form1."+campo+".value");
	tam = vr.length;
	if (tam > 0)
	{
    for (i = 0; i < tam ; i++) 
    {  
      ch = vr.substring(i,i + 1)
      if (ch>='0' && ch<='9') s = s + ch;
    }
    if ((s.length != 6) && (s.length != 8))
    {
      alert("Data inválida. Use o formato dd/mm/aaaa."); 
      eval("document.Form1."+campo+".focus()"); 
    }
    else
    {
      Dia=Number(s.substring(0,2));
      Mes=Number(s.substring(2,4));
      if ((Dia<0) || (Dia>31) || (Mes<0) || (Mes>12))
      {
        alert("Data inválida. Use o formato dd/mm/aaaa.");
        eval("document.Form1."+campo+".focus()");
      }
      else
      {
        if (s.length == 6)
        {
          Ano=Number(s.substring(4,6));
          if (Ano<30) 
            Ano+=2000;
          else
            Ano+=1900;
        }
        else
        {
          Ano=Number(s.substring(4,8));
        }
        s=s.substring(0,2) + "/" + s.substring(2,4) + "/" + String(Ano);
        vr=s;
      }
    }
  }
  return vr;
}

function compasse1(s)
{
	COMP=150;
	if (s.length > COMP) 
	{
		alert("Comprimento máximo alcançado");
		return s.substring(0,COMP);
	}
	else
	{
		return s;
	}
}

function compasse2(s)
{
	COMP=240;
	if (s.length > COMP) 
	{
		alert("Comprimento máximo alcançado");
		return s.substring(0,COMP);
	}
	else
	{
		return s;
	}
}

function comprimento(s)
{
	COMP=255;
	if (s.length > COMP) 
	{
		alert("Comprimento máximo alcançado");
		return s.substring(0,COMP);
	}
	else
	{
		return s;
	}
}

function FiltraHora(campo){
	var s = "";
	var cp = "";
	vr = eval("document.Form1."+campo+".value");
	tam = vr.length;
	if (tam > 0)
	{
		for (i = 0; i < tam ; i++) 
	      {  
      	      ch = vr.substring(i,i + 1)
			if (ch>='0' && ch<='9') s = s + ch;
		}
      	if ((s.length != 4))
	      {
			alert("Hora inválida. Use o formato hhmm."); 
			eval("document.Form1."+campo+".focus()"); 
	      }
      	else
	      {
			hora=Number(s.substring(0,2));
			minuto=Number(s.substring(2,4));
	        if ((hora<0) || (hora>24) || (minuto<0) || (minuto>59))
			{
				alert("Hora inválida. Use o formato hhmm.");
				eval("document.Form1."+campo+".focus()");
			}
 			else
			{
				s=s.substring(0,2) + ":" + s.substring(2,4);
				vr=s;
			}
		}
	}
	return vr;
}

function FiltraData_Form(nome_form,campo)
{
	var s = "";
	var cp = "";
	vr = eval("document."+nome_form+"."+campo+".value");
	tam = vr.length;
	if (tam > 0)
	{
    for (i = 0; i < tam ; i++) 
    {  
      ch = vr.substring(i,i + 1)
      if (ch>='0' && ch<='9') s = s + ch;
    }
    if ((s.length != 6) && (s.length != 8))
    {
      alert("Data inválida. Use o formato DDMMAA."); 
      eval("document."+nome_form+"."+campo+".focus()"); 
      eval("document."+nome_form+"."+campo+".select()"); 
    }
    else
    {
      Dia=Number(s.substring(0,2));
      Mes=Number(s.substring(2,4));
      if ((Dia<0) || (Dia>31) || (Mes<0) || (Mes>12))
      {
        alert("Data inválida. Use o formato DDMMAA.");
        eval("document."+nome_form+"."+campo+".focus()");
        eval("document."+nome_form+"."+campo+".select()");
      }
      else
      {
        if (s.length == 6)
        {
          Ano=Number(s.substring(4,6));
          if (Ano<30) 
            Ano+=2000;
          else
            Ano+=1900;
        }
        else
        {
          Ano=Number(s.substring(4,8));
        }
        s=s.substring(0,2) + "/" + s.substring(2,4) + "/" + String(Ano);
        vr=s;
      }
    }
  }
  return vr;
}

function FiltraHora_Form(nome_form,campo){
	var s = "";
	var cp = "";
	vr = eval("document."+nome_form+"."+campo+".value");
	tam = vr.length;
	if (tam > 0)
	{
		for (i = 0; i < tam ; i++) 
	      {  
      	      ch = vr.substring(i,i + 1)
			if (ch>='0' && ch<='9') s = s + ch;
		}
      	if ((s.length != 4))
	      {
			alert("Hora inválida. Use o formato hhmm."); 
			eval("document."+nome_form+"."+campo+".focus()"); 
	      }
      	else
	      {
			hora=Number(s.substring(0,2));
			minuto=Number(s.substring(2,4));
	        if ((hora<0) || (hora>24) || (minuto<0) || (minuto>59))
			{
				alert("Hora inválida. Use o formato hhmm.");
				eval("document."+nome_form+"."+campo+".focus()");
			}
 			else
			{
				s=s.substring(0,2) + ":" + s.substring(2,4);
				vr=s;
			}
		}
	}
	return vr;
}

function FocuData_Hora(nome_form,campo)
{
	var s = "";
	var cp = "";
	vr = eval("document."+nome_form+"."+campo+".value");
	tam = vr.length;
	if (tam > 0)
	{
       for (i = 0; i < tam ; i++) 
       {  
         ch = vr.substring(i,i + 1)
         if (ch>='0' && ch<='9') s = s + ch;
       }
       tam = s.length;
	   if (tam > 0)
       {
          for (i = 0; i < tam ; i++) 
          {  
              ch = s.substring(i,i + 1)
              if (ch>='0' && ch<='9') cp = cp + ch;
          }
	   }
        if (cp.length == 8)
        {
           cp=cp.substring(0,2) + cp.substring(2,4) + cp.substring(6,8);
        }
    }
  vr=cp;
  return vr;
}

function testainscricao(inscricao) 
{
  var c,total,x,digverificador;
  
  if ((inscricao.length != 9) || (Number(inscricao) == 0)) 
  {
    return false;
  }
  else
  {
    if ((inscricao > 204000000) || (inscricao < 200000000)) 
	{
      return false;
	}
    else
    {
	  total = 0;
      for (x = 9; x >= 2; x--)
	  {
        c = Number(inscricao.charAt(9 - x));
        total = c * x + total;
      }
      digverificador = (total * 10) % 11;
      if (digverificador == 10) digverificador = 0;
      return (digverificador == Number(inscricao.charAt(8)));
    }
  }
}

function TestaNum(nome_form,campo)
{
	var s = "";
	vr = eval("document."+nome_form+"."+campo+".value");
	tam = vr.length;
	if (tam > 0)
	{
       for (i = 0; i < tam ; i++) 
       {  
         ch = vr.substring(i,i + 1);
         if ((ch>='0' && ch<='9') || ch==',' || ch=='.') s = s + ch;
       }
       if (s.length < 1)
       {
         alert("Utilize apenas números no preenchimento deste campo."); 
         eval("document."+nome_form+"."+campo+".focus()"); 
       }
	}
    vr=s;
  return vr;
}
function VazioVar(campovar){
	var retVal = "";
	var start = 0;
	vlr = campovar;
	tam = campovar.length;
	while ((start < tam) && (vlr.charAt(start) == ' ')) {
	++start;
	}
	if (start < tam) {
       var end = tam;
	   while ((end > 0) && (vlr.charAt(end - 1) == ' ')) {
	   --end;
	   }
	}
	else
	{ var end = start;}
	retVal = vlr.substring(start, end);
    if (retVal == "") {return true} else {return false}
}

function Vazio(Form1,campo){
	var retVal = "";
	var start = 0;
	vlr = eval(Form1+"."+campo);
	tam = eval(Form1+"."+campo+".length");
	while ((start < tam) && (vlr.charAt(start) == ' ')) {
	++start;
	}
	if (start < tam) {
       var end = tam;
	   while ((end > 0) && (vlr.charAt(end - 1) == ' ')) {
	   --end;
	   }
	}
	else
	{ var end = start;}
	retVal = vlr.substring(start, end);
    if (retVal == "") {return true} else {return false}
}

function MudaFocus(tamanho, desfocado, focado)
{
	var nome = document.getElementById(desfocado).value;
	var tamanhoNome = nome.length;
	var comando = 'document.Form1.' + focado + '.focus()'; 
	if(tamanhoNome == tamanho)
	{
		eval(comando);		
	}
}

function AnulaEnter(campo, event)
{
	if(event.keyCode == 13)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function FormataValDin(Valor,Tecla)
{
    var browser = navigator.appName
    if(browser == "Microsoft Internet Explorer")
    {
        Codigo=Tecla.keyCode;
        Letra=String.fromCharCode(Codigo);
        retorno="";
        if (Valor.length>0)
        {
            for (i = 0; i < Valor.length ; i++) 
            {  
	            ch = Valor.charAt(i)
		        if (ch>="0" && ch<="9") retorno = retorno + ch;
		    }
        }
        while (retorno.length<3)
        {
          retorno ="0" + retorno;
        }
        if ((retorno.length>3) && (retorno.charAt(0)=="0")) retorno=retorno.substring(1,retorno.length)
        Copia= "," + retorno.substring(retorno.length-2,retorno.length);
        for (i=1;i<=retorno.length-2;i++)
        {
            Copia=retorno.charAt(retorno.length-i-2) + Copia ;
            if (((i % 3) == 0) && (i!=retorno.length-2)  )
            {
                Copia= "." + Copia;
            }
        }  
        retorno=Copia;
        return retorno;
     }
     else
     {
        return Valor;
     }
}

function FormataValDinMaisPreciso(Valor,Tecla)
{
    var browser = navigator.appName
    if(browser == "Microsoft Internet Explorer")
    {
        Codigo=Tecla.keyCode;
        Letra=String.fromCharCode(Codigo);
        retorno="";
        if (Valor.length>0)
        {
            for (i = 0; i < Valor.length ; i++) 
            {  
	            ch = Valor.charAt(i)
		        if (ch>="0" && ch<="9") retorno = retorno + ch;
		    }
        }
        while (retorno.length<6)
        {
          retorno ="0" + retorno;
        }
        if ((retorno.length>4) && (retorno.charAt(0)=="0")) retorno=retorno.substring(1,retorno.length)
        Copia= "," + retorno.substring(retorno.length-4,retorno.length);
        for (i=1;i<=retorno.length-4;i++)
        {
            Copia=retorno.charAt(retorno.length-i-4) + Copia ;
            if (((i % 3) == 0) && (i!=retorno.length-4)  )
            {
                Copia= "." + Copia;
            }
        }  
        retorno=Copia;
        return retorno;
     }
     else
     {
        return Valor;
     }
}


  
<!--
function FormataValor(campo,teclapres) {
	var tecla = teclapres.keyCode;
	vr = document.Form1[campo].value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
tam = vr.length + 1
//	tam = vr.length;

//	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){	tam = tam - 1 ; }
		
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){ 
	 		document.Form1[campo].value = vr ; }
	 	if ( (tam > 2) && (tam <= 5) ){
	 		document.Form1[campo].value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		document.Form1[campo].value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		document.Form1[campo].value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 12) && (tam <= 14) ){
	 		document.Form1[campo].value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		document.Form1[campo].value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;}
	}
		
/*	for (var ct = 0; ct < document.form.elements.length; ct++) {
		if (document.form.elements[ct].name == document.form.elements[campo].name) {
			if ( !teclapres.shiftKey && tecla == 9 && document.form.elements[ct+1] && document.form.elements[ct+1].name == "senhaConta" && document.applets['tclJava'] ){
				document.applets['tclJava'].setFocus();
			}	
		}
	}
*/
}

function SaltaCampo (campo,teclapres){
	var tecla = teclapres.keyCode;
	vr = document.Form1[campo].value;

	if( tecla == 109 || tecla == 188 || tecla == 110 || tecla == 111 || tecla == 223 || tecla == 108 ){
		document.Form1[campo].value = vr.substr( 0, vr.length - 1 ); }
	else{
	 	vr = vr.replace( "-", "" );
	 	vr = vr.replace( "/", "" );
	 	vr = vr.replace( "/", "" );
	 	vr = vr.replace( ",", "" );
	 	vr = vr.replace( ".", "" );
	 	vr = vr.replace( ".", "" );
	 	vr = vr.replace( ".", "" );
	 	vr = vr.replace( ".", "" );
	 	tam = vr.length;	
	}
}

function FormataDado(campo,tammax,pos,teclapres){
	var tecla = teclapres.keyCode;
	vr = document.Form1[campo].value;
	vr = vr.replace( "-", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length ;

	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){ tam = tam - 1 ; }
			
	if ( tecla == 8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){
	 		document.Form1[campo].value = vr ;}
		if ( tam > pos && tam <= tammax ){
			document.Form1[campo].value = vr.substr( 0, tam - pos ) + '-' + vr.substr( tam - pos, tam );}
	}
}

function FormataCpf(campo,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = document.Form1[campo].value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	tam = vr.length;

	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){	tam = tam - 1 ; }
		
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){ 
	 		document.Form1[campo].value = vr ; }
	 	if ( (tam > 2) && (tam <= 5) ){
	 		document.Form1[campo].value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		document.Form1[campo].value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		document.Form1[campo].value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 12) && (tam <= 14) ){
	 		document.Form1[campo].value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		document.Form1[campo].value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ;}
	}		
}

  function calcula1(campo3, campo4, campo5, campo6, campo7)
  {
	var vCampo3 = document.getElementById(campo3).value;//.replace(',','.');
	array3 = vCampo3.split(",");
	valor3 = array3[0].replace('.','');
	centavos3 = array3[1];
	if(valor3 == null || valor3 == "")
	{
		valor3 = 0;
	}
	if(centavos3 == null || centavos3 == "")
	{
		centavos3 = 0;
	} 
	var vCampo4 = document.getElementById(campo4).value;//.replace(',','.');
	array4 = vCampo4.split(",");
	valor4 = array4[0].replace('.','');
	centavos4 = array4[1];
	if(valor4 == null || valor4 == "")
	{
		valor4 = 0;
	}
	if(centavos4 == null || centavos4 == "")
	{
		centavos4 = 0;
	}
	var vCampo5 = document.getElementById(campo5).value;//.replace(',','.');
	array5 = vCampo5.split(",");
	valor5 = array5[0].replace('.','');
	centavos5 = array5[1];
	if(valor5 == null || valor5 == "")
	{
		valor5 = 0;
	}
	if(centavos5 == null || centavos5 == "")
	{
		centavos5 = 0;
	}
	var vCampo6 = document.getElementById(campo6).value;//.replace(',','.');
	array6 = vCampo6.split(",");
	valor6 = array6[0].replace('.','');
	centavos6 = array6[1];
	if(valor6 == null || valor6 == "")
	{
		valor6 = 0;
	}
	if(centavos6 == null || centavos6 == "")
	{
		centavos6 = 0;
	}
	var vCampo7 = document.getElementById(campo7).value;//.replace(',','.');
	array7 = vCampo7.split(",");
	valor7 = array7[0].replace('.','');
	centavos7 = array7[1]; 
	if(valor7 == null || valor7 == "")
	{
		valor7 = 0;
	}
	if(centavos7 == null || centavos7 == "")
	{
		centavos7 = 0;
	}
	totalValor = parseFloat(valor3) + parseFloat(valor4) + parseFloat(valor5) + parseFloat(valor6) + parseFloat(valor7);
	totalCentavos = parseFloat(centavos3) + parseFloat(centavos4) + parseFloat(centavos5) + parseFloat(centavos6) + parseFloat(centavos7);
	resultado = parseFloat(totalValor)+parseFloat(totalCentavos/100);
	document.Form1.calcular1.value = parseFloat(totalValor) + parseFloat(totalCentavos);
}

//FCBSIA-----------------------------

	  function AbreJanela(pagina,nome)
	  {
		window.open(pagina,nome,'scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,width=400,height=200,top=' + (screen.height-200)/2 + ',left=' + (screen.width-400)/2);
	  }


	//******************************Guias
function verificaAgencia()
{
	var primeiro = 0;
	var para = 0;
	var recebeValor = new Array(2);
	var agencia;
	var i = 0;
	var valor = "";
	
	while(i < Form1.elements.length && para == 0)
	{
		var elemento = Form1.elements[i];
		
		if(elemento.type == "checkbox" && primeiro == 0 && elemento.checked)
		{
			recebeValor = elemento.value.split("//");
			agencia = recebeValor[0];
			primeiro = 1;
			valor += recebeValor[1] + ",";
		}
		else if(elemento.type == "checkbox" && elemento.checked)
		{
			recebeValor = elemento.value.split("//");
			agencia2 = recebeValor[0];
			if(agencia2 != agencia)
			{
				para = 1;
				valor = 0;
			}
			else
			{
				valor += recebeValor[1] + ",";
			}
		}
		i++;
	}
	document.getElementById("valorFcbGerado").value = valor;
}

function VerificaData(DataVencimento, DataVencimento2)
{
	  DataPassada = new Date(DataVencimento);

	  var AnoPassado = DataPassada.getFullYear();
	  var MesPassado = DataPassada.getMonth() + 1;
	  var DiaPassado = DataPassada.getDate();

	  DataGravada = new Date(DataVencimento2);
	  var AnoGravado = DataGravada.getFullYear();
	  var MesGravado = DataGravada.getMonth() + 1;
	  var DiaGravado = DataGravada.getDate();

	  var grava = 0;

	  if (AnoPassado < AnoGravado)
	  {
	    grava = 1;
	  }
	  else
	  {
	    if (AnoPassado == AnoGravado)
		{
		  if (MesPassado < MesGravado)
		  {
		    grava = 1;
		  }
		  else
		  {
		    if ((MesPassado == MesGravado) && (DiaPassado <= DiaGravado))
			{
			  grava = 1;
			}
		  }
		}
	  }
	  
	  
	  if (grava == 1)
	  {
		 Form1.jsDataVencimento.value =  MesPassado + "/" + DiaPassado + "/" + AnoPassado;		 
	     Form1.txtDataVencimento.value = DiaPassado + "/" + MesPassado + "/" + AnoPassado;
		 document.all.txtDataVencimento.innerHTML = DiaPassado + "/" + MesPassado + "/" + AnoPassado;
	  }
	  else
	  {
		 Form1.jsDataVencimento.value =  MesGravado + "/" + DiaGravado + "/" + AnoGravado;
	     Form1.txtDataVencimento.value = DiaGravado + "/" + MesGravado + "/" + AnoGravado;
		 document.all.txtDataVencimento.innerHTML = DiaGravado + "/" + MesGravado + "/" + AnoGravado;
	  }
	  

}

function Formata()
{
     var data = document.Form1.txtDataVencimento.value;
	 if ((data.length == 2) || (data.length == 5))
	     document.Form1.txtDataVencimento.value = document.Form1.txtDataVencimento.value + "/";
     return true;
	 
}    

function ChecaCampos()
{
      var cont=0;
      for (var i=0;i<Form1.elements.length;i++)
      {
         var todos = Form1.elements[i];
		 var flag =1;
         if (todos.type == "checkbox" && todos.checked)
		 {
		   cont++;
		 }	
      }
	  if (cont == 0)
	  {
	    alert("Selecione pelo menos um debito para gerar a guia.");
	    return false;
	  }
	  return true;

}

function passaMeuTamanho(tamanho)
{
	parent.document.getElementById("Tamanho").value = tamanho;
}

function mudaCor(referencia, cor, outra)
{
	if(cor == 1)
	{
		referencia.style.backgroundColor = '#E1EFFF';
		outra.style.backgroundColor = '#E1EFFF';
	}
	else
	{
		referencia.style.backgroundColor = '#FFFFFF';
		outra.style.backgroundColor = '#FFFFFF';
	}
}

function impressao(tabela)
{
	var comando = "document.all."+tabela+".class='tabelaImpressao';";
	eval(comando);
	tabela.style.border = '1px';
}

function passaAltParaCima(objeto)
{
	parent.document.getElementById("Ajuda").innerHTML = objeto.alt;
}

function tdAjuda(objeto)
{
	
	parent.document.getElementById("tdAjuda").innerHTML = "<img src='imagens/abaixoMenu1Troc.jpg' id='imagenAtencao' height='52' width='212' border='0' name='abaixoMenu_r2_c1'/><div id='Ajuda' style='position:absolute; width:602px; height:47px; z-index:2; left: 165px; top: 95px; overflow: auto; scrollbar-arrow-color: #31659C; scrollbar-face-color: #ffffff; scrollbar-highlight-color: #ffffff;' class='textoFormulario'>"+objeto.value+"</div>";
}

function tamanhoIframe(tamanho)
{
	parent.document.getElementById("corpo").height = tamanho;
}

function load()
{
	if (form.txtDocumento.value == "")
	{
		form.txtDocumento.value = opener.form.txtDocumento.value;
	}
	form.txtDocumento.focus();
}
	   
function Mensagem(texto)
{
	form.document.all.textResp.innerHTML = "";
	form.document.all.texto.innerHTML = texto;
}

function submeter(numTadf)
{
	if (numTadf>500)
    {
      var msg='Pressione o OK para iniciar o c&aacute;lculo de ' + numTadf + ' d&eacute;bito(s)';
      //minutos=Math.round(NT/1000);
      //if (minutos>1) msg+=unescape('%0A') + 'Esta operação poderá estender-se por ' + minutos + ' minutos.';
      alert(msg);
    }
}

// Adiciona o site aos favoritos. Recebe como parâmetro o titulo e a url
function adicionarFavoritos(titulo,url){
    var title=titulo;
    var url=url;

    if (window.sidebar) window.sidebar.addPanel(title, url,"");

    else if( window.opera && window.print )
    {
    var mbm = document.createElement('a');
    mbm.setAttribute('rel','sidebar');
    mbm.setAttribute('href',url);
    mbm.setAttribute('title',title);
    mbm.click();
    }

    else if( document.all ) window.external.AddFavorite( url, title);

}

//Função que rotaciona a figura central da página. Para acrescentar uma nova figura, basta adicionar mais um
//indice no array e acrescentar um a mais no multiplicador.
function rotacionaFigura()
{
    var ran = Math.random();
    var figuras = new Array("imagens/imgRotativa.jpg","imagens/postoFiscal.jpg","imagens/postoFiscal4.jpg");
    //Econtra o valor aleatório de 0 a 2... quando multiplicamos o random por 3.
    var multiplicador = 3;
    var numeroEncontrado = parseInt(multiplicador*ran);
    //Pegando o valor pelo indice do array
    var figuraEncontrada = figuras[numeroEncontrado];
    //Escrevendo a figura no div especificado.
    document.getElementById("corpoEsquerdaPart2").innerHTML = "<img src='" + figuraEncontrada + "' alt='Seja Bem Vindo' style='width: 344px; height:130px;'/>";
}

//Função disparada no momento do clique nos menus de primeiro nível do menu lateral
//Importante saber que avariável menu deverá ter o mesmo nome do div que receberá a estrutura.
function abreFechaMenuLateral(menu)
{
    //Estrutura montada para o submenu.
    var estrutura = "";
    
    //Comando que será escrito dinamicamente para contruir o menu.
    var comando = "";
    
    //Variável para saber o conteudo atual do div. Informa se devemos apagá-lo ou construí-lo.
    var conteudo = "";
    
    /*Verificando o browser. O problema é que no IE, mesmo apagando todo conteúdo do div, ele ainda está ocupando o espaço.
    e acaba não incolhendo o menu lateral de forma adequada.*/
    var browser = navigator.appName
    
    //Pegando o conteúdo do div.
    conteudo = document.getElementById(menu).innerHTML;
           
    if(menu == "CN")
    {
        if(conteudo == "")
        {
            estrutura = "<div class='celulaInterna'><a class='linkCelulaInterna' href=''>Pessoa Física</a></div>";
            estrutura +="<div class='celulaInterna'><a class='linkCelulaInterna' href=''>Pessoa Jurídica</a></div>";
            estrutura +="<div class='celulaInterna'><a class='linkCelulaInterna' href=''>Reimprimir ou Verificar</a></div>";
            //Modificando o texto do chamador. Retirando o + e colocando o menos, ou vice-versa.
            document.getElementById("CN1").innerHTML = "[-] Certidão Negativa";
            if(browser == "Microsoft Internet Explorer")
            {
                document.getElementById(menu).style.height = "auto";
            }
            
        }
        else
        {
            if(browser == "Microsoft Internet Explorer")
            {
                document.getElementById(menu).style.height = "0px";
            }
            //Modificando o texto do chamador. Retirando o + e colocando o menos, ou vice-versa.
            document.getElementById("CN1").innerHTML = "[+] Certidão Negativa";
            
        }
    }
    else
    {
        if(menu == "PG")
        {
            if(conteudo == "")
            {
                estrutura = "<div class='celulaInterna'><a class='linkCelulaInterna' href='SelecaoPagamento.aspx?debito=cresce'>Cresce/RN</a></div>";
                estrutura += "<div class='celulaInterna'><a class='linkCelulaInterna' href='SelecaoPagamento.aspx?debito=gim'>Débitos da GIM</a></div>";
                estrutura += "<div class='celulaInterna'><a class='linkCelulaInterna' href='SelecaoPagamento.aspx?debito=fecop'>FECOP</a></div>";
                estrutura += "<div class='celulaInterna'><a class='linkCelulaInterna' href='SelecaoPagamento.aspx?debito=icms'>ICMS Antecipado</a></div>";
                estrutura += "<div class='celulaInterna'><a class='linkCelulaInterna' href='SelecaoPagamento.aspx?debito=parcelamento'>Parcelamento</a></div>";
                estrutura += "<div class='celulaInterna'><a class='linkCelulaInterna' href='SelecaoPagamento.aspx?debito=transportadora'>Transportadora</a></div>";
                //Modificando o texto do chamador. Retirando o + e colocando o menos, ou vice-versa.
                document.getElementById("PG1").innerHTML = "[-] Pagamentos";
                if(browser == "Microsoft Internet Explorer")
                {
                    document.getElementById(menu).style.height = "auto";
                }
            }
            else
            {
                if(browser == "Microsoft Internet Explorer")
                {
                    document.getElementById(menu).style.height = "0px";
                }
                //Modificando o texto do chamador. Retirando o + e colocando o menos, ou vice-versa.
                document.getElementById("PG1").innerHTML = "[+] Pagamentos";
            }
        }
    }
    
    //Atribui a estrutura ao div. Se ele estiver vazio, controi o menu, caso contrário, apaga.
    document.getElementById(menu).innerHTML = estrutura;
    
    
    
}

// Rotinas da pagina inicial
function MostrarFrase() 
{ 
    alert('ok');
    var i,p,v,obj,args=MostrarFrase.arguments;
    for (i=0; i<(args.length-2); i+=3) 
    {
        if ((obj=MM_findObj(args[i]))!=null) 
        { 
            v=args[i+2];
            if (obj.style) 
            { 
                obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; 
            }
            obj.visibility=v; 
        }
    }
}

//Tempo de alteração da mensagem (em milisegundos)
var delay=5000;
var fcontent=new Array();
begintag='<font>'; 
fcontent[0]="<a href='index.aspx' class='TextoRotativo'>» A UVT (Unidade Virtual de Tributação) tem no seu objetivo principal unir e facilitar algumas das obrigações do contribuinte. Saiba mais sobre a <b>UVT</b> clicando aqui.</a>";
fcontent[1]="<a href='index.aspx' class='TextoRotativo'>» Em breve, a SET/RN, através da CODIN, estará unificando o uso de senhas para os serviços via internet. O acesso aos serviços on-line da SET/RN será realizado utilizando-se <b>EXCLUSIVAMENTE</b> o código de usuário e senha do SIGAT...</a>";
fcontent[2]="<a href='index.aspx' class='TextoRotativo'>» Solicitamos àqueles usuarios que não tenham senha no SIGAT, que providenciem seu cadastramento clicando aqui. Mais informações e dúvidas quanto a este procedimento, ligar para os telefones (84)3232-2017/2018 ou pelo e-mail sigat@lista.set.rn.gov.br</a>";
closetag='</font>';

var fadescheme=0;
var fadelinks=1;

var hex=(fadescheme==0)? 255 : 0;
var startcolor=(fadescheme==0)? "rgb(239,240,241)" : "rgb(0,0,0)";
var endcolor=(fadescheme==0)? "rgb(0,0,0)" : "rgb(239,240,241)";

var ie4=document.all&&!document.getElementById;
var ns4=document.layers;
var DOM2=document.getElementById;
var faderdelay=0;
var index=0;
var frame=20;

if (DOM2)
{
    faderdelay=2000;
}

//função para modificar o conteudo
function modificarConteudo()
{
    if (index>=fcontent.length)
    {
        index=0;
    }
    if (DOM2)
    {
        document.getElementById("abaixoMenuPart2").style.color=startcolor;
        document.getElementById("abaixoMenuPart2").innerHTML=begintag+fcontent[index]+closetag;
        linksobj=document.getElementById("abaixoMenuPart2").getElementsByTagName("A");
        if (fadelinks)
        {
            ModificarCorLink(linksobj);
        }
        SuavizarCor();
    }
    else if (ie4)
    {
        document.all.abaixoMenuPart2.innerHTML=begintag+fcontent[index]+closetag;
    }
    else if (ns4)
    {
        document.abaixoMenuPart2ns.document.abaixoMenuPart2ns_sub.document.write(begintag+fcontent[index]+closetag);
        document.abaixoMenuPart2ns.document.abaixoMenuPart2ns_sub.document.close();
    }
    index++;
    setTimeout("modificarConteudo()",delay+faderdelay);
}

function ModificarCorLink(obj)
{
    if (obj.length>0)
    {
        for (i=0;i<obj.length;i++)
        {
            obj[i].style.color="rgb("+hex+","+hex+","+hex+")";
        }
    }
}


function SuavizarCor() 
{
    if(frame>0) 
    {
        hex=(fadescheme==0)? hex-12 : hex+12;
        document.getElementById("abaixoMenuPart2").style.color="rgb("+hex+","+hex+","+hex+")"; 
        if (fadelinks)
            ModificarCorLink(linksobj);
        frame--;
        setTimeout("SuavizarCor()",20);
    }
    else
    {
        document.getElementById("abaixoMenuPart2").style.color=endcolor;
        frame=20;
        hex=(fadescheme==0)? 255 : 0
    }
}
/*
* Fim da Estrutura de script que rotaciona as frases no menu superior.
*
*
*/
function posicionaMenu(menu, overout, idObj)
{
    /*-- Verifica se a chamada é proveniente do div ou de alguma imagem.
    O menu nulo caracteriza a chamada de um div, caso contrário, será uma figura.
    Isso porque, se o div chamar a função, não é preciso reposicionar ele,
    só defini-lo como visível ou invisível. Caso a figura faça essa chamada,
    o reposicionamento é necessário.
    */
    if(menu != "")
    {
        var situacao = document.getElementById(idObj).style.visibility;
        var browser = navigator.appName
        var topo = "0px";
        var esquerda ="0px";
        var altura = "120px";
        var largura = "130px";
        var conteudo = "";
        
        //-- Muitos desses estão temporáriamente retornando nulo. Até que seja realmente definido o menu.
        if(menu == "HOME" || menu == "SAC" || menu == "ICMS" || menu == "IPVA" || menu == "ITCD" || menu == "OUVIDORIA")
        {
            return;
        }
        
        if(menu == "ICMS")
        {
            topo = "88px";
            esquerda = "56px";
        }
        if(menu == "IPVA")
        {
            topo = "88px";
            esquerda = "112px";
        }
        if(menu == "ITCD")
        {
            topo = "88px";
            esquerda = "163px";
        }
        if(menu == "FCB")
        {
            topo = "90px";
            esquerda = "167px";
            altura = (browser == "Microsoft Internet Explorer") ? "125px" : "90px";
            //conteudo = "<ul class='ListaMenuUL'>";
            conteudo += "<!--li><a href='SelecaoPagamento.aspx?debito=alcool' class='LinkMenuNovo'>Álcool Etílico</a></li-->";
            conteudo += "<li><a href='SelecaoPagamento.aspx?debito=icms' class='LinkMenuNovo'>icms antecipado</a></li>";
            conteudo += "<li><a href='SelecaoPagamento.aspx?debito=gim' class='LinkMenuNovo'>Débitos da GIM</a></li>";
            conteudo += "<li><a href='SelecaoPagamento.aspx?debito=parcelamento' class='LinkMenuNovo'>parcelamento</a></li>";
            conteudo += "<li><a href='SelecaoPagamento.aspx?debito=cresce' class='LinkMenuNovo'>cresce/rn</a></li>";
            conteudo += "<li><a href='SelecaoPagamento.aspx?debito=fecop' class='LinkMenuNovo'>fecop</a></li>";
            //conteudo += "</ul>";
        }
        if(menu == "OUVIDORIA")
        {
            topo = "88px";
            esquerda = "268px";
        }
        //-- Se for onmouseOver, mostre o menu, caso contrário deixe-o invisivel.
        document.getElementById(idObj).style.visibility = (overout == "OVER") ? "visible" : "hidden";
        //if (overout == "OVER") { 
        //    document.getElementById(idObj).style.visibility = "visible";
        //} else {
        //    setTimeout('oculta_objeto(\''+idObj+'\')', 500);
        //}
        
        //--- Definição da localização do div de submenu. Aqui o div ficará logo abaixo do menu chamador.
        document.getElementById(idObj).style.top = topo;
        document.getElementById(idObj).style.left = esquerda;
        //--- Fim da definição de localização
        
        //--- Definição o tamanho do div
        document.getElementById(idObj).style.width = largura;
        document.getElementById(idObj).style.height = altura;
        //--- Fim da definição do tamanho
        
        //-- Definição do conteúdo do div, ou seja, os links que compõe a estutura.
        document.getElementById(idObj).innerHTML = conteudo;
        //--- Fim da definição dos links
    }
    else
    {
        document.getElementById(idObj).style.visibility = (overout == "OVER") ? "visible" : "hidden";
    }
}    

function oculta_objeto(idObj){
    document.getElementById(idObj).style.visibility = "hidden";
}


function MM_findObj(n, d) 
{ 
    var p,i,x;  
    if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) 
    {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
    }
    if(!(x=d[n])&&d.all) x=d.all[n]; 
    for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
    if(!x && d.getElementById) x=d.getElementById(n); 
    return x;
}

function MM_swapImage() 
{ 
    var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; 
    for(i=0;i<(a.length-2);i+=3)
    if ((x=MM_findObj(a[i]))!=null)
    {
        document.MM_sr[j++]=x; 
        if(!x.oSrc) 
            x.oSrc=x.src; 
        x.src=a[i+2];
    }
}

function MM_preloadImages() 
{ 
    var d=document; 
    if(d.images)
    { 
        if(!d.MM_p) d.MM_p=new Array();
        var i,j=d.MM_p.length,a=MM_preloadImages.arguments; 
        for(i=0; i<a.length; i++)
        if (a[i].indexOf("#")!=0)
        { 
            d.MM_p[j]=new Image; 
            d.MM_p[j++].src=a[i];
        }
    }
}

function ControlaCampoCalendario(campo)
{
    campo.click();
}

function mostrar_ocultar(idObj){
    var obj = document.getElementById(idObj);
    obj.style.display = (obj.style.display=='block' || obj.style.display=='') ? 'none' : 'block';
}

function mostrar(idObj){
    var obj = document.getElementById(idObj);
    obj.style.display = 'block';
}

function ocultar(idObj){
    var obj = document.getElementById(idObj);
    obj.style.display = 'none';
}


//Aqui tem que fomatar o valor do campo. Não poderá conter vírgula, deverá ser de acordo com o formato americano.
/*
function Somar(valor, campoCheck, campoTotal)
{
    
    for (var i = 0; i < document.aspnetForm.elements.length; i++) 
    {
        if (document.aspnetForm.elements[i].type=="checkbox") 
        {
            if(document.aspnetForm.elements[i].value == campoCheck.value)        
                document.aspnetForm.elements[i].checked = campoCheck.checked;
        }
    }
    
    //alert(campoCheck.value);
    //alert(campoCheck.checked);
    
    var total = parseFloat(valorBanco(campoTotal.value));
    var valorMomento = parseFloat(valor);
    
    var resultado;
    
    if(campoCheck.checked)
    {
        resultado = total + valorMomento;
    }
    else
    {
        resultado = total - valorMomento;
    }
    
    var resultadoFormatado = arredondar(resultado,2);
    
    var mostrarResultado = valorBrasileiro(resultadoFormatado.toString());
    
    campoTotal.value =  mostrarResultado;
}
*/

function Somar(campoCheck)
{
    var sqOrigemDebito = ""; 
    var valor = 0; 
    var valorTotal = 0;
    var sqOrigemDebitoCampoClicado = campoCheck.value.split('-')[0];
    var valorCampoClicado = parseFloat(valorBanco(campoCheck.value.split('-')[1]));
    var totalInicial = parseFloat(valorBanco(document.getElementById("ctl00_frameCorpo_hdfTotal").value));
    
    for (var i = 0; i < document.aspnetForm.elements.length; i++) 
    {
        if (document.aspnetForm.elements[i].type=="checkbox") 
        {
            if(document.aspnetForm.elements[i].value != "0")
            {
                sqOrigemDebito = document.aspnetForm.elements[i].value.split('-')[0];
                valor = parseFloat(valorBanco(document.aspnetForm.elements[i].value.split('-')[1]));
                
                if(sqOrigemDebito == sqOrigemDebitoCampoClicado)  
                {      
                    document.aspnetForm.elements[i].checked = campoCheck.checked;
                }
            }
            
            if(document.aspnetForm.elements[i].checked)
            {
                valorTotal += valor;
            }
        }
    }
    
    if(valorTotal <= 0)
    {
        document.getElementById("ctl00_frameCorpo_ckbTodos").checked = false;
    }
    else
    {
        if(valorTotal == totalInicial)
        {
            document.getElementById("ctl00_frameCorpo_ckbTodos").checked = true;
        }
    }
    
    document.getElementById("ctl00_frameCorpo_txtTotal").value = valorBrasileiro(valorTotal.toString());
    
}


function valorBanco(valor)
  {
   var inteiro = valor.split(',')[0];
   var centavos = "";
   try
   {
    centavos = valor.split(',')[1];
   }
   catch(err)
   {
    centavos = "00";
   }
   var charCorrente = "";
   var saidaInteira = "";
   for(var i = 0; i < inteiro.length; i++)
   {
    charCorrente = inteiro.substr(i, 1);
    if(charCorrente != ".")
     saidaInteira += charCorrente;
   }
   return saidaInteira + "." + centavos;
  }


  function valorBrasileiro(valor)
  {
   var inteiro = valor.split('.')[0];
   
   var centavos = "";
   try
   {
    centavos = valor.split('.')[1];
     if(centavos.Length==1)
     {
        centavos += "0";
     }
   }
   catch(err)
   {
    centavos = "00";
   }
   if(inteiro.Length<=3)
   {
    return inteiro + "," + centavos.substr(0,2);
   }
   var cont = 0;
   var saidaInvertido = "";
   for(var i = inteiro.length -1; i>=0; i--)
   {
    saidaInvertido += inteiro.substr(i,1);
    cont ++;
    if(cont%3==0 && i!=0)
    {
     saidaInvertido+=".";
    }
   }
   var saida = "";
   for(var i = saidaInvertido.length -1; i>=0; i--)
   {
    saida += saidaInvertido.substr(i, 1);
   }
   
   try
   {
        if(centavos.length == 1)
        {
            centavos += "0";
        }
        else
        {
            if(centavos.length > 2)
            {
                centavos = centavos.substr(0,2);
            }
        }
        return saida + "," + centavos;
   }
   catch(err)
   {
        return saida + ",00";
   }
  
  }

  function arredondar(x, n)
  {
     try
     {
        if (n < 0 || n > 10) return x;
        var pow10 = Math.pow (10, n);
        var y = x * pow10;
        return Math.round (y) / pow10; 
     }
     catch(err)
     {
        return 0;
     }
  }
  
  function mostraPagamento(opcao, divEsconder)
  {
        if(opcao == "D")
            document.getElementById(divEsconder).style.display = "block";
        else
            document.getElementById(divEsconder).style.display = "none";
  }
  
  function mostraTipoPessoa(opcao, divEsconder, lblTipoPessoa, rbPessoaFisica, txtidentificador)
  {
        if(opcao == "NaoCont")
        {
            document.getElementById(divEsconder).style.display = "block";
            if(document.getElementById(rbPessoaFisica).checked)
            {
                document.getElementById(lblTipoPessoa).innerHTML = "CPF";
                document.getElementById(txtidentificador).maxLength = 11;
            }
            else
            {
                document.getElementById(lblTipoPessoa).innerHTML = "CNPJ";
                document.getElementById(txtidentificador).maxLength = 14;
            }
        }
        else
        {
            document.getElementById(divEsconder).style.display = "none";
            document.getElementById(lblTipoPessoa).innerHTML = "Inscrição Estadual";
            document.getElementById(txtidentificador).maxLength = 10;
        }
        document.getElementById(txtidentificador).value = "";
  }
  
   function defineCampo(tipoPessoa, lblPessoa, txtidentificador)
   {
        if(tipoPessoa == "PF")
        {
            document.getElementById(lblPessoa).innerHTML = "CPF";
            document.getElementById(txtidentificador).maxLength = 11;
        }
        else
        {
            document.getElementById(lblPessoa).innerHTML = "CNPJ";
            document.getElementById(txtidentificador).maxLength = 14;
        }
        document.getElementById(txtidentificador).value = "";
   }
    
  function EnviarSonda()
  {
        document.getElementById('sonda').submit();
  }
  
  function informa(divEsconder, nomeEvento)
  {
        if(nomeEvento == "OVER")
            document.getElementById(divEsconder).style.display = "block";
        else
            document.getElementById(divEsconder).style.display = "none";
  }
  
 function adiciona_informacoes(){
    
 }
 
 function valida_ipva() {
    var placa   = document.getElementById('ctl00_frameCorpo_ipva_placa');
    var renavam = document.getElementById('ctl00_frameCorpo_ipva_renavam');
    
    if ( (placa.value == '') || (renavam.value == '')) 
    {
        alert('Você precisa informar a Placa e o Renavam.');
        return false;
    } 
    else 
    {
        document.location.href = "http://www.detran.rn.gov.br/servicos/consultaveiculo.asp?placa="+ placa.value +"&renavam="+renavam.value;
    }
    return false;
 }
 
 function submeter_bb(){
    var chkLido = document.getElementById("li_entendi").checked
    return (chkLido) ? carrega_bb() : mostra_aviso_bb();
 }
 
 function mostra_aviso_bb(){
    var chkLido = document.getElementById("li_entendi").checked
    var confirmacao = document.getElementById("confirmar_leitura")
    if (!chkLido)
        alert('Você precisa informar que leu e entendeu os dados contidos nesta página.');
    document.getElementById("pagamento").style.display = "block";
    document.getElementById("carregando").style.display = "none";
    return (chkLido) ? (confirmacao.style.display = "none") : (confirmacao.style.display = "block")  ;
 }
  
 function carrega_bb (){
    document.getElementById("pagamento").style.display = "none";
    document.getElementById("carregando").style.display = "block";
    document.getElementById("pagamento").submit();
 }
 
 /**************************************************************
 Trecho adiciona para ser usado pela página debitosagrupados.aspx
 ***************************************************************/
 function submeterBB(){
    var chkLido = document.getElementById("li_entendi").checked
    return (chkLido) ? carregarBB() : mostrarAvisoBB();
 }
 
 function mostrarAvisoBB(){
    var chkLido = document.getElementById("li_entendi").checked
    var confirmacao = document.getElementById("confirmar_leitura")
    if (!chkLido)
        alert('Você precisa informar que leu e entendeu os dados contidos nesta página.');
    document.getElementById("pagamento").style.display = "block";
    document.getElementById("carregando").style.display = "none";
    return (chkLido) ? (confirmacao.style.display = "none") : (confirmacao.style.display = "block")  ;
 }
  
 function carregarBB (){
    document.getElementById("carregando").style.display = "block";
    document.getElementById("pagamento").submit();
 }
 /******************************************************************/
 
//------------------------------------------------------------------------------------------------------ 
function IE(){ return navigator.appName.indexOf('Internet') >= 0; }
 
//------------------------------------------------------------------------------------------------------
function ApenasNumDec(Obj, casas, tam, aEvent)
{
    var Numero = Obj.value;
    var NumeroInt, NumeroDec;
    var intKeyCode = aEvent.keyCode ? aEvent.keyCode : aEvent.which ? aEvent.which : aEvent.charCode;
    
    //Se for TAB
    if(intKeyCode == 9){ return false; }

    //Limita o tamanho de caracteres do número.
    if(Numero.length >= tam){        
        if(IE()){ aEvent.returnValue = false; }
        else{ aEvent.stopPropagation(); aEvent.preventDefault();}
        return(false);
    }

    //Só permite a digitação dessas teclas.
    if( (intKeyCode < 48 || intKeyCode > 57) && (intKeyCode == 8) && (intKeyCode == 9) && (intKeyCode == 46)) {
        if(IE()){ aEvent.returnValue = false; }
        else{ aEvent.stopPropagation(); aEvent.preventDefault();}
        return(false);   
    } 

    //Retira a vírgula.
    var rVg      
    rVg = Numero.replace(",", "");
    Numero = rVg;

    //Retira o ponto.
    var NumeroSemPonto = Numero.split(".");
    if(NumeroSemPonto[0] != "")
    {
        Numero = "";
        for(i = 0; i <= NumeroSemPonto.length - 1; i++)
            Numero = Numero + NumeroSemPonto[i];
        }

    //Caso o número não contenha parte inteira são acrescentados
    //zeros à esquerda.
    if(Numero.length < casas)
    {
        var zeros = "";
        for(i = 0; i < casas - Numero.length; i++){
            zeros += "0";
        }
        Numero = zeros + Numero;	
    }

    //Se o número tiver parte inteira e o primeiro número for '0'
    //o mesmo é desprezado.
    if((Numero.substring(0, 1) == "0") && (Numero.length > casas))
        NumeroInt = Numero.substring(1, Numero.length - (casas - 1));
    else
        //Caso possua parte inteira e o primeiro não for zero,
        //o primeiro número é considerado.
        NumeroInt = Numero.substring(0, Numero.length - (casas - 1));

    //Determina a parte decimal.
    NumeroDec = Numero.substring(Numero.length - (casas - 1), Numero.length);

    //Coloca o ponto na parte inteira.
    if(NumeroInt.length > 1){
        var NumeroIntAux = "";
        var vetorNum = new Array(NumeroInt.length - 1);
        for(i = 0; i < NumeroInt.length; i++){
            vetorNum[i] = NumeroInt.substring(i, i + 1);
        }
        var j = 0;
        for(i = NumeroInt.length - 1; i > -1; i--){
            if(j == 3){
                j = 1;
                NumeroIntAux = vetorNum[i] + "." + NumeroIntAux; 
            }
            else{
                NumeroIntAux = vetorNum[i] + NumeroIntAux 
                j++;
            }
        }
        NumeroInt = NumeroIntAux;
    }

    //Concatena a parte inteira com a parte decimal.
    Numero = NumeroInt + "," + NumeroDec;

    //Atribui o número ao objeto.
    Obj.value = Numero;
}

//------------------------------------------------------------------------------------------------------
function convertToFloat( stringNumber )
{
    if( stringNumber != "" )
	{  
		var strNum = '';
		for(i=0; i <= stringNumber.length - 1; i++) strNum += (stringNumber.charAt(i) == '.'? '': stringNumber.charAt(i));  
		strNum = strNum.replace(",", ".");
		return (isNaN(strNum))?0:parseFloat(strNum);					
	}
	else
	{
		return 0;
	}
}                

//---------------------------------------------------------------------------------------------------    
function formatNumber(num, dec, thou, pnt, curr1, curr2, n1, n2) 
{
    var x = Math.round(num * Math.pow(10,dec));
    if (x >= 0) n1 = n2 = '';
    var y = (''+Math.abs(x)).split('');
    var z = y.length - dec; 
    if (z<0) z--; 
    for(var i = z; i < 0; i++) 
        y.unshift('0');
    y.splice(z, 0, pnt); 
    while (z > 3)
    {
        z-=3; 
        y.splice(z,0,thou);
    }
    var r = curr1 + n1 + y.join('') + n2 + curr2;
    return r;
 }
 
 // ------------------------------------------------------------------------------------------------------
function MaskText(oObj, strMask, aEvent){

	var i;
	var strTexto = oObj.value;
	var intKeyCode = aEvent.keyCode ? aEvent.keyCode : aEvent.which ? aEvent.which : aEvent.charCode;
	
	//Se for TAB
	if(intKeyCode == 9){ return false; }

	for (i = strTexto.length; i <= strMask.length; i++){
		if (! (strMask.substr(i, 1) == "#" || strMask.substr(i, 1) == "A" || strMask.substr(i, 1) == "@")) {
			oObj.value += strMask.substr(i, 1);
		}
		else {
			break;
		}
	}
	
	//Se não for número nem o Backspace, <-, ->, Delete, para o evento e retorna false
	if (strMask.substr(i, 1) == "#") {

		if(!(intKeyCode >= 48 && intKeyCode <= 57) && intKeyCode == 8 && intKeyCode == 37 && intKeyCode == 39 && intKeyCode == 46) {
			if(IE()){ aEvent.returnValue = false; }
			else{ aEvent.stopPropagation(); aEvent.preventDefault();}
		}
		
	}

	//Se não for alfa nem o Backspace, <-, ->, Delete, para o evento e retorna false
	if (strMask.substr(i, 1) == "A") {
		
		if( intKeyCode >= 48 && intKeyCode <= 57 && intKeyCode == 8 && intKeyCode == 37 && intKeyCode == 39 && intKeyCode == 46) {
			if(IE()){ aEvent.returnValue = false; }
			else{ aEvent.stopPropagation(); aEvent.preventDefault();}			
		}
		
	}	
}

//----------------------------------------------------------------------
function ApenasNumero( obj, aEvent ){

	var strTexto = obj.value;
	var strAux = "";
	var intKeyCode = aEvent.keyCode ? aEvent.keyCode : aEvent.which ? aEvent.which : aEvent.charCode;
	
	//Se for TAB
    if(intKeyCode == 9){ return false; }

	for (i = 1; i <= strTexto.length; i++){
		if (! isNaN(strTexto.substr(i -1, 1))) {
			strAux += strTexto.substr(i -1, 1);
		}
	}
	//Se não for número nem o Backspace, <-, ->, Delete, para o evento e retorna false
	if( !(intKeyCode >= 48 && intKeyCode <= 57) && intKeyCode != 8 && intKeyCode != 37 && intKeyCode != 39 && intKeyCode != 46 ) {
		if(IE()){ aEvent.returnValue = false; }
        else{ aEvent.stopPropagation(); aEvent.preventDefault();}
	}
	obj.value = strAux;	
}

// --------------------------------------------------------------------
// Funcao utilizada para marcar todos os checks.


function checkAllBoxes(marcacao)
{
    for (var i = 0; i < document.aspnetForm.elements.length; i++) {
    if (document.aspnetForm.elements[i].type=="checkbox") {
      document.aspnetForm.elements[i].checked = marcacao;
    }
  }
  
  if(! marcacao)
  {
        document.getElementById("ctl00_frameCorpo_txtTotal").value = "0,00";
  }
  else
  {
        document.getElementById("ctl00_frameCorpo_txtTotal").value = document.getElementById("ctl00_frameCorpo_hdfTotal").value;
  }
}   

// --------------------------------------------------------------------

// --------------------------------------------------------------------
// Funcao utilizada em ConsultaContribuinte.aspx

function AjustaCampo(campo) {
    objCampo = document.getElementById("ctl00_frameCorpo_txtIdentificador");

    switch (campo) {
        case "IE":
            alteraTamanhoCampo(objCampo, "", 9, "72px");
            break;
        case "CF":
            alteraTamanhoCampo(objCampo, "", 11, "82px");
            break;
        case "CN":
            alteraTamanhoCampo(objCampo, "", 14, "100px");
            break;
        case "RS":
            alteraTamanhoCampo(objCampo, "", 60, "400px");
            break;
        default:
            return;
    }

    objCampo.focus();
}

function alteraTamanhoCampo(objCampo, valor, tamanhoMaximo, largura){
    try {
        if(objCampo.maxLength != tamanhoMaximo) {
            objCampo.value       = valor;
            objCampo.maxLength   = tamanhoMaximo;
            objCampo.style.width = largura;
        }
    } catch(e){
        //alert('DEBUG:' + e.description);
    }
}

function ajuda(texto){
    alert(texto);
}

function ajudaInscricaoEstadual(){
    ajuda('Identificador de 9 dígitos sem traços e pontos');
}

function ajudaCPF(){
    ajuda('Identificador de 11 dígitos sem traços e pontos.');
}

function ajudaCNPJ(){
    ajuda('Identificador de 14 dígitos sem traços e pontos.');
}

function ajudaRazaoSocial(){
    ajuda('Nome formal da mesma forma do cadastro no SIGAT');
}

/*- limitador de caracteres de um TextArea - */
function max(txarea) 
{ 
    total = 60; 
    tam = txarea.value.length;
    str=""; 
    str=str+tam; 
    document.getElementById("digitado").innerHTML = str; 
    document.getElementById("restante").innerHTML = total - str; 
        if (tam > total){ 
            aux = txarea.value; 
            txarea.value = aux.substring(0,total); 
            document.getElementById("digitado").innerHTML = total; 
            document.getElementById("restante").innerHTML = 0;
        } 
}


/*- Função que muda a cor de uma linha do GridView atraves da marcação de um CheckBox - */
function CorLinhaSelecionada(corChk, RowState)
{
    if (corChk.checked)
         corChk.parentElement.parentElement.style.backgroundColor='#fffbd6';
    else 
        corChk.parentElement.parentElement.style.backgroundColor='#ffffff';
        
       /* { 
           if (RowState=='0')
                  corChk.parentElement.parentElement.style.backgroundColor='#ffffff';
           else
                  corChk.parentElement.parentElement.style.backgroundColor='#ffaa63';
        } */

}

/* - Função que marca todos os CheckBox de um GridView - */
function SelecionaTodosChecks(spanChk){
   var oItem = spanChk.children;
   var theBox= (spanChk.type=="checkbox") ? 

        spanChk : spanChk.children.item[0];

   xState=theBox.checked;

   elm=theBox.form.elements;  

   for(i=0;i<elm.length;i++)

     if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)
     {
       if(elm[i].checked!=xState)
          elm[i].click();
     }
 }
