// -----------------------------------------------
// AJAX
// url - pagina a ser chamada pelo ajax
// ret - div ou span que recebera a resposta do ajax
// par - parametro(s) que sera(o) enviado(s) à url pelo ajax
//
// Esta função apresenta 2 problemas:
//
// 1o) Não executa javascript das páginas que vem do ajax
// 2o) Se executar 2 ou mais ajax juntos, ele só executa o último
//
// --------------------------------------------------
var retorno;	// variavel global - aparece em todas as funcoes
function ajax(url, ret, par)
{
	// atribui a variavel global 'retorno' o valor do parametro 'ret'
	retorno = ret;
	
	// -------------------------------------------						
	// CRIA O OBJETO DA REQUISICAO
	// -------------------------------------------
	// verifica se existe o objeto XMLHttpRequest - firefox, ie 7
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	}
	else
		// verifica se existe o objeto ActiveXObject - ie 5, ie 6
		if (window.ActiveXObject) {
			try {
				req = new ActiveXObject("Msxml2.XMLHTTP");	// ie 6
			}
			catch(e) {
				try {
					req = new ActiveXObject("Microsoft.XMLHTTP");	// ie 5
				}
				catch(e) {
					alert('Seu browser não suporta Não foi possível criar Requisição');
				}
			}
		}
		
	// cada vez que alterar o status, chama a funcao resultado
	// status = 0 --> nao inicializada, 1 --> carregando,
	//			2 --> carregada, 3 --> processando, 4 -->pronto
	req.onreadystatechange = resultado;
	// req.open (METODO, PAGINA, ASSINCRONO);
	req.open('POST', url, true);
	// deve ser utilizado quando o metodo é POST
	req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	// envia a requisicao
	req.send(par);
}

function resultado()
{
	// status = 4 --> pronto
	if (req.readyState == 4) {
		esconde_carregando();
		// 200 --> pagina ok, 404 --> pagina nao encontrada
		// 403 --> forbiden (proibida), 500 --> erro interno
		if (req.status == 200) {
			// req.responseText --> retorno do ajax
			document.getElementById(retorno).innerHTML = req.responseText;  //esse valor vem no formato texto padrão... só texto!
			//alert(req.responseText);
		}
		else {
			alert('Erro de AJAX. Erro:'+req.status);
		}
	}
	else
	// status = 0 --> nao inicializada, 1 --> carregando,
	//			2 --> carregada, 3 --> processando
		mostra_carregando();
}
// -----------------------------------------------------------------------
// CRIA E APRESENTA DIV 'CARREGANDO' ESTILO GMAIL
// -----------------------------------------------------------------------
function mostra_carregando()
{
	// verifica se existe o elemento
	if (!document.getElementById('carregando'))
	{
		// cria elemento dinamicamente
		tag = document.createElement('div');
		// seta propriedades
		tag.id = 'carregando';
		tag.style.position = 'absolute';//pode ter posição relativa
		tag.style.top = '0';
		tag.style.right = '0';
		tag.style.backgroundColor = '#FF0000';
		tag.style.color = '#FFFFFF';
		tag.innerHTML = '<img src=loader.gif />';
		// insere no documento
		document.body.appendChild(tag);
	}
}
// -----------------------------------------------------------------------
// REMOVE DIV 'CARREGANDO'
// -----------------------------------------------------------------------
function esconde_carregando()
{
	// verifica se existe o elemento
	if (document.getElementById('carregando'))
		// remove do documento
		document.body.removeChild(document.getElementById('carregando'));
}









/*********************************************/
function MakeObjectHttp(){
    var objAjax;
    if ( window.XMLHttpRequest ) {
        objAjax = new XMLHttpRequest();
    }else if ( window.ActiveXObject ){
        try {
            objAjax = new ActiveXObject('Msxml2.XMLHTTP');
        }catch(e1){
            try{
                objAjax = new ActiveXObject('Microsoft.XMLHTTP');
            }catch(e2){
                alert('Seu IE não suporta AJAX');
                return false;
            }
        }
    }else{
        alert('Seu browser não da suporte ao AJAX')	;
        return false;
    }
    return objAjax;
}
/******************************************************/
function showText(local, file, method, param) {
	//referência da div que mostra alguma coisa
	div = document.getElementById(local);
	
	//criar o objeto de HTTP
	obj = MakeObjectHttp();
	
	//"abrir a requisição HTTP" chamando o arquivo de processamento
	if (method.toUpperCase() == "GET") {
		file = file + "?" + param;
		param = null;
	}
	obj.open(method, file, true);
	
	//teste para o objeto http interpretar o envio como se tivesse
	//sido feito por um formulário, que possibilita o envio por post
	if (method.toUpperCase() == "POST") {
		obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	}
	
	//envia a requisição... 
	//se o method for get o param é null e o envio dos dados é pelo open
	//se o method for post o param é o que foi enviado pela função
	obj.send(param);
	
	//depois de processado (onreadystatechange)
	//verificar o status e mostrar os dados na DIV
	obj.onreadystatechange = function() {
		if (obj.readyState == 4) {
			if (obj.status == 200) {
				div.style.display = "block";
				div.innerHTML = obj.responseText;
			} else {
				alert(obj.status);
			}
		}
		else {
			div.innerHTML = "processando...";
		}
	}
}