var xmlhttp = getXmlHttpRequest();
var strXPTO;

function getXmlHttpRequest() 
{
	if (window.XMLHttpRequest) 
	{
		return new XMLHttpRequest();
	} 
	else if (window.ActiveXObject) 
	{
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
}

function retornaAjax(strUrl,strDiv)
{
	xmlhttp.open("POST", strUrl, true);
	xmlhttp.onreadystatechange = function()
	{
		//  alert(xmlhttp.readyState + " - " + xmlhttp.status );
		if (xmlhttp.readyState==4)
		{
   		//var result = xmlhttp.responseXML; //Armazena a resposta XML.
			strXPTO = xmlhttp.responseText;
//			alert(strRetorno)
//			alert(strRetorno.substring(0,2))
			if (strXPTO.substring(0,2)=="-1")
			{
				alert(strXPTO.substring(2,strXPTO.length));
				document.all[strDiv].innerHTML = "";
			}
			else
			{
				document.all[strDiv].innerHTML =  xmlhttp.responseText;
			}
	   	//alert(xmlhttp.responseText);
			//document.write(xmlhttp.responseText);
			
			return xmlhttp.responseText;
		}
	}
	
	xmlhttp.send(null);
}

function checatext(campos)
{
campos = campos.split(",");
var campo
var cj
	for (i = 0;i<campos.length;i++){
		cj = campos[i].split("|")

		campo = eval("document.forms[0]."+cj[0])
		
		if (campo.value == "")
		{
			if (balaouchiclete() == "bala"){campo.style.backgroundColor = "#FFFF99";}
			campo.focus();
			alert("Favor preencher o campo: " + cj[1]);
			return false;
			break;
		}
		else if (cj[2] > 0)
		{
			if (campo.value.length > cj[2])
			{
				alert("O campo " + cj[1] + " permite no máximo " + cj[2] + " caracteres, por favor corrija o texto.");
			}
		}
	}
}

function Limpar(valor, validos) {
// retira caracteres invalidos da string
var result = "";
var aux;

	for (var h=0; h < valor.length; h++) {
		aux = validos.indexOf(valor.substring(h, h+1));
		if (aux>=0) {
		result += aux;
		}
	}

return result;
}

function extenso(valor) { 
	
	var rt = "";
    singular = new Array("centavo", "real", "mil", "milhão", "bilhão", "trilhão", "quatrilhão"); 
    plural = new Array("centavos", "reais", "mil", "milhões", "bilhões", "trilhões","quatrilhões"); 
    c = new Array("", "cem", "duzentos", "trezentos", "quatrocentos", "quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"); 
    d = new Array("", "dez", "vinte", "trinta", "quarenta", "cinquenta", "sessenta", "setenta", "oitenta", "noventa"); 
	d10 = new Array("dez", "onze", "doze", "treze", "quatorze", "quinze","dezesseis", "dezesete", "dezoito", "dezenove"); 
	u = new Array("", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove"); 

    var z=0; 

    valor = valor.replace(",","."); 
    
	inteiro = valor.split("."); 

	for (i=0;i<inteiro.length;i++){
   
	    for(ii=inteiro[i].length;ii<3;ii++){ 
            inteiro[i] = "0"+inteiro[i]; 
		}
	}

    fim = inteiro.length - (inteiro[(inteiro.length)-1] > 0 ? 1 : 2); 
  //fim = count($inteiro) - ($inteiro[count($inteiro)-1] > 0 ? 1 : 2); 

	for (i=0;i<(inteiro.length);i++) { 
        valor = inteiro[i]; 
		rc = ((valor > 100) && (valor < 200)) ? "cento" : c[valor.substr(0,1)]; 
		rd = (valor.substr(1,1) < 2) ? "" : d[valor.substr(1,1)]; 
        ru = (valor > 0) ? ((valor.substr(1,1) == 1) ? d10[valor.substr(2,1)] : u[valor.substr(2,1)]) : ""; 
     //   $ru = ($valor > 0) ? (($valor[1] == 1) ? $d10[$valor[2]] : $u[$valor[2]]) : ""; 

        r = rc+((rc && (rd || ru)) ? " e " : "")+rd+((rd && ru) ? " e " : "")+ru; 
        t = (inteiro.length)-1-i; 
        r += r ? " "+(valor > 1 ? plural[t] : singular[t]) : ""; 

        if (valor == "000"){
			z++
		}else if(z > 0){
			z--
		}
        if ((t==1) && (z>0) && (inteiro[0] > 0)){
			 r += ((z>1) ? " de " : "")+plural[t]
		 } 
        if (r) {
			rt = rt + (((i > 0) && (i <= fim) && (inteiro[0] > 0) && (z < 1)) ? ( (i < fim) ? ", " : " e ") : " ") + r
		}
	} 
	
    return (rt); 

} 

function SoNumero(campo)
{
	campo.value = Limpar(campo.value,"0123456789");
}
// Formata número tipo moeda usando o evento onKeyUp
// adicionei um parametro semteclapress para esta função ser utilizada independente 
// da tecla pressionada
function FormataValor(campo,tammax,teclapres,divretornohtml,semteclapres) {
var tecla;
// se vier valor neste parametro mudo o valor da variavel tecla
// para a função ser executada
	if ( semteclapres != "" ) 
	{
		tecla = 8;
	}
	else
	{
		tecla = teclapres.keyCode;

	}
	if (campo.value != ""){
		//retira os pontos e vírgulas
		vr = Limpar(campo.value,"0123456789");
		tam = vr.length;

		if (tam < tammax && tecla != 8){ tam = vr.length ; }

			if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		
				if ( tam <= 2 ){campo.value = vr;}
				
				if ( (tam > 2) && (tam <= 5) ){
					campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - 2, tam ) ; }
				if ( (tam >= 6) && (tam <= 8) ){
					campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ; }
				if ( (tam >= 9) && (tam <= 11) ){
					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) ){
					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) ){
					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 ) ; }
			} 
		
		}
		if (divretornohtml != "")
		{
			document.all(divretornohtml).innerHTML = extenso(campo.value);
		}
	}
