var dirty = false;

// -----------------------------------------------------------------
//	Nome:		VerificarTeclaBusca()
//	Parâmetros:	nenhum
//	Descrição:	Dá o submit na busca se o usuário digitar a tecla ENTER
// -----------------------------------------------------------------
function VerificarTeclaBusca() {
	if(event.keyCode == 13)
		EnviaBusca(0);
}

// -----------------------------------------------------------------
//	Nome:		VerificaString(frase)
//	Parâmetros:	frase
//	Descrição:	Verifica se os caracteres são válidos
// -----------------------------------------------------------------
function VerificaString(frase) {
	var arrCaracteres = new Array();
	var booErro = false;
	arrCaracteres[0] = "´";
	arrCaracteres[1] = "'";
	arrCaracteres[2] = "`";
	arrCaracteres[3] = '"';
	arrCaracteres[4] = '>';
	arrCaracteres[5] = '<';
	for(x=0; x< arrCaracteres.length; x++) {
		if(frase.indexOf(arrCaracteres[x]) >= 0) {
			booErro = true;
		}
	}
	return booErro
}

// -----------------------------------------------------------------
//	Nome:		EnviaBusca
//	Parâmetros:	nenhum
//	Descrição:	envia o formulario da busca
// -----------------------------------------------------------------
function EnviaBusca(bRetorno) {
	if(document.Busca.palavra.value == "")
		alert("Você deve digitar uma palavra chave!")
	else {
		if(VerificaString(document.Busca.palavra.value)) {
			alert("Você não deve utilizar caracteres inválidos, como acentos isolados e símbolos.");
		}
		else {
			if(Trim(document.Busca.palavra.value).length < 3) {
				alert("A palavra chave deve ter no mínimo 3 letras.");
			}
			else {
				if(document.all.OpcaoBusca[0].checked == true)
					document.Busca.action = DirConteudo + "Busca/BuscaFuncionario.asp";
				if(document.all.OpcaoBusca[1].checked == true){
					document.Busca.validate.value = 1;
					document.Busca.PalavraChave.value = document.Busca.palavra.value
					document.Busca.action = DirConteudo + "Busca/Busca.asp";
				}
				document.Busca.submit();
				
			}
		}
	}
	
	if (bRetorno == 1)
		return false;
}

// -----------------------------------------------------------------
//	Nome:		BuscaAvancada
//	Parâmetros:	nenhum
//	Descrição:	vai para a busca avançada
// -----------------------------------------------------------------
function BuscaAvancada() {
	if(document.all.OpcaoBusca[0].checked == true)
		document.location.href = DirConteudo + "Busca/BuscaFuncionario.asp";
	if(document.all.OpcaoBusca[1].checked == true)
		document.location.href = DirConteudo + "Busca/Busca.asp?Validate=4";
}

// -----------------------------------------------------------------
//	Nome:		FichaFuncionario
//	Parâmetros:	matricula, empresa - informações do usuario
//	Descrição:	abri um popup com a ficha completa do funcionario
// -----------------------------------------------------------------

function FichaFuncionario(matricula, empresa) 
{
	AbreJanela(DirConteudo + "Busca/ficha.asp?matricula=" + matricula + "&empresa=" + empresa, 550, 400, "yes", "no", "no")
}

// -----------------------------------------------------------------
//	Nome:		MenuAbrir
//	Parâmetros:	item
//	Descrição:	abri uma pagina do menu do navegador
// -----------------------------------------------------------------

function MenuAbrir(item) {
	switch(item.toUpperCase()) {
		case "FAQ":
				window.location.href = DirConteudo + "faq/faq.asp"
			break;
		case "DICAS":
				window.location.href = DirConteudo + "dica/dica.asp"
			break;
		case "CONVENIO":
				window.location.href = DirConteudo + "convenio/convenio.asp"
			break;
		case "CAMPANHAS":
				window.location.href = DirConteudo + "campanha/campanha.asp"
			break;
		case "SOBRE":
				window.location.href = DirConteudo + "sobre.asp"
			break;
		case "HOME":
				window.location.href = DirConteudo + "default.asp"
			break;
	}
}

// -----------------------------------------------------------------
//	Nome:		MudaImagem
//	Parâmetros:	objeto e imagem
//	Descrição:	muda a imagem de um objeto imagem
// -----------------------------------------------------------------

function MudaImagem(item, imagem)
{
	item.src = DirImagem + imagem;
}

// -----------------------------------------------------------------
//	Nome:		VerificaBotao
//	Parâmetros:	div e item(imagem)
//	Descrição:	troca a imagem de um item
// -----------------------------------------------------------------

function VerificaBotao(div,item)
{
	if (document.all[div].style.display == 'none')
		MudaImagem(item, 'HOME/bt_caixas_dw.gif');
	else
		MudaImagem(item, 'HOME/bt_caixas_up.gif');
}

