/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn(divLoading)
{
  var xmlhttp, bComplete = false;
  xmlhttp = XHRFactory.getInstance();
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		if (sVars != null) { xmlhttp.setRequestHeader("Content-length", sVars.length); }
      }
      xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 1) { divLoading.innerHTML="<img src='imgs/loading.gif'>&nbsp;Aguarde..."; }
        if (xmlhttp.readyState == 4 && !bComplete)  {
		  divLoading.innerHTML="";			
          bComplete = true;
          if(fnDone != null) fnDone(xmlhttp,divLoading);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}


/** XHRFactory                                                                      **
 ** This class from: http://blogs.pathf.com/agileajax/2006/08/object_pooling_.html  **/
var XHRFactory = (function(){
 // static private member
 var stack = new Array();
 var poolSize = 10;
 
 var nullFunction = function() {}; // for nuking the onreadystatechange
 
 // private static methods
 
 function createXHR() {
  if (window.XMLHttpRequest) {
       return new XMLHttpRequest();
     } else if (window.ActiveXObject) {
       return new ActiveXObject('Microsoft.XMLHTTP')
     }
    }

 // cache a few for use
 for (var i = 0; i < poolSize; i++) {
  stack.push(createXHR());
 }
 
 // shared instance methods
 return ({
  release:function(xhr){
   xhr.onreadystatechange = nullFunction;
   stack.push(xhr);
  },
  getInstance:function(){
   if (stack.length < 1) {
    return createXHR();
   } else {
    return stack.pop();
   }
  },
  toString:function(){
   return "stack size = " + stack.length;
  }
 });
})();




/* ---------------------------------------------------------------------- *\
  Funçao    : codigos_erro(codigo)
  Descriçao : Analisa Códigos de Erro HTTP
  Retorno	: retorna a mensagem
\* ---------------------------------------------------------------------- */
function codigos_erro(codigo) {
	var msg = '';
	// Mensagens de Retorno (tratamento de códigos de Erro
	if (codigo == 200) {}
	else if (codigo == 302 ) { msg = "Movido Temporariamente"; }
	else if (codigo == 303 ) { msg = "Ver noutra localiza&ccedil;&atilde;o"; }
	else if (codigo == 305 ) { msg = "Usar proxy"; }
	else if (codigo == 400 ) { msg = "O servidor n&atilde;o compreendeu a sintaxe do pedido"; }
	else if (codigo == 401 ) { msg = "O pedido requer autenticaç&atilde;o"; }
	else if (codigo == 403 ) { msg = "Acesso Negado"; }
	else if (codigo == 404 ) { msg = "P&aacute;gina n&atilde;o encontrada"; }
	else if (codigo == 405 ) { msg = "M&eacute;todo n&atilde;o permitido"; }
	else if (codigo == 408 ) { msg = "Esgotado o tempo limite"; }
	else if (codigo == 411 ) { msg = "O servidor n&atilde;o ir&aacute; aceitar o pedido sem um campo de cabe&ccedil;alho Content-Length v&aacute;lido."; }
	else if (codigo == 413 ) { msg = "O servidor n&atilde;o pode processar o pedido porque &eacute; demasiado grande"; }
	else if (codigo == 414 ) { msg = "O URI pedido (normalmente, um URL) &eacute; demasiado extenso para o servidor o processar."; }
	else if (codigo == 415 ) { msg = "O pedido est&aacute; num formato n&atilde;o suportado pela p&aacute;gina solicitada"; }
	else if (codigo == 500 ) { msg = "O servidor encontrou um erro e n&atilde;o consegue satisfazer o pedido."; }
	else if (codigo == 501 ) { msg = "O servidor n&atilde;o tem a funcionalidade necess&aacute;ria para satisfazer o pedido"; }	
	else if (codigo == 502 ) { msg = "O servidor estava a funcionar como uma gateway ou proxy, e recebeu uma resposta inv&aacute;lida do servidor a montante"; }
	else if (codigo == 503 ) { msg = "O servidor n&atilde;o se encontra dispon&iacute;vel neste momento"; }
	else if (codigo == 505 ) { msg = "O servidor n&atilde;o suporta a vers&atilde;o de protocolo HTTP utilizada no pedido"; }
	return msg;
} // codigos_erro
