// A função abaixo pega a versão mais nova do xmlhttp do IE e verifica se é Firefox. Funciona nos dois.
function createXMLHTTP() 
{
    try 
    {
        ajax = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    catch(e) 
    {
		try 
		{
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
			alert(ajax);
		}
		catch(ex) 
		{
			try 
			{
			    ajax = new XMLHttpRequest();
			}
			catch(exc) 
            {
                 alert("Esse browser não tem recursos para uso do Ajax");
                 ajax = null;
            }
        }
        return ajax;
    }
    var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
        "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
    for (var i=0; i < arrSignatures.length; i++) 
    {
        try 
        {
            var oRequest = new ActiveXObject(arrSignatures[i]);
            return oRequest;
        } 
        catch (oError) 
        {
        }
    }
    throw new Error("MSXML is not installed on your system.");
}
function BuscaEndereco(sCep, sTipo, sForm)
{
	document.getElementById('DIVCADASTRO').innerHTML='<div align="center" class="carregando"><img src="http://www.vscontrol.com.br/imagens/ajaxgif.gif"><br/><br/><font size=1 face=arial>carregando...</font></div>'
    // Criação do objeto XMLHTTP
    var oHTTPRequest = createXMLHTTP(); 
	// Abrindo a solicitação HTTP. O primeiro parâmetro informa o método post/get
	// O segundo parâmetro informa o arquivo solicitado que pode ser asp, php, txt, xml, etc.
	// O terceiro parametro informa que a solicitacao nao assincrona,
	// Para solicitação síncrona, o parâmetro deve ser false
    oHTTPRequest.open("post", "ajax_endereco.asp", true);
    // Para solicitações utilizando o método post, deve ser acrescentado este cabecalho HTTP
    oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1");
    // A função abaixo é executada sempre que o estado do objeto muda (onreadystatechange)
    oHTTPRequest.onreadystatechange=function() 
    {
        // O valor 4 significa que o objeto já completou a solicitação
        if (oHTTPRequest.readyState==4)
        {
            // Abaixo o texto é gerado no arquivo executa.asp e colocado no div
            document.all.DIVCADASTRO.innerHTML = oHTTPRequest.responseText;
        }
    }
	// Abaixo é enviada a solicitação. Note que a configuração
	// do evento onreadystatechange deve ser feita antes do send.
    oHTTPRequest.send("cep=" + sCep + "&sTipo=" + sTipo);
    
	//alert();  
	if(document.forms["frmCadastro"]["text2"].length != 0){
	alert(document.forms["frmCadastro"]["text2"].length);  
	}
	
}
//FUNÇÃO PARA FORMATAR MOEDA
function FormataValor(obj,teclapres) 
{ 
	if(window.event) { // Internet Explorer
		var tecla = teclapres.keyCode; }
	else if(teclapres.which) { // Nestcape / firefox
		var tecla = teclapres.which;
	}
	//alert(tecla)
	var tammax = 17; 
	if ( tecla >= 48 && tecla <= 57 )
	{ 
		vr = obj.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; 
  		if (tam < tammax)
		{ 
			tam = vr.length + 1 ; 
		} 
		if ( tam <= 2 )
		{ 
			obj.value = "0," + vr ; 
		} 
		if(tam>3) 
		{ 
			if(vr.substr(0,1)=="0") 
			{ 
			  vr = vr.substr(1,tam); 
			  tam--; 
			} 
		} 
	    //if ( (tam > 2) && (tam <= 6) ){//000,00 
		if ( (tam > 2) )
		{//000,00 
		obj.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam );
	} 
} 
else
	{
		return false;
	}
}

function FormataValor3(obj,teclapres) 
{ 
	if(window.event) { // Internet Explorer
		var tecla = teclapres.keyCode; }
	else if(teclapres.which) { // Nestcape / firefox
		var tecla = teclapres.which;
	}
	//alert(tecla)
	var tammax = 17; 
	if ( tecla >= 48 && tecla <= 57 )
	{ 
		vr = obj.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; 
  		if (tam < tammax)
		{ 
			tam = vr.length + 1 ; 
		} 
		if ( tam <= 3 )
		{ 
			obj.value = "0," + vr ; 
		} 
		if(tam>4) 
		{ 
			if(vr.substr(0,1)=="0") 
			{ 
			  vr = vr.substr(1,tam); 
			  tam--; 
			} 
		} 
	    //if ( (tam > 2) && (tam <= 6) ){//000,00 
		if ( (tam > 3) )
		{//000,00 
		obj.value = vr.substr( 0, tam - 3 ) + ',' + vr.substr( tam - 3, tam );
	} 
} 
else
	{
		return false;
	}
}