function balaouchiclete()
{
	if (navigator.appName.indexOf("Netscape") != -1) {return "chiclete"}
	if (navigator.appName.indexOf("Microsoft") != -1) {return "bala"}
}


function checaradio(nom_rad,des_rad)
{
	var tam = nom_rad.length
	
	for (i = 0;i<nom_rad.length;i++){
		if (nom_rad[i].checked == true){
		return true;
		break;
		}
	}
	nom_rad[0].focus();
	alert("Preencha o campo "+des_rad)
	return false;
}

//2.5.Funcao que checa se foi preenchido o CPF e se é verdadeiro
function check_cpf(nom_cpf)
{
 var cpf_ver = nom_cpf.value
 var p="";
 var soma=0, i=0, num=0, d=0, d1=0, d2=0, zero;

 if (cpf_ver == "11111111111"||cpf_ver == "22222222222"||cpf_ver == "33333333333"||cpf_ver == "44444444444"||cpf_ver == "55555555555"||cpf_ver == "66666666666"||cpf_ver == "77777777777"||cpf_ver == "88888888888"||cpf_ver == "99999999999"||cpf_ver == "00000000000")
    {
	 nom_cpf.value="";
     nom_cpf.focus();
     alert("CPF Inválido. Favor Informar o CPF correto!");
     return false;
    }


 if (cpf_ver.length < 3)
    {
	 nom_cpf.value="";
     nom_cpf.focus();
     alert("CPF Inválido. Favor Informar o CPF correto!");
     return false;
    }
 for (i=0; i < cpf_ver.length; i++)
     {
      if ((digito(cpf_ver.substring(i,i+1))) != 1)
         {
     		nom_cpf.value="";
			nom_cpf.focus();
			alert("CPF Inválido. Favor Informar o CPF correto!");
         return false;
         }
     }
 zero = parseInt(cpf_ver, 10);
 if (zero == 0)
    {
     nom_cpf.value="";
     nom_cpf.focus();
	alert("CPF Inválido. Favor Informar o CPF correto!");
     return false;
    }
 p = cpf_ver.substring(0,(cpf_ver.length - 2));

 for (i = (p.length - 1), d=2; i >= 0; i--, d++)
     {
      num = parseInt(p.charAt(i), 10);
      soma += num*d;
     }
 num = soma / 11;
 num = parseInt(num, 10);
 num = 11 - (soma - (num * 11));
 if (num >= 10) num = 0;
 d1 = num;
 p = cpf_ver.substring(0,(cpf_ver.length - 1));
 for (i = (p.length - 1), d=2, soma=0; i >= 0; i--, d++)
     {
      num = parseInt(p.charAt(i), 10);
      soma += num*d;
     }
 num = soma / 11;
 num = parseInt(num, 10);
 num = 11 - (soma - (num * 11));
 if (num >= 10) num = 0;
 d2 = num;
 p = cpf_ver.substring((cpf_ver.length - 2), (cpf_ver.length - 1));
 if (d1 != parseInt(p, 10))
    {
	 nom_cpf.value="";
     nom_cpf.focus();
     alert("CPF Inválido. Favor Informar o CPF correto!");
     return false;
    }
 p = cpf_ver.substring((cpf_ver.length - 1), (cpf_ver.length));
 if (d2 != parseInt(p, 10))
    {
	 nom_cpf.value="";
     nom_cpf.focus();
     alert("CPF Inválido. Favor Informar o CPF correto!");
     return false;
    }
 return true;
} 


