/************************************************************
Coleção de Funções do site da SEED
Última Atualização: 15.07.2004
*************************************************************/

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.0
  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 && document.getElementById) x=document.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 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 P7_autoLayers() { //v1.4 by PVII
 var g,b,k,f,args=P7_autoLayers.arguments;a=parseInt(args[0]);if(isNaN(a))a=0;
 if(!document.p7setc){p7c=new Array();document.p7setc=true;for(var u=0;u<10;u++){
 p7c[u]=new Array();}}for(k=0;k<p7c[a].length;k++){if((g=MM_findObj(p7c[a][k]))!=null){
 b=(document.layers)?g:g.style;b.visibility="hidden";}}for(k=1;k<args.length;k++){
 if((g=MM_findObj(args[k]))!=null){b=(document.layers)?g:g.style;b.visibility="visible";f=false;
 for(var j=0;j<p7c[a].length;j++){if(args[k]==p7c[a][j]) {f=true;}}
 if(!f){p7c[a][p7c[a].length++]=args[k];}}}
}

function P7_hideDiv(evt) { //v1.3 by PVII
 var b,relT,mT=false; 
 if(document.layers){b=evt.target;if(b.p7aHide){
  b.visibility="hidden";}else{routeEvent(evt);}
 }else if(document.all&&!window.opera){b=event.srcElement;
  while(b!=null){if(b.tagName=="DIV" && b.p7ahD){mT=true;break;}b=b.parentElement;}
  if(!b.contains(event.toElement)){b.style.visibility="hidden";}
 }else if(document.getElementById){b=evt.currentTarget;relT=evt.relatedTarget;
  while(relT!=null){if(b==relT){mT=true;break;}
  relT=relT.parentNode;}if(!mT){b.style.visibility="hidden";}}
}

function P7_autoHide() { //v1.3 by PVII
 var i,g,args=P7_autoHide.arguments;
 for(i=0;i<args.length;i++){if((g=MM_findObj(args[i]))!=null){
  g.p7aHide=true;if(document.layers){
  g.captureEvents(Event.MOUSEOUT);}g.onmouseout=P7_hideDiv;g.p7ahD=true;}}
}

// Testa se o valor de um campo CPF é Válido
// Recebe o nome e a descrição do campo como parâmetros
function TestaCPF(Campo, Descricao) {
  cpf = Campo.value;
  cpf = cpf.replace(".", "");
  cpf = cpf.replace(".", "");
  cpf = cpf.replace("/", "");
  cpf = cpf.replace("-", "");
  erro = new String;
  if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! "; 
  var nonNumbers = /\D/;
  if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! "; 
  if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
    erro += "Numero de CPF inválido!"
  }
  var a = [];
  var b = new Number;
  var c = 11;
  for (i=0; i<11; i++){
    a[i] = cpf.charAt(i);
    if (i < 9) b += (a[i] * --c);
  }
  if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
  b = 0;
  c = 11;
  for (y=0; y<10; y++) b += (a[y] * c--); 
  if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
  if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
    erro +="Numero de CPF inválido!\nDígito verificador com problema!";
  }
  if (erro.length > 0){
    alert(erro);
    return false;
  }
  return true;
}

// Testa se o valor de um campo é uma Data válida
// Recebe o nome e a descrição do campo como parâmetros
function TestaData(Campo, Descricao) {
  hoje = new Date();
  anoAtual = hoje.getFullYear();
  barras = Campo.value.split("/");
  if (barras.length == 3){
    dia = barras[0];
    mes = barras[1];
    ano = barras[2];
    resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) && (ano >= 1900));
    if (!resultado) {
      alert("A Data do campo \"" + Descricao + "\" é Inválida!");
      return false;
    }
  } else {
      alert("A Data do campo \"" + Descricao + "\" é Inválida!");
      return false;
  }
}

// Testa se o valor de um campo é uma Hora válida no formato HH:MM de 24h
// Recebe o nome e a descrição do campo como parâmetros
function TestaHora(Campo, Descricao) {
    var pStr = Campo.value;
	var reTime = /^([0-1]\d|2[0-3]):[0-5]\d$/;
	if (!reTime.test(pStr)) {
      alert("O Horário do campo \"" + Descricao + "\" é Inválido!\nDigite um valor no formato \"HH:MM\"");
      return false;
	}
}