function AtualizaTabelaPreco(sCampo, sValor, sCondicao)
{
	document.getElementById('DIV_PRECO').innerHTML='<div align="center" class="carregando"><img src="http://www.vscontrol.com.br/imagens/ajaxgif.gif"><br/><br/></div>'
    // Criação do objeto XMLHTTP
    var oHTTPRequest = createXMLHTTP(); 
	// Abrindo a solicitação HTTP. O primeiro parâmetro informa o método post/get
	// O segundo parâmetro informa o arquivo solicitado que pode ser asp, php, txt, xml, etc.
	// O terceiro parametro informa que a solicitacao nao assincrona,
	// Para solicitação síncrona, o parâmetro deve ser false
    oHTTPRequest.open("post", "atualiza_tabela.asp", true);
    // Para solicitações utilizando o método post, deve ser acrescentado este cabecalho HTTP
    oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1");
    // A função abaixo é executada sempre que o estado do objeto muda (onreadystatechange)
    oHTTPRequest.onreadystatechange=function() 
    {
        // O valor 4 significa que o objeto já completou a solicitação
        if (oHTTPRequest.readyState==4)
        {
            // Abaixo o texto é gerado no arquivo executa.asp e colocado no div
            document.all.DIV_PRECO.innerHTML = oHTTPRequest.responseText;
        }
    }
	// Abaixo é enviada a solicitação. Note que a configuração
	// do evento onreadystatechange deve ser feita antes do send.
    oHTTPRequest.send("campo=" + sCampo + "&valor=" + sValor + "&condicao=" + sCondicao);	
}

function MostraFoto(link)
{
window.open(link,'foto','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,height=450,width=450, left='+((window.screen.width-820)/2)+' , top='+((window.screen.height-600)/2)+'');
}
function AtualizaFoto(sIMG)
{
	document.getElementById('DIVFOTO').innerHTML='<div align="center"><IMG SRC=' + sIMG + ' height=300 width=300 border=0></div><BR>'
}
    
function QueryString(variavel){
    return qs[variavel]
}

function AbreJanela(link)
{
window.open(link,'JANELA','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,height=400,width=400, left='+((window.screen.width-820)/2)+' , top='+((window.screen.height-600)/2)+'');
}
function AbreJanelaPag(link)
{
window.open(link,'JANELA','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,height=600,width=800, left='+((window.screen.width-820)/2)+' , top='+((window.screen.height-600)/2)+'');
}
//MÁSCARA DE VALORES
function txtBoxFormat(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

if(document.all) { // Internet Explorer
    nTecla = evtKeyPress.keyCode;
} else if(document.layers) { // Nestcape
    nTecla = evtKeyPress.which;
} else {
    nTecla = evtKeyPress.which;
}
    
    if (nTecla == 8) {
        return true;
    }
    if (nTecla == 13) {
        return true;
    }
    if (nTecla == 0) {
        return true;
    }

    sValue = objeto.value;
    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
      bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
      bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

      if (bolMask) {
        sCod += sMask.charAt(i);
        mskLen++; }
      else {
        sCod += sValue.charAt(nCount);
        nCount++;
      }
      i++;
    }

    objeto.value = sCod;
    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58)); } 
      else { // qualquer caracter...
        return true;
      } 
    }
    else {
      return true;
    }
  }
  
  //FUNCAO PARA MUDAR CAMPO COM ENTER
  function autoTab(input, e)  {    
  var ind = 0;   
  var isNN = (navigator.appName.indexOf("Netscape")!=-1);   
  var keyCode = (isNN) ? e.which : e.keyCode;    
  var nKeyCode = e.keyCode;    
  if(keyCode == 13){    
    if (!isNN) {window.event.keyCode = 0;} // evitar o beep   
    ind = getIndex(input);   
    if (input.form[ind].type == 'textarea') {   
      return;   
    }   
    ind++;   
    input.form[ind].focus();    
    if (input.form[ind].type == 'text') {   
      input.form[ind].select();    
    }   
  }    
  
  function getIndex(input) {    
    var index = -1, i = 0, found = false;    
    while (i < input.form.length && index == -1)    
      if (input.form[i] == input) {   
        index = i;   
          if (i < (input.form.length -1)) {   
           if (input.form[i+1].type == 'hidden') {   
       index++;    
     }   
     if (input.form[i+1].type == 'button' && input.form[i+1].id == 'tabstopfalse') {   
       index++;    
     }   
   }   
      }   
      else    
   i++;    
    return index;    
  }   
} 
//***************************************************************************************   
function verifica_cnpj(cnpj)
{
var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
digitos_iguais = 1;
if (cnpj.length < 14 && cnpj.length < 15) {
	  alert('O CNPJ Informado é inválido.');
      return false;
      }
for (i = 0; i < cnpj.length - 1; i++)
      if (cnpj.charAt(i) != cnpj.charAt(i + 1))
            {
            digitos_iguais = 0;
            break;
            }
if (!digitos_iguais)
      {
      tamanho = cnpj.length - 2
      numeros = cnpj.substring(0,tamanho);
      digitos = cnpj.substring(tamanho);
      soma = 0;
      pos = tamanho - 7;
      for (i = tamanho; i >= 1; i--)
            {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
                  pos = 9;
            }
      resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
      if (resultado != digitos.charAt(0))
            return false;
      tamanho = tamanho + 1;
      numeros = cnpj.substring(0,tamanho);
      soma = 0;
      pos = tamanho - 7;
      for (i = tamanho; i >= 1; i--)
            {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
                  pos = 9;
            }
      resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
      if (resultado != digitos.charAt(1)) {
	        alert('O CNPJ Informado é inválido.');
            return false;
            }
      return true;
      }
else
	alert('O CNPJ Informado é inválido.');
    return false;
}