// -----------------------------------------------------------------
//	Nome:		AbreEditor
//	Parâmetros:	nome do Campo do Formulário a ser preechido com o código HTML
//	Descrição:	abre o editor HTMl com o conteúdo do campo, para ser editado 
// -----------------------------------------------------------------
function FechaJanelaErro() {
	document.all.JanelaErro.style.display = 'none';
}
// -----------------------------------------------------------------
//	Nome:		abrePopUp
//	Parâmetros:	sPagina: página do pop-up
//				nAltura
//	Descrição:	abre um pop-up no tamanho padrão
// -----------------------------------------------------------------
function abrePopUp(sPagina, nAltura)
{
	if(!nAltura)
		nAltura = 400;
	AbreJanela(sPagina, 516, nAltura);
}
// -----------------------------------------------------------------
//	Nome:		abreEvento
//	Parâmetros:	nCodAgenda: Código do evento da agenda
//	Descrição:	abre num pop-up os dados do evento
// -----------------------------------------------------------------
function abreEvento(nCodAgenda)
{
	abrePopUp(DirConteudo + "agenda/pop_evento.asp?nCodAgenda=" + nCodAgenda);
}
// -----------------------------------------------------------------
//	Nome:		AbreEditor
//	Parâmetros:	nome do Campo do Formulário a ser preechido com o código HTML
//	Descrição:	abre o editor HTMl com o conteúdo do campo, para ser editado 
// -----------------------------------------------------------------
function AbreEditor(Campo)
{	AbreJanela('../Editor/webedit/fulledit.asp?Field=' + Campo, 670, 400);
}


// -----------------------------------------------------------------
//	Nome:		LimpaItens
//	Parâmetros:	nenhum
//	Descrição:	limpa os valores de alguns itens 
// -----------------------------------------------------------------

function LimpaItens() {
	if(document.Paging) {
		document.all.id_item_lista.value = '';
		document.all.cod_item_lista.value = '';
	}
}

// -----------------------------------------------------------------
//	Nome:		VerificaData
//	Parâmetros:	campo - nome do campo com a data a ser verificada
//				condição - codição para desabilitar o campo
//	Descrição:	verifica se a data pode ser modificada ou não.
// -----------------------------------------------------------------

function VerificaData(campo, condicao) {
	var objeto = document.Cadastro.elements["OWS:" + campo + ":Date"];
	if(condicao) {
		var Data = new Date();
		var mes = Data.getMonth() + 1;
		var dia = Data.getDate()
		if(mes<10)
			mes = "0" + mes;
		if(dia < 10)
			dia = "0" + dia;
		sData = dia + "/" + mes + "/" + Data.getYear();
		
		if( InverteData(objeto.value) < InverteData(sData) ) {
			document.all["img" + campo].onclick = "";
			objeto.style.background = "#FEFEFE"
			objeto.style.color = "#888888"
			objeto.readOnly = true;
			if(document.Cadastro.elements["OWS:" + campo + ":Hours"])
				document.Cadastro.elements["OWS:" + campo + ":Hours"].disabled = true;
			
			if(document.Cadastro.elements["OWS:" + campo + ":Minutes"])
				document.Cadastro.elements["OWS:" + campo + ":Minutes"].disabled = true;
		}
	}
}

// -----------------------------------------------------------------
//	Nome:		VerificaData
//	Parâmetros:	campo - nome do campo com a data a ser verificada
//				condição - codição para desabilitar o campo
//	Descrição:	verifica se a data pode ser modificada ou não.
// -----------------------------------------------------------------

