// Inicializa as variáveis para controle da fila
var ifila = 0
var fila = new Array();

function $(id)
{
	return document.getElementById(id);
}

// Inicializa o objeto que irá fazer as solicitações
function ajax()
{
	if( window.XMLHttpRequest )
	{
		var objetoXMLHttp = new XMLHttpRequest();
	}
	else if( window.ActiveXObject )
	{
		var versoes = ["MSXML2.XMLHttp.7.0", "MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"];

		for( var i = 0; i < versoes.length; i++ )
		{
			try
			{
				var objetoXMLHttp = new ActiveXObject(versoes[i]);
			}
			catch(e){}
		}
	}

	// Retorna o objeto criado ou retorna um erro
	if( !objetoXMLHttp )
	{
		alert("Seu navegador não suporta AJAX, Desculpe!");
	}
	else
	{
		return objetoXMLHttp;
	}
}

// Guarda na fila o ID do objeto, a url e o tipo de carregamento que serão carregados pelo link clicado
function ajaxLink(id, url, tipo)
{
	// Exibe mensagem de que está carregando a pagina no objeto de ID informado
	ajaxCarregando(id, tipo);
	
	// Adiciona a solicitação na fila
	fila[fila.length] = [id, url, "GET", null, tipo];
	
	// Se não tem conexões na fila, inicia a execução
	if( fila.length == 1 )
	{
		ajaxRun();
	}
    return;
}

// Executa a próxima solicitação da fila
function ajaxRun()
{
	// Pega a URL da fila
	var url = fila[ifila][1];
	// Pega o método de envio
	var metodoEnvio = fila[ifila][2];

	// Abre a conexão
	xmlhttp = ajax();
	xmlhttp.open(metodoEnvio, url, true);
	
	// Seta as funcões que irão tratar a mudança de estado do objeto XMLHTTP
	xmlhttp.onreadystatechange = ajaxStateChange;
	xmlhttp.send(null);
}

// Função executada quando alterar o status da solicitação (readyState)
function ajaxStateChange()
{
	// 0 - Não inicializado, 1 - Carregando, 2 - Carregado, 3 - Interativo, 4 - Completo
	if( xmlhttp.readyState == 1 )
	{
		ajaxCarregando(fila[ifila][0], fila[ifila][4]);	// Quando iniciar a solicitação
	}
	else
	{
		if( xmlhttp.readyState == 4 )
		{
			ajaxStateChangeCompleto(xmlhttp, fila[ifila][0]);	// Quando estiver completa a solicitação
		}
	}
}

// Função executada quando a solicitação estiver completa (readyState=4)
function ajaxStateChangeCompleto(xmlhttp, id)
{
	var retorno;

	// Verifica o status da página de retorno
	if( xmlhttp.status == 200 || xmlhttp.status == 0 )
	{
		// Caso o status seja 200 (Sucesso) ou não utilize servidor (chamada local [C:\...]), trata o valor retornado
		//retorno = unescape(xmlhttp.responseText.replace(/\+/g," "));
		retorno = xmlhttp.responseText;
	}

	// Exibe o valor retornado no objeto de ID informado
	$(id).innerHTML = retorno;

	// Passa para a próxima posição da fila
	ifila++;

	if( ifila < fila.length )
	{
		// Caso tenha mais solicitações na fila, executa a próxima
		setTimeout("ajaxRun()", 20);
	}
	else
	{
		// Caso não tenha mais solicitações na fila, reinicia a fila
		fila = null;
		fila = new Array();
		ifila = 0;
	}

	return;
}

// Função para retornar a mensagem de carregando
function ajaxCarregando(id, tipo)
{
	if( tipo == 0 )
	{
		$(id).innerHTML = "";
	}
	else if( tipo == 1 )
	{
		$(id).innerHTML = "<b>Aguarde...</b>";
	}
	else if( tipo == 2 )
	{
		$(id).innerHTML = "<img src='imagens/load.gif'>";
	}
	else if( tipo == 3 )
	{
		$(id).innerHTML = "<img src='imagens/load.gif'> <b>Carregando...</b>";
	}
}