// 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) 
{ 
  var tecla = teclapres.keyCode; 
  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 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=330,width=310, 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=150 width=150 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;
    }
}
    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;    
  }   
} 
//***************************************************************************************   