// -----------------------------------------------------------------
// Nome: setDirty
// Descrição: 
// -----------------------------------------------------------------
function setDirty()
{	
	dirty = true;
}

 // -----------------------------------------------------------------
 // Nome: ConfirmaRemocao
 // Descrição: pede confirmacao ao usuario antes da remocao de um item
 // -----------------------------------------------------------------
 function ConfirmaRemocao()
 {
 	return confirm("Você tem certeza que deseja remover este item?");
 }

 // -----------------------------------------------------------------
 // Nome: TrocaImagem
 // Descrição: substitui uma imagem pela outra
 // Parâmetros: nomes das imagens
 // -----------------------------------------------------------------
 function TrocaImagem(oldImage,newImage)
 {
 	if (parseInt(navigator.appVersion) >= 3)
 		document[oldImage].src = eval(newImage + ".src");
 }

 // -----------------------------------------------------------------
 // Nome: AbreJanela
 // Parâmetros: pagina (pagina a ser aberta na nova janela - caminho relativo)
 //			   largura e altura - opcionais - definem altura e largura da nova janela (valores padrão: 600, 400)
 // -----------------------------------------------------------------
 function AbreJanela(pagina, largura, altura, scrollbar, status, resizable, nomeJanela)
 {
 	if (!largura)
 		largura = 600;
			
 	if (!altura)
 		altura = 400;

	if (!status)
 		status = "yes";

	if (!scrollbar)
		scrollbar = "yes";

	if (!resizable)
		resizable = "yes";
		
	if (!nomeJanela)
	{
		nomeJanela = Substitui(RetiraEspaco(Date()),":","");
		nomeJanela = nomeJanela.substring(0, 15)
	}

	window.open(pagina, nomeJanela, "toolbar=no,status=" + status + ",location=no,directories=no,scrollbars=" + scrollbar + ",resizable=" + resizable + ",copyhistory=no,width=" + largura + ",height=" + altura);
 }
	
 // -----------------------------------------------------------------
 // Nome: Substitui
 // Parâmetros:	t (expressão a ser modificada)
 //				f (expressão a ser substituída)
 //				r (expressão que irá substituir a antiga)
 // Retorno:
 // -----------------------------------------------------------------
 function Substitui(t,f,r)
 {

   if (f == ".")
      var re = /\./g;
   else
      var re = new RegExp(f,"g");

   return t.replace(re, r);
 }


 // -----------------------------------------------------------------
 // Nome: ValidaData
 // Parâmetro: strData - string representando uma data
 // Retorno: TRUE caso seja uma data válida (dd/mm/aaaa), FALSE caso contrário
 // -----------------------------------------------------------------
 function ValidaData(strData)
 {
 	//verifica se a data foi digitada corretamente
 	strData = RetiraEspaco(strData);
 	if (Vazio(strData)) 
 		return false;
 	var strNum = "0123456789/";
 	var Size = strData.length;
 	//testa a validade dos caracteres que formam a data
 	for (var i=0; i<Size; i++) {
 		if (strNum.indexOf(strData.charAt(i)) < 0)
 			return false;
 	}
			
 	var Pos1 = strData.indexOf("/");
 	var Pos2 = strData.lastIndexOf("/");
 	if (!(Pos1==2 && Pos2==5)) return false;
						
 	a = strData.split("/");
 	if (a.length == 3 && a[2].length==4 && a[2]>0) {
 		if ((a[1]<1) || (a[1]>12)) 
 			return false;
 		else if ((a[0]<1) || (a[0]>numDias(a[1], a[2])))
 				return false;
 	} else return false;
			
 	return true;
 }

	
 // -----------------------------------------------------------------
 // Nome: ValidaDataResumida
 // Parâmetro: strData - string representando uma data
 // Retorno: TRUE caso seja uma data resumida válida (dd/mm), FALSE caso contrário
 // -----------------------------------------------------------------
 function ValidaDataResumida(strData)
 {
 	strData = strData + "/2000";
 	if (!isDate(strData))
 		return false;
 	return true;
 }

 // -----------------------------------------------------------------
 // Nome: RetiraEspaco
 // Parâmetro: theString - string qualquer
 // Retorno: theString, formatada sem espaços
 // -----------------------------------------------------------------
 function RetiraEspaco(theString) 
 {
 	if (theString.indexOf(" ") >= 0) {
 		var i = 0;
 		while (theString.indexOf(" ") >= 0) {
 			if (theString.charAt(i) == " ") 
 				theString = theString.substring(0,i) + theString.substring(i+1,theString.length);
 			else i++
 		}
 		newString = theString;
 	} 
 	else newString = theString;
 	return newString;
 }

 // -----------------------------------------------------------------
 // Nome: numDias
 // Parâmetro:	intMes (inteiro representando um mês)
 //				intAno (inteiro representando um ano)
 // Retorno: número de dias de um mês em um ano qualquer
 // -----------------------------------------------------------------
 function numDias(intMes,intAno)	{
 	var Dias;
 	intMes = parseInt(intMes, 10);
 	intAno = parseInt(intAno, 10);
			
 	switch(intMes) {
 		case 1: 
 		case 3:
 		case 5:
 		case 7:
 		case 8:
 		case 10:
 		case 12: Dias = 31; break;
 		case 4:
 		case 6:
 		case 9:
 		case 11: Dias = 30;	break;
 		case 2:
 			Dias = 28;
 			if (((intAno%400)==0) || ((intAno%100)!=0 && (intAno%4)==0)) 
 				Dias++; 
 			break;
 		default:
 			Dias = 0;
 			alert("DATA DESCONHECIDA");
 	}
 	return Dias;
 }
		
 // -----------------------------------------------------------------
 // Nome: Vazio
 // Parâmetro: str (qualquer string)
 // Retorno: TRUE se existe algum valor, FALSE caso contrário
 // -----------------------------------------------------------------
 function Vazio(str) {
 	if (str == null || str == "")
 		return true;
 	return false;
 }
	
 // -----------------------------------------------------------------
 // Nome: ValidaNumero
 // Parâmetros:	t (número a ser testado)
 //				d (usar decimais ou nao)
 // Retorno: TRUE se é um número válido, FALSE caso contrário
 // -----------------------------------------------------------------
 function ValidaNumero(t,d) {
 	var i, sepused;
 	if (t == "")
 		return false;
 	sepused = false;
		
 	for (i=0;i<t.length;i++) {
 		if (Trim(t.substr(i,1)) == "" || (isNaN(t.substr(i,1)) && ((t.substr(i,1) != ",") || !d || sepused || i==0 || i==t.length-1)))
 		   return false;
 		if (t.substr(i,1) == ",")
 		   sepused = true;	
 	}
   return true;     
 }
	
 // -----------------------------------------------------------------
 // Nome: FormataHorario
 // Parâmetros: string contendo um horario (formatos h:mm, hh:mm)
 // Retorno: horario formatado (hh:mm)
 // -----------------------------------------------------------------
 function FormataHorario(lStrHorario){
		
 	a = lStrHorario.split(":");
 	if(a[0].length == 1)
 		a[0] = "0" + a[0];
		
 	lStrHorario = a[0] + ":" + a[1];
		
 	return lStrHorario;
 }

 // -----------------------------------------------------------------
 // Nome: ValidaHorario
 // Descricao: Valida hora, minuto, segundo
 // Parâmetros: string contendo um horario 
 // Retorno: TRUE, caso o horario esteja no formato [hh:mm] ou [hh:mm:ss]
 //			FALSE, caso contrário
 // -----------------------------------------------------------------
 function ValidaHorario(lStrHorario)
 {
 	var lHora, lMinuto, lSegundo, lPrimeiroSeparador, lSegundoSeparador
		
 	if (lStrHorario.length < 5){
 		return false
 	}
 	if (lStrHorario.length > 8){
 		return false
 	}
		
 	lHora = lStrHorario.substr(0, 2)
 	lPrimeiroSeparador = lStrHorario.substr(2, 1)
 	if (lPrimeiroSeparador != ':'){
 		return false
 	}
 	lMinuto = lStrHorario.substr(3, 2)
 	if (lStrHorario.length > 5){
 		lSegundoSeparador = lStrHorario.substr(5, 1)
 		if (lSegundoSeparador != ':'){
 			return false
 		}
 		lSegundo = lStrHorario.substr(6, 2)
 		if (lSegundo.length < 2){
 			return false
 		}
 	}
		
     //Valida Hora
     if (!(fJSIsNumber(lHora))){
 		return false
 	}
 	if (!(fJSInRange(lHora, 0, 23))){
 		return false
 	}
			
 	//Valida Minuto
 	if (!(fJSIsNumber(lMinuto))){
 		return false
 	}
 	if (!(fJSInRange(lMinuto, 0, 59))){
 		return false
 	}
			
 	//Valida Segundo
 	if (lStrHorario.length > 5){
 		if (!(fJSIsNumber(lSegundo))){
 			return false
 		}
 		if (!(fJSInRange(lSegundo, 0, 59))){
 			return false
 		}
 	}
 	return true
 }

 //Funcoes utilizadas para validação do horario
 function fJSInRange( inputStr, ini, fim ){
   var num = parseInt(inputStr, 10)
   if ( num < ini || num > fim ) {
      return false
   }
   return true
 }

 function fJSIsNumber( num ){
   var numeros = '0123456789,';
   var valor = num.toString();
   var lCount = 0;
	  
   for ( var i=0; i < valor.length; i++ )
   {
       if ( numeros.indexOf( valor.substr(i,1) ) == -1 ) 
       {
           return false
       }
	      
       if ( valor.substr(i,1) == ',' ) {
          lCount += 1
          if ( lCount > 1 ) { return false }
       }
   }
   return true
 }

 // -----------------------------------------------------------------
 // Nome: ValidaEmail
 // Parâmetros: string contendo um endereço de e-mail
 // Retorno: TRUE, se é um endereço de e-mail válido (segundo padrões de endereços de e-mails)
 //			FALSE, caso contrário
 // -----------------------------------------------------------------
 function ValidaEmail(str) {
 	//verifica se o e-mail digitado é válido 
 	var strAlfa = "ABCDEFGHIJKLMNOPQRSTUWVXYZ";
 	var strNum = "0123456789";
 	var strSpecial = "_.-@/";
 	var strValid = strAlfa + strNum + strSpecial;
 	var email = str.toUpperCase();
 	//verifica se os caracteres do e-mail são válidos
 	for (i=0; i<email.length; i++) {
 		if (strValid.indexOf(email.charAt(i)) < 0) {
 			return false;
 		}
 	}

 	var strC = "@."; 
 	//verifica se o e-mail contém @ e . (caracteres obrigatórios)
 	for (i=0; i<strC.length; i++) {
 		if (email.indexOf(strC.charAt(i)) < 0) 
 			return false;
 	}

 	if (email.indexOf("@") != email.lastIndexOf("@"))
 		return false;
 	if (email.indexOf("@") > email.lastIndexOf("."))
 	    return false;
 	if (email.charAt(email.indexOf("@") + 1) == ".")
 	    return false;
 	if (!(email.indexOf("@") != 0 && email.lastIndexOf(".") != email.length-1))
 		return false;
						
 	return true;
 }
		
 // -----------------------------------------------------------------
 // Nome: ValidaDinheiro
 // Parâmetros: string 
 // Retorno: TRUE, se a string é um valor em dinheiro
 //			FALSE, caso contrário
 // -----------------------------------------------------------------
 function ValidaDinheiro(strValue) 
 {
		
 	//verificando se os caracteres da string são válidos
 	var strDin = "0123456789.,";
 	for (i=0; i<strValue.length; i++) {
 		if (strDin.indexOf(strValue.charAt(i)) < 0)
 			return false;
 	}
	
 	//verifica se a vírgula está no lugar certo caso ela exista	
 	var arrDin = strValue.split(",");
 	if(arrDin.length != 1 && arrDin.length !=2)
 		return false;
 	else
 		if(arrDin.length == 2 && arrDin[1].length != 2)
 			return false;
		
 	//verifica se entre os pontos presentes na string
 	//existe um número mútiplo de três de algarismos
 	//Ex: "1.000", "1000.000", "1000000", "1.000.000.000" (corretos)
 	//Ex: "1.00000", "100.0000", "1.000.0000.00" (incorretos)
 	if(arrDin[0].indexOf(".") > 0)
 	{
 		var arrInt = arrDin[0].split(".");
 		var i;
 		for(i=1; i<arrInt.length; i++)
 			if( (arrInt[i].length % 3) != 0 )
 				return false;
 	}
			
			
 	return true;
 }
	
 // -----------------------------------------------------------------
 // Nome: InverteData
 // Parâmetros: string contendo data no formato [dd/mm/aa] ou [dd/mm/aaaa] 
 // Retorno: data no formato [aa/mm/dd] ou [aaaa/mm/dd]
 //
 // Obs.: Útil para comparaçoes (>,<) entre datas
 // -----------------------------------------------------------------
 function InverteData(strData){
 	var novadata, a;
		
 	a = strData.split("/");
 	novadata = a[2] + "/" +  a[1] + "/" + a[0] ;
 	return novadata;
 }
	
 // -----------------------------------------------------------------
 // Nome: RetiraEspacosLaterais
 // Parâmetros: string qualquer
 // Retorno: string sem espaços antes ou depois
 // -----------------------------------------------------------------
 function RetiraEspacosLaterais(theString) {
 	var aString = theString;
 	var newString = "";
 	var kBlank = " ";
 	if (aString.indexOf(kBlank) >= 0)  {
 		for (var i = 0; i < aString.length; i++)
 			if (aString.charAt(i) != kBlank)
 				break;
				
 		for (var j =  aString.length-1; j >= 0; j--)
 			if (aString.charAt(j) != kBlank)
 				break;
				
 		if (i == aString.length && j == -1)
 			newString = "";
 		else
 			if (i != 0 || j != aString.length -1)
 				newString = Trim(aString.substring(i, j+1));
 			else
 				newString = aString.charAt(i) + RetiraEspacosLaterais(aString.substring(i+1, j+1)) + aString.charAt(j+1);
 	}
 	else
 		newString = aString;
				
 	return newString;
 }
	
 // -----------------------------------------------------------------
 // Nome: ValidaCGC
 // Parâmetros: string respresentando um CGC
 // Retorno: TRUE se o CGC for válido, FALSE caso contrário
 // -----------------------------------------------------------------
 function ValidaCGC(strCGC) {
 	//verifica se o CGC é válido
 	var strvalid = "0123456789", i = 0;
 	//retira os caracteres que não forem números para aplicar o algoritmo
 	while (i < strCGC.length) {
 		if (strvalid.indexOf(strCGC.charAt(i)) < 0) {
 			strCGC = strCGC.substring(0,i) + strCGC.substring(i+1,strCGC.length)
 		} else i++;	
 	}
 	if (strCGC.length != 14) return false;
 	//teste do primeiro dígito
 	strserie = "543298765432", c1=0;
 	for (i=1; i < 13; i++) {
 		c1 += strCGC.charAt(i-1) * strserie.charAt(i-1);
 	}
 	c1 %= 11;
 	if (c1 < 2)
 		c1 = 0
 	else c1 = 11 - c1;
 	if (c1 != strCGC.charAt(12))
 		return false;
 	//teste do segundo dígito
 	strserie = "6543298765432", c1=0;
 	for (i=1; i < 14; i++) {
 		c1 += strCGC.charAt(i-1) * strserie.charAt(i-1);
 	}
 	c1 %= 11;
 	if (c1 < 2)
 		c1 = 0
 	else c1 = 11 - c1;
 	if (c1 != strCGC.charAt(13))
 		return false;
		
 	return true;		
 } //29.010.519/0001-32
	
 // -----------------------------------------------------------------
 // Nome: FormataCGC
 // Parâmetros: string representando um CGC válido
 // Retorno: string representando um CGC válido e formatado, com os pontos, a barra e o traco
 // -----------------------------------------------------------------
 function FormataCGC(strCGC){
 	var strvalid = "0123456789", i = 0, strFormatado = "";
 	//retira os caracteres que não forem números para aplicar o algoritmo
 	while (i < strCGC.length) {
 		if (strvalid.indexOf(strCGC.charAt(i)) < 0) {
 			strCGC = strCGC.substring(0,i) + strCGC.substring(i+1,strCGC.length)
 		} else i++;	
 	}
		
 	for(i=0; i<2; i++)
 		strFormatado += strCGC.charAt(i);
			
 	strFormatado += ".";
			
 	for(i=2; i<5; i++)
 		strFormatado += strCGC.charAt(i);
		
 	strFormatado += ".";
		
 	for(i=5; i<8; i++)
 		strFormatado += strCGC.charAt(i);
		
 	strFormatado += "/";
		
 	for(i=8; i<12; i++)
 		strFormatado += strCGC.charAt(i);
		
 	strFormatado += "-";
		
 	for(i=12; i<14; i++)
 		strFormatado += strCGC.charAt(i);
			
 	return strFormatado;		
 }
	
 // -----------------------------------------------------------------
 // Nome: ValidaNumero
 // Parâmetros: string representando um número
 // Retorno: TRUE caso represente um número inteiro, FALSE caso contrário
 // -----------------------------------------------------------------
 function ValidaNumero(strTexto)
 {
 	//Obs.: utiliza a função Vazio
		
 	if (Vazio(strTexto)) 
 		return false;
 	var strNum = "0123456789";
		
 	for (var i=0; i < strTexto.length; i++) {
 		if (strNum.indexOf(strTexto.charAt(i)) < 0)
 			return false;			
 	}
 	return true;
 }
	
 // -----------------------------------------------------------------
 // Nome: ValidaCEP
 // Parâmetros: string representando um CEP
 // Retorno: TRUE caso represente um CEP válido, apenas com números e "-", FALSE caso contrário
 // -----------------------------------------------------------------
 function ValidaCEP(cep)
 {	
 	var i, strCEP = "0123456789";
		
 	if(cep.length != 9)
 		return false;
		
 	for (i=0; i<5; i++)
 	{
 		if ( strCEP.indexOf(cep.charAt(i)) < 0 )
 			return false;
 	}
 	if ( (strCEP.indexOf(cep.charAt(i)) >= 0 && cep.length != 8) || (cep.charAt(i) == "-" && cep.length != 9) || (cep.charAt(i) != "-" && strCEP.indexOf(cep.charAt(i)) < 0) )
 		return false;
				
 	for (++i; i<cep.length; i++)
 	{
 		if ( strCEP.indexOf(cep.charAt(i)) < 0 )
 			return false;
 	}
		
 	return true;
 }
	
 // -----------------------------------------------------------------
 // Nome: FormataCEP
 // Parâmetros: string representando um CEP válido, já testado
 // Retorno: string representando um CEP válido e formatado, com o traço
 // -----------------------------------------------------------------
 function FormataCEP(strCEP)
 {
 	var strvalid = "0123456789", i = 0, strFormatado = "";
 	//retira os caracteres que não forem números para aplicar o algoritmo
 	while (i < strCEP.length) {
 		if (strvalid.indexOf(strCEP.charAt(i)) < 0) {
 			strCEP = strCEP.substring(0,i) + strCEP.substring(i+1,strCEP.length)
 		} else i++;	
 	}
		
 	for(i=0; i<5; i++)
 		strFormatado += strCEP.charAt(i);
			
	if(strCEP.length >= 5)
 		strFormatado += "-";
		
 	for(i=5; i<strCEP.length; i++)
 		strFormatado += strCEP.charAt(i);
			
 	return strFormatado;		
 }
	
 // -----------------------------------------------------------------
 // Nome: VerificaNumero
 // Parâmetros:	num (numero)
 //				e	(numero de casa a esquerda da virgula)
 //				d	(numero de casa a direita da virgula)
 // Retorno: TRUE se estiver correto, FALSE caso contrário
 // -----------------------------------------------------------------
 function VerificaNumero(num, e, d){
 	var aux, retorno;
		
 	retorno = true;
		
 	//aux = new Array();
 	aux = num.split(",");
		
 	if(aux[0].length > e)
 		retorno = false;
				
 	if(aux.length > 1){
 		if(aux[1].length > d)
 			retorno = false;
 	}
		
 	return retorno;
 }
	
	
 // -----------------------------------------------------------------
 // Nome: ValidaBusca
 // Parâmetros: strBusca (string digitada no campo de Busca)
 // Retorno: TRUE se for um string válida, FALSE caso contrário
 // -----------------------------------------------------------------
 function ValidaBusca(strBusca)
 {
 	var strvalid = "0123456789 ABCDEFGHIJKLMNOPQRSTUVXYZ().-,;", i = 0, strFormatado = "";
 	strBusca = Trim(strBusca);
 	strBusca = strBusca.toUpperCase();
				
 	//retira os caracteres que não forem números para aplicar o algoritmo
 	while (i < strBusca.length)
 	{
 		if (strvalid.indexOf(strBusca.charAt(i)) < 0)
 			return false;
 		else
 			i++;
 	}
		
 	return true;
 }	
	

 // -----------------------------------------------------------------
 // Nome: ValidaCPF
 // Parâmetro: strCPF (string representando um CPF)
 // Retorno: ??? se a string representar um CPF válido, ??? caso contrário
 // -----------------------------------------------------------------
 function ValidaCPF(strCPF){
 	if ((strCPF.length <11) || (strCPF.length >14)){
 		 return(1);
 		 }  
 	else{  
 	strCor='';
 	for (i=0;i<strCPF.length;i++){
 		if ((strCPF.charAt(i)>='0')&&(strCPF.charAt(i)<='9')){
 			  strCor = strCor + strCPF.charAt(i);
 				}
 			}    
 	if (strCor.length != 11)
 	 return(1);
 	else{
 		cv = 0;
 		for (i=0;i<9;i++){
 		  cv = cv + strCor.charAt(i)*(i+1);
 		 }
 	cv = cv%11;
 	if (cv==10) 
 		 cv = 0;
 	 if ( cv != strCor.charAt(9))
 		return(2);
 		cv = 0;
 		for (i=0;i<9;i++){
 		cv = cv + strCor.charAt(i+1)*(i+1);
 		}
 	cv = cv%11;
 	if (cv==10) 
     cv = 0;
 	if ( cv != strCor.charAt(10))
 	 return(2);
 		}  
 	}  
  return true;  
}
   
