function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}


function exibirOcultarBusca() {
	if(document.getElementById('busca_avancada').style.display != 'block') {
		document.getElementById('busca_avancada').style.display = 'block'
		document.getElementById('busca_avancada_aberta').value = '1'
		_disabled = false;
	} else {
		document.getElementById('busca_avancada').style.display = 'none'
		document.getElementById('busca_avancada_aberta').value = '0'
		_disabled = true;
	}
	// DESABILITAR CAMPOS:
	for(i=0; i<exibirOcultarBusca.arguments.length; i++) {
		nome_campo = exibirOcultarBusca.arguments[i];
		document.getElementById(nome_campo).disabled = _disabled;
	}
}

// ATUALIZAÇÃO DA LISTAGEM DEPOIS DO AJAX:
function atualizarPagina() {
	if(typeof(preloaderPagina) == 'object') {
		preloaderPagina.exibir();
	}
	document.location.reload();
}
// FUNÇÃO ACIONADA QUANDO O CHECKBOX DE EXCLUSÃO DE IMAGEM É ACIONADO, EM PÁGINAS DE CADASTRO:
function ativarDesativarImagem() {
	if(document.getElementById('excluir_imagem').checked) {
		// PRA IE:
		document.getElementById('img_imagem').style.filter = 'alpha(opacity=30)';
		// PRA FIREFOX:
		document.getElementById('img_imagem').style.opacity = '.3';
	} else {
		// PRA IE:
		document.getElementById('img_imagem').style.filter = 'alpha(opacity=100)';
		// PRA FIREFOX:
		document.getElementById('img_imagem').style.opacity = '1';
	}
}

function limitarCaracteresCampo(id_elemento, numero_caracteres) {
	qtd_atual = document.getElementById(id_elemento).value.length;
	if(qtd_atual > numero_caracteres) {
		document.getElementById(id_elemento).value = document.getElementById(id_elemento).value.substr(0, numero_caracteres);
	}
	temp = id_elemento + '_relatorio_caracteres';
	if(document.getElementById(temp)) {
		relatorio = '';
		if(qtd_atual < numero_caracteres) {
			relatorio = qtd_atual + ' caracteres utilizados (máximo: ' + numero_caracteres + ')';
		} else {
			relatorio = '<strong style="color: #990000">O texto já atingiu o máximo de ' + numero_caracteres + ' caracteres.</strong>';
		}
		document.getElementById(id_elemento + '_relatorio_caracteres').innerHTML = relatorio;
	}
}


styleDisplay = Array();
function exibirOcultar(nome_div, modo_visivel) {
	if(document.getElementById(nome_div).style.display != 'none') {
		styleDisplay[nome_div] = document.getElementById(nome_div).style.display;
		document.getElementById(nome_div).style.display = 'none'
	} else {
		if(!modo_visivel) {
			modo_visivel = 'block';
		}
		if(!styleDisplay[nome_div]) {
			styleDisplay[nome_div] = modo_visivel;
		}
		document.getElementById(nome_div).style.display = styleDisplay[nome_div];
	}
}

function formatarStringParaSistema(texto) {
	// transforma uma string "EXEMPLO: textão com ceçedilha" em "exemplo_textao_com_cecedilha"

	texto = texto.toLowerCase();

	underlines = Array(' ', '-', '\!', '\\?', '\\.', ':', '\\\'', '\\/', '\\(', '\\)', '\\+', '\\=', '@', '_____', '____', '___', '__')
	vazios = Array('~', '´', '`', '^', '¨', ',', '\\"', '\\(', '\\)', '\\%', '\\$')
	
	// RETIRAR CARACTERES:
	for(i=0; i<vazios.length; i++) {
		eval("texto = texto.replace(/" + vazios[i] + "/g, '_'); ");
	}
	// TROCAR CARACTERES POR UNDERLINE
	for(i=0; i<underlines.length; i++) {
		eval("texto = texto.replace(/" + underlines[i] + "/g, '_'); ");
	}
	
	// LETRAS COM ACENTOS:
	texto = texto.replace(/á/g, 'a');
	texto = texto.replace(/à/g, 'a');
	texto = texto.replace(/â/g, 'a');
	texto = texto.replace(/ã/g, 'a');
	texto = texto.replace(/ä/g, 'a');
	
	texto = texto.replace(/é/g, 'e');
	texto = texto.replace(/è/g, 'e');
	texto = texto.replace(/ê/g, 'e');
	texto = texto.replace(/ë/g, 'e');
	texto = texto.replace(/ë/g, 'e');
	
	texto = texto.replace(/í/g, 'i');
	texto = texto.replace(/ì/g, 'i');
	texto = texto.replace(/î/g, 'i');
	texto = texto.replace(/ï/g, 'i');
	
	texto = texto.replace(/ó/g, 'o');
	texto = texto.replace(/ò/g, 'o');
	texto = texto.replace(/ô/g, 'o');
	texto = texto.replace(/õ/g, 'o');
	texto = texto.replace(/ö/g, 'o');

	texto = texto.replace(/ú/g, 'u');
	texto = texto.replace(/ù/g, 'u');
	texto = texto.replace(/û/g, 'u');
	texto = texto.replace(/ü/g, 'u');

	texto = texto.replace(/ç/g, 'c');

	texto = texto.replace(/&/g, 'e');
	
	// RETIRAR UNDERLINE DO INÍCIO E FIM:
	if(texto.charAt(0) == '_') {
		texto = texto.substr(1);
	}
	if(texto.charAt(texto.length-1) == '_') {
		texto = texto.substr(0, texto.length-1);
	}
	return texto;
}