function check_cnpj(nom_cnpj)
{
var StrCGC = nom_cnpj.value
var varFirstChr = StrCGC.charAt(0);
var vlMult,vlControle,s1, s2 = "";
var i,j,vlDgito,vlSoma = 0;
var c;
	for ( var i=0; i<=13; i++ ) 
	{
		c = StrCGC.charAt(i);
		if( ! (c>="0")&&(c<="9") )
		{
			nom_cnpj.value="";
		    nom_cnpj.focus();
			alert("Número do CNPJ Inválido !");
			return false; 
		}
		if( c!=varFirstChr ) { vaCharCGC = true; }
	}
	
	if( ! vaCharCGC ) {
		nom_cnpj.value="";
		nom_cnpj.focus();
		alert("Número do CNPJ Inválido !");
		return false ;
	}
	
	s1 = StrCGC.substring(0,12);
	s2 = StrCGC.substring(12,15);
	vlMult = "543298765432";
	vlControle = "";
	
	for ( j=1; j<3; j++ ) {
		vlSoma = 0;
		for ( i=0; i<12; i++ )
		{ 
			vlSoma += eval( s1.charAt(i) )* eval( vlMult.charAt(i) );
		}
		if( j == 2 ){ vlSoma += (2 * vlDgito); }
		vlDgito = ((vlSoma*10) % 11);
		if( vlDgito == 10 ){ vlDgito = 0; }
			vlControle = vlControle + vlDgito;
			vlMult = "654329876543";
	}		
	if( vlControle != s2 ) 
	{
		nom_cnpj.value="";
		nom_cnpj.focus();
		alert("Número do CNPJ Inválido !");
		return false;
	}
}

function Valida_Email(controle)
{
  if (controle.value != "")
  {
    	var reg1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)")
		var reg2 = new RegExp("[a-zA-Z0-9\\-\\.]+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$")
    	if (reg1.test(controle.value) || !(reg2.test(controle.value)))
    	{
      	alert("Favor preencher o campo de E-mail corretamente");
      	controle.value = "";
      	controle.focus();
      	return false;
		}
	}
}
//Funcao checa se o caracter é numerico retorna 1 e se for string retorna 0
 function digito(dig)
{
 if (dig != "0" && dig !="1" && dig !="2" && dig !="3" && dig !="4"
     && dig !="5" && dig !="6" && dig !="7" && dig !="8" && dig !="9")
    return 0;
 else return 1;
}

//Função que obriga que o campo seja numérico
 function numerico(valor)
{
 for (i=0; i < valor.length; i++)
     {
      if ((digito(valor.substring(i,i+1))) != 1)
         {
         return false;
         }
     }
 return true;
}