function formatNumberTrunc(n,d)
 {
 	var i,c,s,z,r;
 	if (n==0) n = "0"
 	r = "";
 	c = 0;
 	s = false;
 	z = "0000000000";
 	if (Bad_Number(n,1)) return r;
 	n = n.toString();
 	if (d>10) d = 10;
 	if (d<0) d = 0;
     for (i=0;i<n.length;i++) {
         if (s) c++;
         if (c>d) return r;
 	    if (n.substr(i,1)=="." || n.substr(i,1)==","){
 	       s = true;
 	       if (d>0) r += ",";
 	    }   
 	    else r += n.substr(i,1);
 	}
 	if (c<d) {
 	   if (!s) r += ",";
 	   r += z.substr(0,d-c);
 	}   
 	return r;
 }
   
	//Funcao que coloca os ':' no horario
 function FormataHorario(index,evento,form) {
 	var tecla = evento.keyCode;
 	vr = form[index].value;
 	vr = vr.replace( ".", "" );
 	vr = vr.replace( ".", "" );
 	vr = vr.replace( ":", "" );
 	vr = vr.replace( ":", "" );
 	tam = vr.length + 1;
 	if (((tecla >= 48) && (tecla <= 57)) || ((tecla == 9) || (tecla == 8))){
 		if ( tecla != 9 && tecla != 8 ){
 			if ( tam == 3 )
 				form[index].value = vr.substr( 0, tam - 1  ) + ':' + vr.substr( tam - 1, tam );
 		}		
 	}
 	else{
 		evento.returnValue = false;
 	}
 }

 //Funcao que coloca as '/' na data
 function FormataData(index,evento,form) {
 	var tecla = evento.keyCode;
 	vr = form[index].value;
 	vr = vr.replace( ".", "" );
 	vr = vr.replace( ".", "" );
 	vr = vr.replace( "/", "" );
 	vr = vr.replace( "/", "" );
 	tam = vr.length + 1;
 	if (((tecla >= 48) && (tecla <= 57)) || ((tecla == 9) || (tecla == 8))){
 		if ( tecla != 9 && tecla != 8 ){
 			if ( tam == 3 )
 				form[index].value = vr.substr( 0, tam - 1  ) + '/' + vr.substr( tam - 1, tam );
 			if ( tam > 3 && tam < 5 )
 				form[index].value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
 			if ( tam >= 5 && tam <= 10 )
 				form[index].value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
 		}		
 	}
 	else{
 		evento.returnValue = false;
 	}
 }
 