// =========================================================================
// LOGOUT AJAX: ============================================================
// =========================================================================
function requisitarLogout() {
	modo_debugger_ajax = false;
	url = ARQUIVO_PROCESSAMENTO_GERAL_AJAX;
	parametros = 'acao=deslogar&nome_dado=pessoa'
	objetoRequisicaoDados = new requisicaoDados(url, parametros, resultadoLogout, cancelarAjax, 'preloader_logout', '');
}
function resultadoLogout() {
	if(resultado_ajax == "sucesso") {
		if(typeof(preloaderPagina) == 'object') {
			preloaderPagina.exibir();
		}
		setTimeout('document.location = "' + RAIZ_SITE + 'index.php"; ', 500);
	} else {
		alert('Erro interno ao tentar sair do sistema.');
	}
}


// =========================================================================
// EXCLUSÃO AJAX: ==========================================================
// =========================================================================
if(typeof(resultadoExclusao) == 'undefined') {
	var resultadoExclusao;
}
function requisitarExclusao(nome_dado, id, pergunta_confirmacao_exclusao, id_div_preloader, resultadoExclusao) {
	// CONFIRMAR EXCLUSÃO: 
	if(!pergunta_confirmacao_exclusao) {
		pergunta_confirmacao_exclusao = 'Deseja realmente excluir permantentemente este cadastro?';
	}
	confirmacao = confirm(pergunta_confirmacao_exclusao);
	
	if(confirmacao) {
		document.getElementById(id_div_preloader).style.display = 'block';
		// FUNÇÃO DE RESULTADO, CASO NÃO TENHA SIDO ESPECIFICADO:
		if(typeof(resultadoExclusao) != 'function') {
			resultadoExclusao = function() {
				if(resultado_ajax == 'sucesso') {
					if(typeof(preloaderPagina) == 'object') {
						preloaderPagina.exibir();
					}
					document.location = 'index.php';
				} else {
					alert('Erro interno na exclusão.');
				}
			}
		} 
		// EXECUTAR AJAX:
		modo_debugger_ajax = false;
		url = ARQUIVO_PROCESSAMENTO_GERAL_AJAX;
		parametros = 'acao=excluir&nome_dado=' + nome_dado + '&' + nome_dado + '=' + id;
		objetoRequisicaoDados = new requisicaoDados(url, parametros, resultadoExclusao, cancelarAjax, id_div_preloader, '');
	}
}

// ==================================================================================
// MUDANÇA DE STATUS AJAX: ==========================================================
// ==================================================================================
if(typeof(resultadoMudancaStatus) == 'undefined') {
	var resultadoMudancaStatus;
}
function requisitarAlteracaoStatus(nome_dado, id, id_div_preloader, resultadoMudancaStatus, status) {
	document.getElementById(id_div_preloader).style.display = 'block';
	// FUNÇÃO DE RESULTADO, CASO NÃO TENHA SIDO ESPECIFICADO:
	if(typeof(resultadoMudancaStatus) != 'function') {
		resultadoMudancaStatus = function() {
			if(resultado_ajax == 'sucesso') {
				if(typeof(preloaderPagina) == 'object') {
					preloaderPagina.exibir();
				}
				document.location = 'index.php';
			} else {
				alert('Erro interno na alteração de status.');
			}
		}
	}
	// EXECUTAR AJAX:
	modo_debugger_ajax = false;
	url = ARQUIVO_PROCESSAMENTO_GERAL_AJAX;
	parametros = 'acao=alterar_status&nome_dado=' + nome_dado + '&' + nome_dado + '=' + id + '&status=' + status;
	objetoRequisicaoDados = new requisicaoDados(url, parametros, resultadoMudancaStatus, cancelarAjax, id_div_preloader, '');
}