// Testa se o valor de um campo é um Número Inteiro
// Recebe o nome e a descrição do campo como parâmetros
function TestaInteiro(Campo, Descricao) {
  var checkOK = "0123456789";
  var checkStr = Campo.value;
  var allValid = true;
  var allNum = "";
  for (i = 0;  i < checkStr.length;  i++) {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length) {
      allValid = false;
      break;
    }
    if (ch != ",")
      allNum += ch;
  }
  if (!allValid) {
    alert("O campo \"" + Descricao + "\" só pode conter Números Inteiros!");
    return (false);
  }
}

//--------------------------------------------------------------------------------------------------
// Confirma - Exibe uma Caixa de Diálogo para Confirmação de uma Operação (Edição, Deleção, etc)
//--------------------------------------------------------------------------------------------------
//   Pagina = Nome da página onde será executada a ação. Ex: CadastroAlunos.asp;
//   Texto = Texto (Pergunta, Enunciado...) exibido antes dos Botões de Sim ou Não;
//   Larg = Largura da Caixa de Diálogo em pixels;
//   Alt = Altura da Caixa de Diálogo em pixels;
//   Obs: Necessita dos arquivos: "confirma_popup.asp" e "images/atencao_popup.gif"
//   Ex: Confirma('<%=Server.URLEncode(Request.ServerVariables("SCRIPT_NAME")&"?Chave=5&Chave2=0&nrRG="&strnrRG&"&dsUf="&strdsUf&"&cdExame="&strcdExame&"&dsNome="&strdsNome)%>', 'Tem certeza que deseja <b>Excluir</b> o registro de<br><b><%=strdsNome%></b>?', 320, 125)
function Confirma(Pagina, Texto, Larg, Alt) {
  if (window.showModalDialog) {
  window.showModalDialog("confirma_popup.asp?Pagina="+Pagina+"&Texto="+Texto, window, "dialogWidth:"+Larg+"px; dialogHeight:"+Alt+"px; status:no;")
  } else {
    alert("Para utilizar esse sistema você necessita do Internet Explorer 4 ou Superior!")
  }
}

//--------------------------------------------------------------------------------------------------
// Pick - Função que retorna a opção escolhida numa janela de "Localizar" de volta para a página que a chamou 
//--------------------------------------------------------------------------------------------------
function Retorna(Link) {
  if (window.opener && !window.opener.closed) {
    window.opener.location.href = Link;
    window.close();
  }
}

//--------------------------------------------------------------------------------------------------
// Fechar - Função que solicita uma confirmação ao usuário antes de fechar a janela atual
//--------------------------------------------------------------------------------------------------
function Fechar() {
	if ( window.confirm("Tem certeza que deseja sair do Sistema?")) {
		window.close();
	}
}

/************************************************************
Coleção de Funções Extraídas do Site da Caixa
*************************************************************/

//-----------------------------------------------------------
// Função para filtar campos tipo TEXT em formulários
// Ex: <INPUT onfocus=this.select() onkeyup="Filtro(this,'data');" class=ie id=txtDataInicio title="Entre com a data no formato: DD/MM/AAAA" maxLength=10 size=11 name=txtDataInicio>
// Objeto =  Campo de um Formulário
// tpCampo =  Tipo do campo (alfanumerico, maiusculas, sonumeros, data, hora, valor, inteiro, real, float)
//-----------------------------------------------------------

