var cidade = null;
var aguardando = false;	// indica se há uma consulta em processamento
var formFlds=null;
var canalGlo = null;
var placeGlo = null;
var win = null;

function IEHoverPseudo() {
   if(chkBrowser(navigator.appName)==1) {
      if(navigator.appVersion.indexOf('6.0') != -1) {
           var navItems = document.getElementsByTagName('tr');
           for(var i=0; i<navItems.length; i++) {
               if(navItems[i].className == "linha") {
                    navItems[i].onmouseover = function() {this.className  = 'blue';}
                    navItems[i].onmouseout  = function() {this.className  = 'linha';}
               }
           }
      }
   }
}

function masDate(campo, evento) {
  var objeto = document.getElementById(campo);
  var tecla;
  if(chkBrowser(navigator.appName)==1)
       tecla = evento.keyCode;
  else  tecla = evento.which;

  var data = objeto.value;

  if (evento.keyCode==8 || evento.keyCode==46 || evento.keyCode==9 || evento.keyCode==13 || evento.keyCode==116 || evento.keyCode==37 || evento.keyCode==38 || evento.keyCode==39 || evento.keyCode==40) {
      return (true);
  }

  if (data.length==10) {
      return (false);
  }

  if (tecla<48 || tecla>57) {
     alert("Somente números");
     return (false);
  }

  if ((data.length==2) || (data.length==5)){
       data=data+'/';
  }

  objeto.value=data;
  return (true);
}

function showSearchLink()  {
  var tipo=encodeURIComponent(document.getElementById("tipo").value);
  var buscar=document.getElementById("buscar").href;
  var pesq=encodeURIComponent(document.getElementById("pesq").value);
  var link=buscar+pesq+'&tipo='+tipo;
  return document.getElementById("buscar").href=link;
}

function removeDados() {
    //removendo tabela dados
    var dates = document.getElementById('dados');
    while(dates.hasChildNodes() == true) {
        dates.removeChild(dates.childNodes[0]);
    }
   //removendo paginação
   var pag = document.getElementById('paginacao');
   var pai = pag.parentNode;
   pai.removeChild(pag);
}

function trim (str, charlist) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
 
    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function ProtectCode() {
   if (event.button==2||event.button==3) {
      alert('Código Protegido!');
      oncontextmenu='return false';
  }
}

function aviso(tipo,msg,cor) {
  if(cor) {
      document.getElementById('avisos').className = 'alertRed';
  }
  else {
     document.getElementById('avisos').className = 'alert';
  }
  var texto = '';
  if(!msg)
    texto = "Aguarde...processando!";
  else
    texto = msg;
  var aviso = document.getElementById('avisos');
    if(tipo==0) 
      aviso.innerHTML="";
    else {
      aviso.innerHTML = texto;
    }
}

function onlyNumber(event){
    var tecla, evento;
	if (!event)
       evento = window.event;
    else
       evento = event;
	if (evento.keyCode) tecla = evento.keyCode;
	else if (evento.which) tecla = evento.which;
    var validos = '0123456789';
    if (tecla==0 || tecla==8 || tecla==9 || tecla==13 || tecla==37 || tecla==38 || tecla==39 || tecla==40 || tecla==116 || tecla == 46 ) {
     return (true);
    }
    var numerico = validos.indexOf(String.fromCharCode(tecla));
    if (numerico==-1) {
       alert('Campo númerico!');
    return (false);
  }
  return true;
}

function onlyChar(event){
    var tecla, evento;
	if (!event)
       evento = window.event;
    else
       evento = event;
	if (evento.keyCode) tecla = evento.keyCode;
	else if (evento.which) tecla = evento.which;
    var validos = 'qwertyuiopasdfghjklzxcvbnm';
    if (tecla==0 || tecla==8 || tecla==9 || tecla==13 || tecla==37 || tecla==38 || tecla==39 || tecla==40 || tecla == 46 ) {
     return (true);
    }
    var numerico = validos.indexOf(String.fromCharCode(tecla));
    if (numerico==-1) {
       alert('Campo caracter!');
    return (false);
  }
  return true;
}