//-------------------------------------------------------------------
//	Função que seleciona todos os checkboxes
//	Parâmetros: o objeto checkbox
//-------------------------------------------------------------------
 
 function SelecionaTudo(CheckBox){		
	var obj = eval(CheckBox);
	if(obj)
	{
		if (obj.length) {
			for (i = 0; i < obj.length; i++) {
				obj[i].checked = true; }
		}else{
			obj.checked = true;
		}
	}
}

//==============================================================
//	Nome:		FaleConosco()
//	Descrição:	Redireciona para o formulário do fale conosco
//==============================================================

function FaleConosco() {
	document.FaleConosco.submit();
}


/*
******************************************************************************
 Descrição: Suprime os espaços em branco à esquerda da string
******************************************************************************
*/
function LTrim(strInput)
{
	var strOutput;
	
	if (strInput.substr(0,1) == ' ')
		for (var i = 0; i <= strInput.length; i++)
		{
			if (strInput.substr(i, 1) == ' ')
				strOutput = strInput.substr(i + 1, strInput.length);
			else
				break
		}
	else
		strOutput = strInput;
		
	return strOutput;
}

/*
******************************************************************************
 Descrição: Suprime os espaços em branco à direita da string
******************************************************************************
*/
function RTrim(strInput)
{
	var strOutput;
	
	if (strInput.substr(strInput.length - 1,1) == ' ')
		for (var i = strInput.length - 1; i >= 0; i--)
		{
			if (strInput.substr(i, 1) == ' ')
				strOutput = strInput.substr(0, i);
			else
				break
		}
	else
		strOutput = strInput;
		
	return strOutput;
}