function Filtro(Objeto,tpCampo) {
    if (navigator.appName.substr(0,9) != "Microsoft") {
        return;
    }

    if (window.event.keyCode == 37 || window.event.keyCode == 8
            || window.event.keyCode == 36 || window.event.keyCode == 46
            || window.event.keyCode == 16 || window.event.keyCode == 9)
        return;

    if (window.event.keyCode == 111 || window.event.keyCode == 191) {
	    if (tpCampo == "data") {
		    if (Objeto.value.length == 3 || Objeto.value.length == 6) {
			    return;
		    }
		    if (Objeto.value.length == 4 || Objeto.value.length == 7) {
			    var newpos = Objeto.value.length - 1;
			    Objeto.value = Objeto.value.substring(0,newpos);
			    return;
		    }
	    }
    }

    if (window.event.keyCode == 39) {
	    if (tpCampo == "data") {
            if (Objeto.value.length == 2 || Objeto.value.length == 5) {
			    Objeto.value = Objeto.value + "/";
            }
        }
        return;
    }

	if (tpCampo == "alfanumerico" || tpCampo == "alfamaiuscula" || tpCampo == "alfaminuscula") {
    	Objeto.value = PassaDominio(Objeto.value, " ,-ºª´`~^._!@$*()=+[]{}?/\|;:<>%#¨0123456789AÁÀÂÃBCÇDEÉÊFGHIÍJKLMNOÓÔÕPQRSTUÚÜVWXYZaáàâãbcçdeéêfghiíjklmnoóôõpqrstuúüvwxyz");
		if (tpCampo == "alfamaiuscula") {
            Objeto.value = Objeto.value.toUpperCase();
			return;
		}
		if (tpCampo == "alfaminuscula") {
            Objeto.value = Objeto.value.toLowerCase();
			return;
		}
		return;
	}
	if (tpCampo == "letra" || tpCampo == "letramaiuscula" || tpCampo == "letraminuscula") {
    	Objeto.value = PassaDominio(Objeto.value, " AÁÀÂÃBCÇDEÉÊFGHIÍJKLMNOÓÔÕPQRSTUÚÜVWXYZaáàâãbcçdeéêfghiíjklmnoóôõpqrstuúüvwxyz");
		if (tpCampo == "letramaiuscula") {
            Objeto.value = Objeto.value.toUpperCase();
			return;
		}
		if (tpCampo == "letraminuscula") {
            Objeto.value = Objeto.value.toLowerCase();
			return;
		}
		return;
	}
	if (tpCampo == "uf") {
    	Objeto.value = PassaDominio(Objeto.value, "ABCDEFGIJLMNOPRSTabcdefgijlmnoprst");
        Objeto.value = Objeto.value.toUpperCase();
		if (Objeto.value.length == 2) {
			if (Objeto.value != "AC" && Objeto.value != "AL" && Objeto.value != "AP" && Objeto.value != "AM" && Objeto.value != "BA" && Objeto.value != "CE" && Objeto.value != "DF" && Objeto.value != "GO" && Objeto.value != "ES" && Objeto.value != "MA" && Objeto.value != "MT" && Objeto.value != "MS" && Objeto.value != "MG" && Objeto.value != "PA" && Objeto.value != "PB" && Objeto.value != "PR" && Objeto.value != "PE" && Objeto.value != "PI" && Objeto.value != "RJ" && Objeto.value != "RN" && Objeto.value != "RS" && Objeto.value != "RO" && Objeto.value != "RR" && Objeto.value != "SP" && Objeto.value != "SC" && Objeto.value != "SE" && Objeto.value != "TO") {
               alert("Informe uma UF válida!\nAC, AL, AP, AM, BA, CE, DF, GO, ES, MA, MT, MS, MG,\nPA, PB, PR, PE, PI, RJ, RN, RS, RO, RR, SP, SC, SE, TO.");
               Objeto.focus();
               return;
			}
		}
		return;
	}
	if (tpCampo == "inteiro") {
        Objeto.value = PassaDominio(Objeto.value, "0123456789+-");
		return;
	}
	if (tpCampo == "real") {
        Objeto.value = PassaDominio(Objeto.value, "0123456789+-,.");
		return;
	}
	if (tpCampo == "float") {
        Objeto.value = PassaDominio(Objeto.value, "0123456789+-Ee,.");
		return;
	}
	if (tpCampo == "maiusculo") {
        Objeto.value = Objeto.value.toUpperCase();
		return;
	}
	if (tpCampo == "minusculo") {
        Objeto.value = Objeto.value.toLowerCase();
		return;
	}
	if (tpCampo == "fone") {
        Objeto.value = PassaDominio(Objeto.value, "0123456789()- ");
		return;
	}
	if (tpCampo == "email") {
    	//Objeto.value = BloqueiaDominio(Objeto.value, " ÁÀÂÃÄáàâãäÉÈÊËéèêëÍÌÎÏíìîïÓÒÔÕÖóòôõöÚÙÛÜúùûü'()*&¨%$#!´`~^/?[]{}=+\|,<>;:");
    	Objeto.value = PassaDominio(Objeto.value, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@-_.");
        Objeto.value = Objeto.value.toLowerCase();
		return;
	}
	if (tpCampo == "numero" || tpCampo == "data" || tpCampo == "cpf" || tpCampo == "cnpj" || tpCampo == "hora" || tpCampo == "valor" || tpCampo == "cep") {
        Objeto.value = PassaDominio(Objeto.value, "0123456789");
		if (tpCampo == "data") {
			Objeto.value = FmtData(Objeto.value);
			return;
		}
		if (tpCampo == "cpf") {
			Objeto.value = FmtCPF(Objeto.value);
			return;
		}
		if (tpCampo == "cnpj") {
			Objeto.value = FmtCNPJ(Objeto.value);
			return;
		}
		if (tpCampo == "hora") {
			Objeto.value = FmtHora(Objeto.value);
			return;
		}
		if (tpCampo == "valor") {
			Objeto.value = FmtCurr(Objeto.value);
			return;
		}
		if (tpCampo == "cep") {
			Objeto.value = FmtCEP(Objeto.value);
			return;
		}
	}
}

/*-----------------------------------------------------------------*
 | PassaDominio        Retorna a String dada, somente com os       |
 |                     caracteres do domínio dado                  |
 *-----------------------------------------------------------------*/
function PassaDominio(StrDado, Dominio)
	{
	var i, j, c;
	var Result;
	
	Result = "";
	for (i=0; i<StrDado.length; i++)
		{
		c = StrDado.substr(i,1);
		for (j=0; j<Dominio.length; j++)
			{
			if (c == Dominio.substr(j,1)) break;
			}
		if (j < Dominio.length)
			{
			Result = Result + c;
			}
		}
	return Result;
}

/*-----------------------------------------------------------------*
 | BloqueiaDominio     Retorna a String dada retirando os          |
 |                     caracteres do domínio dado                  |
 *-----------------------------------------------------------------*/
function BloqueiaDominio(StrDado, Dominio)
	{
	var i, j;
	
	Result = "";
	for (i=0; i<StrDado.length; i++)
		{
		c = StrDado.substr(i,1);
		for (j=0; j<Dominio.length; j++)
			{
			if (c == Dominio.substr(j,1)) break;
			}
		if (j >= Dominio.length)
			{
			Result = Result + c;
			}
		}
	return Result;
	}

/*
 Nome........: FmtData
 Descricao...: Insere a máscara de data no campo
 Paramentros.: Dado
 Retorno.....: Retorna o conteúdo formatado em dd/mm/yyyy, não permitindo a digitação de caracteres alfa
*/
function FmtData(Dado)
  {
  var Result = Dado;
  var l = Dado.length;

  if((l > 2) && (l < 5))
    {
	Result = Dado.substr(0, 2) + "/" + Dado.substr(2, 2);
    }
  if(l >= 5)
    {
	Result = Dado.substr(0, 2) + "/" + Dado.substr(2, 2) + "/" + Dado.substr(4, 4);
	}
  return Result;
  }

/*
 Nome........: FmtCPF
 Descricao...: Insere a máscara de CPF no campo
 Paramentros.: Dado
 Retorno.....: Retorna o conteúdo formatado em 000.000.000-00, não permitindo a digitação de caracteres alfa
*/
function FmtCPF(Dado)
  {
  var Result = Dado;
  var l = Dado.length;

  if((l > 3) && (l < 7))
    {
	Result = Dado.substr(0, 3) + "." + Dado.substr(3, 3);
    }
  if((l >= 7) && (l < 10))
    {
	Result = Dado.substr(0, 3) + "." + Dado.substr(3, 3) + "." + Dado.substr(6, 3);
    }
  if(l >= 10)
    {
	Result = Dado.substr(0, 3) + "." + Dado.substr(3, 3) + "." + Dado.substr(6, 3) + "-" + Dado.substr(9, 2);
	}
  return Result;
  }
/*
 Nome........: FmtCPF
 Descricao...: Insere a máscara de CPF no campo
 Paramentros.: Dado
 Retorno.....: Retorna o conteúdo formatado em 000.000.000-00, não permitindo a digitação de caracteres alfa
*/

function FmtCNPJ(Dado)
  {
  var Result = Dado;
  var l = Dado.length;

  if((l > 2) && (l < 6))
    {
	Result = Dado.substr(0, 2) + "." + Dado.substr(2, 3);
    }
  if((l >= 6) && (l < 9))
    {
	Result = Dado.substr(0, 2) + "." + Dado.substr(2, 3) + "." + Dado.substr(5, 3);
    }
  if((l >= 9) && (l < 13))
    {
	Result = Dado.substr(0, 2) + "." + Dado.substr(2, 3) + "." + Dado.substr(5, 3) + "/" + Dado.substr(8, 4);
	}
  if((l >= 13))
    {
	Result = Dado.substr(0, 2) + "." + Dado.substr(2, 3) + "." + Dado.substr(5, 3) + "/" + Dado.substr(8, 4) + "-" + Dado.substr(12, 2);
	}
  return Result;
  }

/*
 Nome........: FmtCEP
 Descricao...: Insere a máscara de CEP no campo
 Paramentros.: Dado
 Retorno.....: Retorna o conteúdo formatado em 00.000-000, não permitindo a digitação de caracteres alfa
*/
function FmtCEP(Dado)
  {
  var Result = Dado;
  var l = Dado.length;

  if((l > 2) && (l < 6))
    {
	Result = Dado.substr(0, 2) + "." + Dado.substr(2, 3);
    }
  if((l >= 6))
    {
	Result = Dado.substr(0, 2) + "." + Dado.substr(2, 3) + "-" + Dado.substr(5, 3);
    }
  return Result;
  }

/*
 Nome........: FmtCurr
 Descricao...: Insere a máscara de Moeda (Currency) no campo
 Paramentros.: Dado
 Retorno.....: Retorna o conteúdo formatado moeda
*/
function FmtCurr(Dado)
  {
  var Result, i;
  
  if (Dado.length > 2)
    {
    Result = "," + Dado.substr(Dado.length-2, 2);
    for (i=5; i<=Dado.length; i+=3)
      {
      Result = Dado.substr(Dado.length-i, 3) + Result;
      if (Dado.length > i) Result = "." + Result;
      }
    Result = Dado.substr(0, Dado.length-i+3) + Result;
    }
  else
    {
    Result = Dado;
    }
  return Result;
}

/*
 Nome........: FmtHora
 Descricao...: Insere a máscara de hora no campo
 Paramentros.: Dado
 Retorno.....: Retorna o conteúdo formatado em hh:mm, não permitindo a digitação de caracteres alfa
*/
function FmtHora(Dado)
{
  var Result = Dado;
  for (i = 1; i <= Dado.length; i++)
	{
      if (i >= 3)
		{
			Result = Dado.substr(0, 2) + ":" + Dado.substr(2, 2);
		}
	}
  return Result;
}

/*-----------------------------------------------------------------*
 | ContidoNoDominio    Retorna True se a String dada só contiver   |
 |                     caracteres do domínio dado                  |
 *-----------------------------------------------------------------*/
function ContidoNoDominio(StrDado, Dominio)
	{
	var i, j;
	
	if (StrDado == "") return false;
	
	for (i=0; i<StrDado.length; i++)
		{
		for (j=0; j<Dominio.length; j++)
			{
			if (StrDado.substr(i,1) == Dominio.substr(j,1)) break;
			}
		if (j >= Dominio.length) return false;
		}
	return true
	}
			
/*-----------------------------------------------------------------*
 | ContemDominio    Retorna True se a String dada contiver algum   |
 |                  caractere do domínio dado                      |
 *-----------------------------------------------------------------*/
function ContemDominio(StrDado, Dominio)
	{
	var i, j;
	
	if (StrDado != "")
		{
		for (i=0; i<StrDado.length; i++)
			{
			for (j=0; j<Dominio.length; j++)
				{
				if (StrDado.substr(i,1) == Dominio.substr(j,1)) return true;
				}
			}
		}
		
	return false;
	}

function TiraPontos (NumeroFormatado)
{
    var s
    s  = NumeroFormatado.split (".");
    return s.join("");
}

function TiraVirgula (NumeroFormatado)
{
    var s
    s  = NumeroFormatado.split (",");
    return s.join("");
}

function TiraTracos (NumeroFormatado)
{
    var s
    s  = NumeroFormatado.split ("-");
    return s.join("");
}

function limpaCamposTxt(nomeForm) {
    for (i = 0; i < nomeForm.length; i++) {
        if (nomeForm.elements[i].type == "text") {
            nomeForm.elements[i].value = "";
        }
    }
}