function onlyNumberP(event){
    var tecla, evento;
	if (!event)
       evento = window.event;
    else
       evento = event;
	if (evento.keyCode) tecla = evento.keyCode;
	else if (evento.which) tecla = evento.which;
    var validos = '0123456789';
    if (tecla==58 || tecla==0 || tecla==8 || tecla==46 || tecla==9 || tecla==13 || tecla==37 || tecla==38 || tecla==39 || tecla==40 || tecla==116|| tecla == 46) {
     return (true);
    }
    var numerico = validos.indexOf(String.fromCharCode(tecla));
    if (numerico==-1) {
      alert('Campo númerico!');
    return (false);
  }
  return true;
}

function masVal(campo,event,act) {
    var tecla, evento;
	if (!event)
       evento = window.event;
    else
       evento = event;
	if (evento.keyCode) tecla = evento.keyCode;
	else if (evento.which) tecla = evento.which;
    var validos = '0123456789';
    if (tecla==0 || tecla==8 || tecla==46 || tecla==9 || tecla==13 || tecla==37 || tecla==38 || tecla==39 || tecla==40 || tecla==116 || tecla==46 || validos.indexOf(String.fromCharCode(tecla))!=-1) {
    if(tecla!=13) {
    	var vr = document.getElementById(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;
    	if (tecla == 9){tam = tam - 1 ;}
    	if ( tecla != 8 && tecla != 46 && tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 || tecla == 9) {
    		if ( tam <= 2 ){
                document.getElementById(campo).value = vr;}
    	 	if ( (tam > 2) && (tam <= 5) ){
    	 		document.getElementById(campo).value = vr.substr( 0, tam - 2 ) + '.' + vr.substr( tam - 2, tam ) ;}
    	 	if ( (tam >= 6) && (tam <= 8) ){
                document.getElementById(campo).value = vr.substr( 0, tam - 5 ) + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam ) ;}
    	 	if ( (tam >= 9) && (tam <= 11) ){
    	 		document.getElementById(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.getElementById(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.getElementById(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 ) ;}
    	}
    }
   else {
     if(act!=null)
       act();
   }
  }
  else {
     alert('Campo númerico!');
     return false;
  }
 return true;
}

function masVal4(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode==0) return true;
if (whichCode==13) return true;
if (whichCode==38) return true;
if (whichCode==39) return true;
if (whichCode==40) return true;
if (whichCode==41) return true;
if (whichCode == 13) return true;
if (whichCode == 8) return true;
if (whichCode == 9) return true;
if (whichCode == 46) return true;
key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida
len = fld.value.length;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) fld.value = '';
if (len == 1) fld.value = '0'+ decSep + '0' + aux;
if (len == 2) fld.value = '0'+ decSep + aux;
if (len == 3) fld.value = '0'+ decSep + aux;
if (len == 4) fld.value = '0'+ decSep + aux;
if (len > 4) {
aux2 = '';
for (j = 0, i = len - 5; i >= 0; i--) {
if (j == 6) {
aux2 += milSep;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}
fld.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
fld.value += aux2.charAt(i);
fld.value += decSep + aux.substr(len - 4, len);
}
return false;
}

function showPhoneType(phone,mostra) {
    var tel = document.getElementById(phone).value;
    var first = tel.substr(0,1);
    if(tel) {
        if(tel.length < 10 || first==0) 
          document.getElementById(mostra).innerHTML = 'Inválido';
        else {
         var letra3 =  tel.substr(2,1);
         if(letra3 >= 7) //mobile
           document.getElementById(mostra).innerHTML = 'Celular';
         else 
           document.getElementById(mostra).innerHTML = 'Fixo';   
        }
     }
   else
      document.getElementById(mostra).innerHTML = 'DD+NÚMERO';   
}

// cria a div das sugestões, com uma tabela dentro
function createSuggest(cidlink) {
    cidade = cidlink;
	// cria a camada onde serão exibidas as sugestões
	var novaCamada = document.createElement('div');
	novaCamada.className = 'sugestoes';
	novaCamada.setAttribute('id','divPopup');

	// cria a tabela que ficará dentro da camada
	var tabela = document.createElement('table');
	tabela.setAttribute('id','tabela');
	tabela.setAttribute('bgcolor','#EEEEEE');
	tabela.setAttribute('border','0');
	tabela.setAttribute('cellspacing','0');
	tabela.setAttribute('cellpadding','0');
	novaCamada.appendChild(tabela);
	document.body.appendChild(novaCamada);
    Sugestoes();
}

// ativa o programa servidor que retorna as sugestões
function Sugestoes() {
	var palavras =  document.getElementById(cidade);
	if(palavras.value.length>0) {
		if(!aguardando) {
			var url="sugestoes.php?palavras="+palavras.value;
      		requisicaoHTTP("GET",url,true,16);
			aviso(1);
		}
	}
	else LimparSugestoes();
}

// trata a resposta do servidor
function shoSug(){
	var resposta = ajax.responseXML;
	aviso(0);
	MostrarSugestoes(resposta);
}

// cria a lista de sugestões na tabela HTML
function MostrarSugestoes(dados) {
	LimparSugestoes();
	var linha, celula;
	var tabela =  document.getElementById('tabela');
	var num = dados.getElementsByTagName('nome').length;
	if(num>0) {
		PosicionarCamada();
		for(var i=0; i<num; i++) {
			var sugestao = dados.getElementsByTagName('nome')[i].firstChild.data;
			linha = tabela.insertRow(tabela.rows.length);
			celula = linha.insertCell(0);
			celula.onmouseover = function() {this.className='comCor';};
			celula.onmouseout = function() {this.className='semCor';};
			celula.onclick = function() {PreencherCaixa(this);};
			celula.setAttribute('border','0');
			celula.innerHTML = sugestao;
		}
	}
}

// preenche a caixa de texto com a sugestão selecionada
function PreencherCaixa(valor) {
	var caixaTexto =  document.getElementById(cidade); 
	caixaTexto.value = valor.firstChild.nodeValue;
	LimparSugestoes();
}

// limpa a camada de sugestões
function LimparSugestoes() {
	var camada =  document.getElementById('divPopup');
	camada.style.border = '0';
	var tabela = document.getElementById('tabela');
	while(tabela.hasChildNodes())
		tabela.removeChild(tabela.childNodes[0]);
}

// posiciona a camada de sugestões logo abaixo da caixa de texto
function PosicionarCamada() {
	var camada =  document.getElementById('divPopup');
	var tabela =  document.getElementById('tabela');
	var caixaTexto =  document.getElementById(cidade);

	var largura = caixaTexto.offsetWidth;
	var esq = CalcularPos(caixaTexto,'offsetLeft');
	var cima = CalcularPos(caixaTexto,'offsetTop') + caixaTexto.offsetHeight;
	
	camada.style.border = '#000000 1px solid';
	camada.style.left = esq + 'px';
	camada.style.top = cima + 'px';
	tabela.style.width = largura + 'px';
}

// função auxiliar para calcular a posição (offset) do campo
function CalcularPos(campo, atributo) {
	var posicao = 0;
	while(campo) {
		posicao += campo[atributo];
		campo = campo.offsetParent;
	}
	return posicao;
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  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 MM_findObj(n, d) { //v4.01
  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() { //v3.0
  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 plaCall() {
    if(confirm('Deseja realmente ligar para sua Operadora?')) {
       var url="cliente.php?act=plc";
       alert('Aguarde enquanto a conferência com a operadora é realizada!');
       requisicaoHTTP('GET',url,true,17);
    }
}

function plcCal() {
   var resp = ajax.responseText;
   if(resp.indexOf('Erro') != -1)   //se ocorreu erro
       alert(resp);
   else
       alert('Ligação recebida pela operadora!');
}

function valCpf(cpf) {
   var numeros, digitos, soma, i, resultado, digitos_iguais;
   digitos_iguais = 1;
   if (cpf.length < 11)
      return false;
   for (i = 0; i < cpf.length - 1; i++)
     if (cpf.charAt(i) != cpf.charAt(i + 1)) {
          digitos_iguais = 0;
          break;
     }
     if (!digitos_iguais) {
         numeros = cpf.substring(0,9);
         digitos = cpf.substring(9);
         soma = 0;
         for (i = 10; i > 1; i--)
                soma += numeros.charAt(10 - i) * i;
         resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
         if (resultado != digitos.charAt(0))
               return false;
         numeros = cpf.substring(0,10);
         soma = 0;
         for (i = 11; i > 1; i--)
            soma += numeros.charAt(11 - i) * i;
         resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
         if (resultado != digitos.charAt(1))
               return false;
         return true;
     }
     else
        return false;
}

function valCnpj(cnpj) {
   var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
   digitos_iguais = 1;
   if (cnpj.length < 14 && cnpj.length < 15)
        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))
           return false;
         return true;
   }
   else
       return false;
}

function retnotEmpt(campo) {
   var revpre   = document.getElementById(campo).value;
   if(revpre.length<2 || revpre==null)
      document.getElementById(campo).className = 'fielderr';
   else
     document.getElementById(campo).className = 'field';
}

function valrevTel() {
  var revtel   = document.getElementById('revtel').value;
  if(revtel.length < 8)
      document.getElementById('revtel').className = 'fielderr';
  else
     document.getElementById('revtel').className = 'field';
      
}

function valrevNom() {
   var revnom  = document.getElementById('revnom').value;
   if(revnom == null || revnom.length == 0)
        document.getElementById('revnom').className = 'fielderr';
   else
     document.getElementById('revnom').className = 'field';

}
function masData(objeto, event) {
    var tecla, evento;
	if (!event)
       evento = window.event;
    else
       evento = event;
	if (evento.keyCode) tecla = evento.keyCode;
	else if (evento.which) tecla = evento.which;
    var data = objeto.value;
    if (data.length==10) {
      if (tecla==8 || tecla==46 || tecla==9 || tecla==13 || tecla==37 || tecla==38 || tecla==39 || tecla==40) {
       return (true);
      }
      else
        return (false);
    }
    if (tecla==8 || tecla==46 || tecla==9 || tecla==13 || tecla==37 || tecla==38 || tecla==39 || tecla==40) {
     return (true);
    }
    else {
        if (tecla<48 || tecla>57) {
            alert("Somente números");
            return (false);
        }
    }
    if ((data.length==2) || (data.length==5)){
        data=data+'/';
    }
    objeto.value=data;
  return (true);
}

function valMail(campo) {
    var cliema   = document.getElementById(campo).value;
    if(cliema.length != 0) {
        if(cliema.indexOf('.') == -1 || cliema.indexOf('@') == -1 || cliema.indexOf(' ') != -1)
            document.getElementById(campo).className = 'fielderr';
        else
            document.getElementById(campo).className = 'field';
    }
    else
       document.getElementById(campo).className = 'fielderr';
}

function valSen(campo) {
   var clisen   = document.getElementById(campo).value;
   if(clisen.length < 5 || clisen.length==0)
      document.getElementById(campo).className = 'fielderr';
   else
     document.getElementById(campo).className = 'field';
}

function valTel(campo,tam) {
   var teldig   = document.getElementById(campo).value;
   if(teldig.length < tam || teldig.length==0)
      document.getElementById(campo).className = 'fielderr';
   else
     document.getElementById(campo).className = 'field';
}

function valIP(IP) {
   var ipaddress   = document.getElementById(IP).value;
   if(verifyIP(ipaddress)==false)
      document.getElementById(IP).className = 'fielderr';
   else
     document.getElementById(IP).className = 'field';
}

function verifyIP (IPvalue) {
   errorString = "";
   theName = "IPaddress";
   var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
   var ipArray = IPvalue.match(ipPattern);

   if (IPvalue == "0.0.0.0")
       errorString = errorString + theName + ': '+IPvalue+' é um IP especial e não pode ser usado!';
   else if (IPvalue == "255.255.255.255")
       errorString = errorString + theName + ': '+IPvalue+' é um IP especial e não pode ser usado!';
   if (ipArray == null)
       errorString = errorString + theName + ': '+IPvalue+' não é um IP válido!';
   else {
      for (i = 0; i < 4; i++) {
         thisSegment = ipArray[i];
         if (thisSegment > 255) {
            errorString = errorString + theName + ': '+IPvalue+' não é um IP válido!';
            i = 4;
         }
         if ((i == 0) && (thisSegment > 255)) {
            errorString = errorString + theName + ': '+IPvalue+' é um IP especial e não pode ser usado!';
            i = 4;
         }
      }
   }
   extensionLength = 3;
   if (errorString == "")
      return true; //alert ("That is a valid IP address.");
   else
     return false; //alert (errorString);
}

function valDate(dtIni,dtFin) {
    var ano_dataI,mes_dataI,dia_dataI;
    var myDateI=new Date();
    var dadosI = new Array(3);
    dadosI = dtIni.value.split("/");
    ano_dataI = parseFloat(dadosI[2]);
    mes_dataI = parseFloat(dadosI[1]);
    dia_dataI = parseFloat(dadosI[0]);
    myDateI.setFullYear(ano_dataI, mes_dataI-1, dia_dataI);

    var ano_dataF,mes_dataF,dia_dataF;
    var myDateF=new Date();
    var dadosF = new Array(3);
    dadosF = dtFin.value.split("/");
    ano_dataF = parseFloat(dadosF[2]);
    mes_dataF = parseFloat(dadosF[1]);
    dia_dataF = parseFloat(dadosF[0]);
    myDateF.setFullYear(ano_dataF, mes_dataF-1, dia_dataF);

    if(myDateF<myDateI || document.getElementById(dtFin.id).value.length==0)
       document.getElementById(dtFin.id).className = 'fielderr';
    else
       document.getElementById(dtFin.id).className = 'field';
}

function valDifDate(dtIni,dtFin) {
    var ano_dataI,mes_dataI,dia_dataI;
    var myDateI=new Date();
    var dadosI = new Array(3);
    dadosI = dtIni.value.split("/");
    ano_dataI = parseFloat(dadosI[2]);
    mes_dataI = parseFloat(dadosI[1]);
    dia_dataI = parseFloat(dadosI[0]);
    myDateI.setFullYear(ano_dataI, mes_dataI-1, dia_dataI);

    var ano_dataF,mes_dataF,dia_dataF;
    var myDateF=new Date();
    var dadosF = new Array(3);
    dadosF = dtFin.value.split("/");
    ano_dataF = parseFloat(dadosF[2]);
    mes_dataF = parseFloat(dadosF[1]);
    dia_dataF = parseFloat(dadosF[0]);
    myDateF.setFullYear(ano_dataF, mes_dataF-1, dia_dataF);

    if(myDateF<myDateI)
       return false;
    else
       return true;
}

function chkBrowser(nome) {
   var sta = '';
    if((nome.indexOf('Netscape') != -1) || (nome.indexOf('Firefox') != -1))
        sta = 0;
    else if((nome.indexOf('Internet Explorer') != -1) || (nome.indexOf('Microsoft') != -1))
        sta = 1;
    if(sta!=0 && sta!=1)
        sta = 2;
  return sta;
}


function formFldData (fld) {
   this.name  = fld.name;
   this.value = fld.value;
}

function SaveFormData(theForm) {
   formFlds = new Array();
   if (!theForm) {return false;}
   for (var ix=0; ix < theForm.elements.length; ix++) {
         formFlds[ix] = new formFldData(theForm.elements[ix]);
   }
   return true;
}

function FindFld (fld) {
   var str = null;
   if (!fld) {return false;}
   for (var ix=0; ix < formFlds.length; ix++) {
         if (!fld.name) {continue;}
         if (!formFlds[ix].name) {continue;}
       if (exactMatch(fld.name,formFlds[ix].name)) {
            if (!exactMatch(encodeURIComponent(fld.value),encodeURIComponent(formFlds[ix].value))) {
                if(fld.value.length!=0 || formFlds[ix].value.length!=0)
                   str = 1; //'\n Field Name:' + fld.name + '\n    New Value:' + fld.value.length + '\n  Old Value:' + formFlds[ix].value.length;
                break;
            }
         }
   }
   return str;
}

function exactMatch(s1, s2) {
   if (!s1) {return false;}
   if (!s2) {return false;}
   if (s1.length == s2.length) {
      if (s1.match(s2) && s2.match(s1)) {return true;}
   }
   return false;
}

function CheckChanged(theForm1) {
    var theForm = document.getElementById(theForm1);
    var changed = false;
    if (!theForm) {return changed;}
    for (var ex=0; ex < theForm.elements.length; ex++) {
       var str = FindFld (theForm.elements[ex]);
       if (str)
          changed = true;
    }
    if (changed==false) {
        alert('Não houveram alterações!');
    }
  return changed;
}

function valRota(event){
    var tecla, evento;
	if (!event)
       evento = window.event;
    else
       evento = event;
	if (evento.keyCode) tecla = evento.keyCode;
	else if (evento.which) tecla = evento.which;
    var validos = '0123456789[-]X';
    if (tecla==0 || tecla==8 || tecla==9 || tecla==13 || tecla==37 || tecla==38 || tecla==39 || tecla==40) {
     return (true);
    }
    var numerico = validos.indexOf(String.fromCharCode(tecla));
    if (numerico==-1) {
       alert('Caracter Inválido!');
    return (false);
  }
  return true;
}

function buscaCidades(uf,objeto) {
	cidades = document.getElementById(objeto);
	cidades.innerHTML = '';
	var op = document.createElement('option');
        op.setAttribute('value', '');
        cidades.appendChild(op);
        var url = 'usuario.php?act=shc&cidest='+uf;
	requisicaoHTTP('GET',url,true,21);
        op.appendChild(document.createTextNode("Carregando..."));
}

function shwCid() {
    aviso(0);
    var resp = ajax.responseText;
    var arrayOpcoes = eval(resp);
    cidades.innerHTML = '';
    createOptions(cidades,arrayOpcoes);
}

function createOptions(lista, opcoes) {
    if(opcoes == null || opcoes.length==0) {return;}
    var op = null;
    for(var i=0; i<opcoes.length; i++) {
        op = document.createElement("option");
        op.setAttribute("value",opcoes[i]);
        op.appendChild(document.createTextNode(opcoes[i]));
        lista.appendChild(op);
    }
}

function hanRow(canal,place) {
  if(confirm('Deseja realmente desligar essa chamada?')) {
     canalGlo = canal;
     placeGlo = place;
     var url="usuario.php?act=han&canal="+canal;
     requisicaoHTTP("GET",url,true,24);
     aviso(1);
  }
}

function hanReg() {
   var resp = ajax.responseText;
   if(resp.indexOf('Erro') != -1)   //se ocorreu erro
       alert(resp);
   else {
     if(placeGlo==0) {
       var row = document.getElementById(canalGlo);
       if(row) {
           var pai = row.parentNode;
           pai.removeChild(row);
           alert(resp);
       }
       else {
          alert(resp);
       }
     }
     else {
        alert(resp);
        var canal = document.getElementById('channel').value;
        var url = 'showcalldetail.php?channel='+canal;
        window.open(url, target='_top');
        if(chkBrowser(navigator.appName)==1) {
            location.href=url;
        }
     }
   }
   aviso(0);
}

function NovaJanela(pagina,nome,w,h,scroll){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	var settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
	window.open(pagina,nome,settings);
}

function retqteAbas(menu) {
    var menP = document.getElementById(menu);
    var abas = menP.getElementsByTagName('a');
    return parseInt(abas.length);
}

function changeAba(num,fieldFoco) {
    var qteAbas = retqteAbas('menu');
    for(var i=1; i <= qteAbas; i++) {
          document.getElementById('div'+i).style.display = 'none';
          document.getElementById('op'+i).className = 'abaoff';
    }
    document.getElementById('div'+num).style.display = 'inline';
    document.getElementById('op'+num).className = 'abaon';
    foco(num,fieldFoco);
}

function mudaAba(event,atual) {
   var tecla, evento, newAba;
   atual = parseInt(atual);
   if (!event)
       evento = window.event;
   else
       evento = event;
   if (evento.keyCode) tecla = evento.keyCode;else if (evento.which) tecla = evento.which;
   if(parseInt(tecla)==9) {
        newAba = atual+1;
        changeAba(newAba);
   }
}

function foco(aba,fieldFoco) {
    if(fieldFoco) {
        document.getElementById(fieldFoco).focus();
    }
    else {
        var divCont = document.getElementById('div'+aba);
        var tabCont = divCont.getElementsByTagName('table')[0];
        var celulas = tabCont.getElementsByTagName('td');
        if(celulas[1].firstChild.id)
          document.getElementById(celulas[1].firstChild.id).focus();
    }
}

function criaoptCombo(lista,opcoes,tipo) {
    if(opcoes == null || opcoes.length==0) {return;}
    var op = null;
    if(tipo==0) {
        op = null;
        opc = document.createElement("option");
        opc.appendChild(document.createTextNode('Todos'));
    	opc.setAttribute('value','T');
        lista.appendChild(opc);
    }
    if(tipo==1) {
        op = null;
        opc = document.createElement("option");
        opc.appendChild(document.createTextNode('Selecione'));
    	opc.setAttribute('value','');
        lista.appendChild(opc);
    }
    for(var i=0; i<opcoes.length; i++) {
        var separado = eval(opcoes[i]);
        op = document.createElement("option");
        op.appendChild(document.createTextNode(separado[1]));
	op.setAttribute('value',separado[0]);
        lista.appendChild(op);
    }
}

function limpaCombo(elemento) {
    if(elemento != null && elemento.hasChildNodes()) {
        for(var i=0; i<elemento.childNodes.length; i++) {
            elemento.removeChild(elemento.firstChild);
        }
    }
}

function setCookie(c_name,value,expiredays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

function getCookie(c_name) {
if (document.cookie.length>0) {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1) {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
    }
  }
 return "";
}

function updateAciona(opc) {
    setCookie('acionado',opc,1);
    if(getCookie('acionado')==1) {
         msg = 'Atualização automática iniciada.';
    }
    else {
         msg = 'Atualização automática parada.';
    }
    aviso(1,msg);
    alert(msg);
}

function updateStatus() {
    if(getCookie('acionado')==1) {
       window.location.reload();
       aviso(1,'Atualização Automática iniciada.');
    }
    else {
        aviso(1,'Atualização Automática parada.');
    }
}

function showStatus() {
    var status = getCookie('acionado');
    var msg = '';
    if(status=='1') {
        msg = 'Atualização Automática iniciada.';
    }
    else {
        msg = 'Atualização Automática parada.';
    }
    aviso(1,msg);
}