/*
******************************************************************************
 Descrição: Suprime os espaços em branco à direita e à esquerda da string
******************************************************************************
*/
function Trim(strInput)
{
	var strOutput;
	
	strOutput = LTrim(strInput);
	strOutput = RTrim(strOutput);
	return strOutput;
}


//******************************************************************************
//	Nome: MoveOpcoesDePara
//	Parâmetros: fonte, destino
//	Descrição: move as opções selecionadas de um SELECT para outro
//******************************************************************************

function MoveOpcoesDePara(fonte, destino)
{
	if(document.Cadastro[fonte])
	{
		SelectFonte = document.Cadastro[fonte];
	}
	else
	{
		if(document.all[fonte])
		{
			SelectFonte = document.all[fonte];
		}
		else
		{
			alert("Não foi possível encontrar a Fonte");
			return false;
		}
	}
	if(document.Cadastro[destino])
	{
		SelectDestino = document.Cadastro[destino];
	}
	else
	{
		if(document.all[destino])
		{
			SelectDestino = document.all[destino];
		}
		else
		{
			alert("Não foi possível encontrar o Destino");
			return false;
		}
	}
	if(SelectFonte.selectedIndex >= 0)
	{
		x = SelectFonte.selectedIndex;
		while(x >= 0)
		{					
			if (SelectFonte.options[x].value != "")
			{
				opcao = new Option;
				opcao.value	= SelectFonte.options[x].value;
				opcao.text	= SelectFonte.options[x].text;
				SelectFonte.remove(SelectFonte.selectedIndex);
				SelectDestino.add(opcao);					
			}
			x = SelectFonte.selectedIndex;
		}
	}
	else
	{
		alert("Selecione um ou mais item!");
	}
}
//******************************************************************************
//	Nome: MoveOpcoes
//	Parâmetros: fonte
//	Descrição: move as opções selecionadas de um SELECT
//******************************************************************************