function verificacpf (cpf) {
	valido=true;
	if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
		valido=false;
	add = 0;
	for (i=0; i < 9; i ++)
		add += parseInt(cpf.charAt(i)) * (10 - i);
	rev = 11 - (add % 11);
	if (rev == 10 || rev == 11)
		rev = 0;
	if (rev != parseInt(cpf.charAt(9)))
		valido=false;
	add = 0;
	for (i = 0; i < 10; i ++)
		add += parseInt(cpf.charAt(i)) * (11 - i);
	rev = 11 - (add % 11);
	if (rev == 10 || rev == 11)
		rev = 0;
	if (rev != parseInt(cpf.charAt(10)))
		valido=false;
	if (valido == false)
		alert('O CPF Informado é inválido.');
	return true;
}

//**************************************************************************/
function TABEnter(oEvent){
  var oEvent = (oEvent)? oEvent : event;
  var oTarget =(oEvent.target)? oEvent.target : oEvent.srcElement;
  if(oEvent.keyCode==13)
    oEvent.keyCode = 9;
  if(oTarget.type=="text" && oEvent.keyCode==13)
    //return false;
    oEvent.keyCode = 9;
  if (oTarget.type=="radio" && oEvent.keyCode==13)
    oEvent.keyCode = 9;
}

//**************************************************************************/

function LerCookie(strCookie)
{
    var strNomeIgual = strCookie + "=";
    var arrCookies = document.cookie.split(';');

    for(var i = 0; i < arrCookies.length; i++)
    {
        var strValorCookie = arrCookies[i];
        while(strValorCookie.charAt(0) == ' ')
        {
            strValorCookie = strValorCookie.substring(1, strValorCookie.length);
        }
        if(strValorCookie.indexOf(strNomeIgual) == 0)
        {
            return unescape(strValorCookie.substring(strNomeIgual.length, strValorCookie.length));
        }
    }
    return null;
}

function GerarCookie(strCookie, strValor, lngDias)
{
    var dtmData = new Date();

    if(lngDias)
    {
        dtmData.setTime(dtmData.getTime() + (lngDias * 24 * 60 * 60 * 1000));
        var strExpires = "; expires=" + dtmData.toGMTString();
    }
    else
    {
        var strExpires = "";
    }
    strValor=escape(strValor);

    document.cookie = strCookie + "=" + strValor + strExpires + "; path=/";
}

function ExcluirCookie(strCookie)
{
    GerarCookie(strCookie, '', -1);
}

//************************************************************************************

function removeAcento(text) { 
	if (text != 'null') {
	text = text.replace(new RegExp('[ÁÀÂÃ]','gi'), 'A'); 
	text = text.replace(new RegExp('[ÉÈÊ]','gi'), 'E'); 
	text = text.replace(new RegExp('[ÍÌÎ]','gi'), 'I'); 
	text = text.replace(new RegExp('[ÓÒÔÕ]','gi'), 'O'); 
	text = text.replace(new RegExp('[ÚÙÛ]','gi'), 'U'); 
	text = text.replace(new RegExp('[Ç]','gi'), 'C'); 
	text = text.replace(new RegExp('[áâã]','gi'), 'a'); 
	text = text.replace(new RegExp('[éê]','gi'), 'e'); 
	text = text.replace(new RegExp('[íî]','gi'), 'i'); 
	text = text.replace(new RegExp('[óôõ]','gi'), 'o'); 
	text = text.replace(new RegExp('[úû]','gi'), 'u'); 
	text = text.replace(new RegExp('[ç]','gi'), 'c'); 
	text = text.replace(new RegExp('[+]','gi'), ' '); 
	text = text.replace(new RegExp('%2E','gi'), '.'); 
	return text;
	}
}

function replaceAll(str, de, para){
 while (str.indexOf(de) != -1) {   
        str = str.replace(de, para);   
    }  
    return (str);
}