// Checa se o CEP foi digitado e se é valido //
function cep_ver(in_cep)
{
	var len = in_cep.value.length
		var cep1 = in_cep.value.substr(0,5);
		var cep2 = in_cep.value.substr(6,3);

		if (numerico(cep1) == true)
	    {
		  if (in_cep.value.substr(5,1) == '-')
	    	{

			  if (numerico(cep2) == true)
	    		{
	    		}
	    	  else
	    	  	{
	    		  alert("Favor preencher o campo de CEP corretamente");
	    		  in_cep.value = "";
	    		  in_cep.focus();
	    		  return false;
			  	}
			}
		   else
		    {
    		  alert("Favor preencher o campo de CEP corretamente");
    		  in_cep.value = "";
    		  in_cep.focus();
    		  return false;
		    }
		   	return true;
		}
	  else
		{
		  alert("Favor preencher o campo de CEP corretamente");
		  in_cep.value = "";
		  in_cep.focus();
		  return false;
		}
		return true;
  	  
}


function VerificaData(nom_Data,msg)
{
	var Data = nom_Data.value
	Tamanho = Data.length;    // recebe o tamanho da data digitada

	if (Tamanho!=8) // avisa que o tamanho está fora do padrão
	{
		nom_Data.focus();
		nom_Data.value = "";
		alert(msg);
		return false
	}

	for(var i = 1; i < Tamanho; i++) // Verifica cada caracter da data digitada
   {
		Letra=Data.substring(i-1,i); // letra recebe o caracter posicionado
       // se o caracter estiver numa dessas posições (1,2,4,5,7,8), então
       // deve ser um número
		if ((i==1) || (i==2) || (i==4) || (i==5) || (i==7) || (i==8))
	   {
			if (Letra<"0" || Letra>"9")
         {
              if (Tamanho!=5)
                 // senão avisa que o formato permitido é DD/MM/AA
              {
				  	 		nom_Data.focus();
		nom_Data.value = "";
		alert(msg);
				  }
				return false;
		   }
		}
		else
      {
			if ((i==3) || (i==6)) // e se estiver na posição 3 ou 6
         {
				if (Letra != "/")
            {
					nom_Data.focus();
		nom_Data.value = "";
		alert(msg);
					return false;}
				}
         }
		}

   // já que a data está com números e barras nas posições corretas
	var Dia=Data.substring(0,2); // extrai o dia
	var Mes=Data.substring(3,5); // extrai o mês
	var Ano=Data.substring(6,8); // extrai o ano

   // valida os limites aceitáveis para dia, mês e ano
	if ((Dia<1 || Dia>31) || (Mes<1 || Mes>12) || (Ano<00 || Ano>99))
   {
		nom_Data.focus();
		nom_Data.value = "";
		alert(msg);
		return false;
	}

   // valida o limite de dia para o meses que possuem limite igual a 30 (2,4,6,9,11)
	if ((Mes==2 || Mes==4 || Mes==6 || Mes==9 || Mes==11) & Dia>30)
   {	Verifica=false;
		nom_Data.focus();
		nom_Data.value = "";
		alert(msg);
		return Verifica;}

    // valida o dia para o mês de fevereiro
	if (Mes==2 & Dia>29)
   {
		nom_Data.focus();
		nom_Data.value = "";
		alert(msg);
		return false;
	}

return true;
} /** function VerificaData(Data) **/





// script coloca os pontos do cnpj

function FormataCNPJ(campo,tammax,teclapres) {

		var tecla = teclapres.keyCode;
		
		var vr = campo.value;
		vr = vr.replace( "-", "" );
		vr = vr.replace( "/", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		tam = vr.length;
	
		if (tam < tammax && tecla != 13){ tam = vr.length + 1 ; }
	
		if (tecla == 13 ){	tam = tam - 1 ; }
			
		if ( tecla == 13 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) ){
			if ( tam <= 2 ){ 
				campo.value = vr ; }
			tam = tam - 1;
			if ( (tam > 2) && (tam <= 5) ){
				campo.value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 6) && (tam <= 8) ){
				campo.value = vr.substr( 0, tam - 6 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 9) && (tam <= 11) ){
				campo.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 12) && (tam <= 14) ){
				campo.value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
		}
}

function fecha_busca()
{
	document.all["divbusca"].style.visibility = "hidden";
}
function abre_busca()
{
	document.all["divbusca"].style.visibility = "visible";
}

function voltabranco(ocampo)
{
ocampo.style.backgroundColor = "#FFFFFF";
}

//#################################################################################################################