function MoveOpcoes(fonte, opcao)
{
	if(document.Cadastro[fonte])
	{
		SelectFonte = document.Cadastro[fonte];
	}
	else
	{
		if(document.all[fonte])
		{
			SelectFonte = document.all[fonte];
		}
		else
		{
			alert("Não foi possível encontrar a Fonte");
			return false;
		}
	}
	if(SelectFonte.selectedIndex >= 0)
	{
		x = SelectFonte.selectedIndex;
		SelectFonte.options[x].selected = false;
		if( SelectFonte.selectedIndex >= 0)
		{
			SelectFonte.options[x].selected = true;
			alert("Selecione somente um item!");
		}
		else
		{
			switch(opcao)
			{
				case 'sobe':
					if(x > 0)
					{
						opcao = new Option;
						opcao.value	= SelectFonte.options[x-1].value;
						opcao.text	= SelectFonte.options[x-1].text;
						SelectFonte.remove(x-1);
						SelectFonte.add(opcao, x);
						SelectFonte.options[x-1].selected = true;
					}
					else
					{
						SelectFonte.options[x].selected = true;
					}
					break;
				case 'desce':
					if(SelectFonte.options[x+1] && SelectFonte.options[x+1].value != "") {
						opcao = new Option;
						opcao.value	= SelectFonte.options[x+1].value;
						opcao.text	= SelectFonte.options[x+1].text;
						SelectFonte.remove(x+1);
						SelectFonte.add(opcao, x);
						SelectFonte.options[x+1].selected = true;
					}
					else
					{
						SelectFonte.options[x].selected = true;
					}
					break;
			}
		}
	}
	else
	{
		alert("Selecione um ou mais item!");
	}
}
// -----------------------------------------------------------------
//	Nome:		AbreAgenda
//	Parâmetros:	iCodigo = codigo do evento a ser exibido
//	Descrição:	abre o popup com os dados do evento
// -----------------------------------------------------------------
function AbreAgenda(iCodigo)
{
	AbreJanela(DirConteudo + "agenda/popup_agenda.asp?cod_agenda=" + iCodigo, 700, 650, "yes", "no", "yes");
}

