//Cria a fila de requisições
//Variáveis Globais
var fila=[];
var ifila=0;
var req=CriaReq();

/*
Objetivo: Verificar se o navegador suporta XML e criar instâcia do XML.
Retorno : tXHR - objeto XML
*/
function CriaReq()
{ var tXHR=0;
  if (window.XMLHttpRequest)
  {
    tXHR=new XMLHttpRequest(); //objeto nativo (FF / Safari / Konqueror / Opera / etc)
  }
  else{
     if (window.ActiveXObject)
     {
      // tXHR=new ActiveXObject("Msxml2.XMLHTTP");  //activeX (IE5.5+/MSXML2+)

       tXHR=new ActiveXObject("Microsoft.XMLHTTP");  //activeX (IE5+/MSXML1)

     }
     else //O navegador não tem suporte
     {
       tXHR=false;
     }
  }
  return tXHR; //retornar resultado (objeto, ou "false", no caso de erro)
}

/**********************************************/
function limpaID(id){

  while (document.getElementById(id).hasChildNodes())
      document.getElementById(id).removeChild(document.getElementById(id).lastChild);

} 

/**********************************************/
function msg(id,msg)
{
    document.getElementById(id).appendChild(document.createTextNode(msg));
}

/**********************************************/
function RespServOK()
{
  if (req.readyState == 4){
    if (req.status == 200) {
       return true;
    }
    else { //Se o servidor retornou outro código que não "200", mostrar o erro.
       //alert('Erro no acesso aos dados '+  req.readyState +' - '+req.status) ;
       alert('Erro no acesso aos dados!') ;
       return false;
    }
    return false;
  }
  return false;
}

/**********************************************/
function carregaDados()
{
	
  req.open('GET', fila[ifila][1], true);
  req.setRequestHeader("Cache-Control", "no-cache");

  req.onreadystatechange=function()
  {
     if (RespServOK()){
        //Mostra o HTML recebido
         document.getElementById(fila[ifila][0]).innerHTML=req.responseText;
         //Roda o próximo
         ifila++
         if(ifila < fila.length)
         	setTimeout("carregaDados()",100);
     }
  }
  //Executa
  req.send(null);

}

/**********************************************/
function carregaDadosPost()
{

  req.open('POST', fila[ifila][1], true);
  //req.setRequestHeader("Cache-Control", "no-cache");
  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  req.setRequestHeader("Content-length", fila[ifila][2].length);
  req.setRequestHeader("Connection", "close");

  req.onreadystatechange=function()
  {
     if (RespServOK()){
        //Mostra o HTML recebido
         document.getElementById(fila[ifila][0]).innerHTML=req.responseText;
         //Roda o próximo
         ifila++
         if(ifila < fila.length)
         	setTimeout("carregaDadosPost()",100);
     }
  }
  req.send(fila[ifila][2]);

}

/**********************************************/
function ajaxHTML(id,url){
	
	var obj= document.getElementById(id);
	var count=url.length;
	var tam=0;
	if (req){
		  //limpa id
		  limpaID(id);
	      //Exibe mensagem
	      document.getElementById(id).innerHTML="<img src='imagens/loading.gif' alt='Carregando...' />";
	      //msg(id,);
	      //Adiciona à fila
	      while (count!=tam) {
	      	count = url.length;
	      	url = url.replace("&amp;","&");
	      	tam = url.length;
	      }
	      
	      fila[fila.length]=[id,url];
	      //Se não há conexões pendentes, executa
	      if((ifila+1)==fila.length)
	      	carregaDados();
	}
	else{
	   alert('O navegador não suporta esta tecnologia, use Internet Explorer 6 / 7 ou Mozilla FireFox para este sistema');
	}

}

function ajaxHTMLpost(id,url,send){
	
	var obj= document.getElementById(id);
	var count=url.length;
	var tam=0;
	if (req){
		  //limpa id
		  limpaID(id);
	      //Exibe mensagem
	      document.getElementById(id).innerHTML="<img src='imagens/loading.gif' alt='Carregando...' />";
	      //msg(id,);
	      //Adiciona à fila
	      while (count!=tam) {
	      	count = send.length;
	      	send = send.replace("&amp;","&");
	      	tam = send.length;
	      }
	      
	      fila[fila.length]=[id,url,send.substring(1)];
	      //Se não há conexões pendentes, executa
	      if((ifila+1)==fila.length)
	      	carregaDadosPost();
	}
	else{
	   alert('O navegador não suporta esta tecnologia, use Internet Explorer 6 / 7 ou Mozilla FireFox para este sistema');
	}

}