// ==================================================================================
// ENVIO DE LOGIN: ==================================================================
// ==================================================================================
function requisitarEnvioLogin(nome_dado, id, email, id_div_preloader, resultadoEnvioLogin, primeiro_envio_login_senha) {

	// CONFIRMAR ENVIO:
	_email = (email ? email : 'o e-mail cadastrado');
	confirmacao = confirm('Deseja enviar login e senha para ' + email + '?');
	if(!confirmacao) {
		return false;
	}

	document.getElementById(id_div_preloader).style.display = 'block';
	// FUNÇÃO DE RESULTADO, CASO NÃO TENHA SIDO ESPECIFICADO:
	if(typeof(resultadoEnvioLogin) != 'function') {
		resultadoEnvioLogin = function() {
			if(resultado_envio_login_senha == 'sucesso') {
				alert("Nome de usuário e senha enviados para " + email_destinatario + ".");
			} else {
				alert('Houve algum erro ao tentar enviar o nome de usuário e senha. \nIsso pode ser ocasionado por instabilidade na conexão da internet, congestionamento no servidor de e-mail ou endereço de e-mail digitado incorretamente durante o cadastro. Confira o e-mail e tente novamente.');
			}
		}
	}
	// EXECUTAR AJAX:
	modo_debugger_ajax = false;
	url = ARQUIVO_PROCESSAMENTO_GERAL_AJAX;
	parametros = 'acao=enviar_login_senha&nome_dado=' + nome_dado + '&' + nome_dado + '=' + id + '&primeiro_envio_login_senha=' + (primeiro_envio_login_senha ? '1' : '0');
	objetoRequisicaoDados = new requisicaoDados(url, parametros, resultadoEnvioLogin, cancelarAjax, id_div_preloader, '');
}


// ==================================================================================
// VERIFICACAO DE LOGIN E E-MAIL: ===================================================
// ==================================================================================

function requisitarVerificacaoLoginEmail(nome_dado, id, id_div_preloader) {
	email = document.getElementById(nome_dado + '_email').value;
	login = document.getElementById('usuario_sistema_login').value;
	document.getElementById('formulario').style.display = 'none';
	// EXECUTAR AJAX:
	modo_debugger_ajax = false;
	url = RAIZ_SITE + "biblioteca/processamento.php";
	parametros = 'acao=verificar_existencia_login_email&nome_dado=' + nome_dado + '&' + nome_dado + '=' + idLogado() + '&' + NIVELACESSO + '_email=' + email + '&usuario_sistema_login=' + login;
	_funcao = new Function( 'resultadoVerificacaoLoginEmail("' + nome_dado + '"); ');
	objetoRequisicaoDados = new requisicaoDados(url, parametros, _funcao, cancelarVerificacaoLoginEmail, id_div_preloader, '');
}
function cancelarVerificacaoLoginEmail() {
	cancelarAjax();
	document.getElementById('formulario').style.display = 'block';
}
function resultadoVerificacaoLoginEmail(nome_dado) {
	if(resultado_ajax == 'login_existente') {
		alert('Este login já está cadastrado para outra pessoa.');
		// EXIBIR FORMULARIO:
		document.getElementById('formulario').style.display = 'block';
		document.getElementById('usuario_sistema_login').select();
		document.getElementById('usuario_sistema_login').focus();
	} else if(resultado_ajax == 'email_existente') {
		alert('O e-mail digitado já está cadastrado no nome de ' + nome + '.\nInsira outro e-mail.');
		// EXIBIR FORMULÁRIO E SELECIONAR E-MAIL:
		document.getElementById('formulario').style.display = 'block';
		document.getElementById(nome_dado + '_email').select();
		document.getElementById(nome_dado + '_email').focus();
	} else if(resultado_ajax == 'aprovado') {
		setTimeout("document.getElementById('formulario').submit(); ", 500);
	} else {
		alert('Erro no processamento. Tente novamente mais tarde.');
	}
}


// ==================================================================================
// LOGAR COMO USUÁRIO: ==============================================================
// ==================================================================================
function requisitarLogarComo(nome_dado, id, id_div_preloader, nome) {

	// CONFIRMAR ENVIO: 
	frase_confirmacao_login = 'Deseja logar como se você fosse ';
	frase_confirmacao_login += (nome ? nome+'?' : 'este(a) usuário(a)?');
	confirmacao = confirm(frase_confirmacao_login);

	// EXECUTAR AJAX:
	if(confirmacao) {
		modo_debugger_ajax = false;
		url = RAIZ_SITE + "biblioteca/processamento.php";;
		parametros = 'acao=logar_como&nome_dado=' + nome_dado + '&' + nome_dado + '=' + id;
		objetoRequisicaoDados = new requisicaoDados(url, parametros, resultadoLogarComo, cancelarAjax, id_div_preloader, '');
	}
}
function resultadoLogarComo() {
	if(resultado_logar_como == 'sucesso') {
		pagina_resultado_login = (RAIZ_SITE != '' ? RAIZ_SITE : './');
		document.location = pagina_resultado_login;
	} else {
		alert('Houve algum erro ao tentar logar como ' + nome + '.');
		window.location.reload();
	}
}



// GRAVA COOKIE DE CHECKBOX NO onsubmit DO FORMULARIO
function setarCookieCheckboxBusca(id_checkbox) {
	objDate = new Date();
	_time = objDate.getTime();
	expiracao = _time + (60*60*24*30*12);
	valor = (document.getElementById(id_checkbox).checked ? '1' : '0');
	setcookie('busca_' + id_checkbox, valor, expiracao); 
}