// -----------------------------------------------------------------
// Nome: DeletaImagem
// Parâmetros: item = tipo de Imagem a ser excluido
// Descrição: deleta uma imagem
// -----------------------------------------------------------------
function DeletaImagem(item)
{
	if(confirm("Você tem certeza que deseja deletar esta imagem?")) {
		f1 = eval("document.Cadastro.nCod"+item)
		f1.value = ""	
		f2 = eval("document.all.tdNome"+item)
		f2.innerHTML = "Nenhuma Imagem Selecionada"
		f3 = eval("document.Cadastro.btn"+item)
		f3.value = "escolher imagem"
		f4 = eval("document.all.divDeleta"+item)
		f4.style.display = "none"
	}
}

// -----------------------------------------------------------------
// Nome: AbreRelatorio
// Parâmetros:	pagina = nome da página a ser aberta
//				strWidth = tamanho horizontak da janela
//				strHeight = tamanho vertical da janela
//				popupname = nome do popup
// Descrição: abre uma janela para o relatório do crystal ( Armazém de  Boas Práticas Mineiras )
// -----------------------------------------------------------------
function abreRelatorio(pagina, strWidth, strHeight, popupname)
{
	if(!strWidth)
		strWidth = "400";
	
	if(!strHeight)
		strHeight = "400";
	
	if (!popupname)
		popupname = "Popup"
		
	var Wnd = window.open(pagina,popupname,"fullscreen=yes,toolbar=no,status=yes,location=no,directories=no,scrollbars=yes,resizable=yes,copyhistory=no,width="+strWidth+",height="+strHeight);
	Wnd.focus();
	return false;
}

// -----------------------------------------------------------------
// Nome: ValidaPeriodo
// Parâmetros:	sDatPortInicio = data inicial em portuques
//				sDatPortFim = data final em portuques

// Descrição: Retorna true se a data final é maior que a inicial
// -----------------------------------------------------------------
function ValidaPeriodo(sDatPortInicio, sDatPortFim)
{
	var arrInicio = sDatPortInicio.split("/");
	var arrFim = sDatPortFim.split("/");
	
	var dInicio = new Date(arrInicio[2], arrInicio[1], arrInicio[0]);
	var dFim = new Date(arrFim[2], arrFim[1], arrFim[0]);
	
	if (dInicio > dFim )
		return false
	else
		return true
}

// Validação do textarea
function validaTextArea(oTextArea,nTamanho)
	{
		if (oTextArea.value.length>nTamanho)
			{
				alert("Este campo permite no máximo "+ nTamanho +" caracteres")
				oTextArea.value = oTextArea.value.slice(0,oTextArea.value.length-(oTextArea.value.length-nTamanho))
			}
	}

// Mouse Over, ao passar o mouse sobre os itens da Barra esquerda	
function mOvr(src,clrOver) 
{
	if (!src.contains(event.fromElement)) 
	{  
		src.bgColor = clrOver;  
	}  
}  

// Mouse Out, ao passar o mouse sobre os itens da Barra esquerda
function mOut(src,clrIn) 
{  
	if (!src.contains(event.toElement)) 
	{  
		src.bgColor = clrIn;  
	}  
}

// -----------------------------------------------------------------
//	Nome:		abreConteudo(pagina)
//	Parâmetros:	pagina
//	Descrição:	abre a página de conteúdos com o iframe com a página passada por parametro
// -----------------------------------------------------------------
function abreConteudo(pagina,codigo) {
	var f = top.document.frmConteudo;
	if (top.ifrmConteudo){
		//top.ifrmConteudo.document.location.href = pagina;
		f.action = pagina;
		f.target = "ifrmConteudo";
	}
	f.pagina.value = pagina;
	f.codigo.value = codigo;
	f.submit();
}