/*
   AJAX (Asynchronous JavaScript and XML) is a newly coined term for two powerful 
   browser features that have been around for years, but were overlooked by many 
   web developers until recently when applications such as Gmail, Google suggest, 
   and Google Maps hit the streets. 

   The two features in question are that you can: 

   1 - Make requests to the server without reloading the page 
   2 - Parse and work with XML documents 

      
   AJAXConn
   ---------
   
   Objeto que encapsula os metodos de comunicação entre JS e ASP
   explorados pela técnica AJAX.
   Utiliza 2 outros objetos nativos: XMLHTTP para conectar-se via 
   HTTP a um outro arquivo (asp, html, xml, ...) e 
   XMLDOM que encorpora um arquivo xml, facilitando o acesso aos 
   dados
   
   Apos instaciado, deve-se chamar a função connect para processar
   o pedido de request ao arquivo desejado, em geral definindo uma 
   função a ser executada quando o retorno chegar.

   1 - Exemplo de utilização do objeto
   
      var myConn = new AJAXConn();      
      if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");      
      var fnWhenDone = function (oXML) { alert(oXML.responseText); };      
      myConn.connect("mypage.asp", "POST", "foo=bar&baz=qux", fnWhenDone);
      
   2 - Compatibilidade do objeto AJAXConn :   
      - Apple Safari 1.2+ 
      - Microsoft Internet Explorer 5.0+ (Windows) 
      - Mozilla 0.7.3+ -- includes Firefox, Camino, etc. 
      - Opera Browser 7.60 P1+ (Note: GET support only)
   
*/
function AJAXConn()  { 

   var xmlhttp, bComplete = false;

   if (window.XMLHttpRequest) { // Mozilla, Safari,...
      xmlhttp = new XMLHttpRequest();
      if (xmlhttp.overrideMimeType) {
         xmlhttp.overrideMimeType('text/xml');
         // See note below about this line
      }
   } else if (window.ActiveXObject) { // IE
      try {
         xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            // MSIE 5.5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) { xmlhttp = false; }
      }
   }
   if (!xmlhttp) return null;
   
   
   /*
      AJAXConn.connect
      ----------------
      
      Funcao que processa o request HTTP do objeto XmlHttp passado como parametro.
      Parametros: 
      psMethod    :  metodo HTTP (usualmente GET (querystring) ou POST (form)
      pHandler    :  funcao a ser executada ao final quando o objeto receber os dados da URL
                     (tem que ter como parametro oXml)
      psUrlProc   :  pagina a ser carregada e processada (html, asp ou xml) pelo submit
      pbAssincr   :  booleano para assincrono (true - default AJAX)  ou síncrono (false). 
      psParams    :  parametros da url, serve tanto para GET quanto para POST                   
   */
   this.connect = function(psMethod, pHandler, psUrlProc, pbAssincr, psParams) {
   
      var sParams;
      
      if (!xmlhttp) return false;
      bComplete = false;
      psMethod = psMethod.toUpperCase();
      
      try {
         if (psMethod == "GET")  {
            // evita problema com cache
            //sParams = escape(psParams);
            sUrl = psUrlProc + "?sid=" + Math.random() + "&" + psParams      
            xmlhttp.open("GET", sUrl, pbAssincr);
            
            // o submit será sem parametros
            sParams = null;
         }
         else  {
            
            //  evita problema com cache
            sParams = "sid=" + Math.random() + "&" + psParams
            sParams = escape(sParams);
   
            xmlhttp.open("POST", psUrlProc, pbAssincr);
            xmlhttp.setRequestHeader("Method", "POST "+psUrlProc+" HTTP/1.1");
            xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlhttp.setRequestHeader("Content-length", sParams.length);
            xmlhttp.setRequestHeader("Connection", "close");   
         }
         
         // funcao 'pHandler' é executada quando xmlhttp estiver pronto (carregado)
         // para isso, verifica readyState e status do arquivo 
         xmlhttp.onreadystatechange = function(){
            
         	if(xmlhttp.readyState == 0) { return "Sending Request..."; }
         	if(xmlhttp.readyState == 1) { return "Loading Response..."; }
         	if(xmlhttp.readyState == 2) { return "Response Loaded..."; }
         	if(xmlhttp.readyState == 3) { return "Response Ready..."; }            
            if (  (xmlhttp.readyState == 4  || xmlhttp.readyState == "complete") 
                  && !bComplete)   {
               if (xmlhttp.status == 200)   {
                  bComplete = true;
                  pHandler(xmlhttp);
               }
               else if(xmlhttp.status == 404) {
			         // Add a custom message or redirect the user to another page
			         return "File not found";
         		}
         		else  {
         			return "There was a problem retrieving the XML";
         		}
            }
         };

         // realiza o submit com dados do post (mesma sintaxe da querystring, exceto '?')
         xmlhttp.send(sParams);
      }         
      catch(z) { return false; }
      return true;
   }
      
   /*      
      AJAXConn.getXMLObject
      --------------------
      
      Funcao que retorna o objeto Xml, para tratar 
      a resposta obtida do servidor, facilitando o acesso 
      aos dados
   */
   this.getXMLObject = function(pbAsync)   {
   
      var xmlDoc;
         
      //Code for IE
      if (window.ActiveXObject)  {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = pbAsync;
      }
      
      //Code for Mozilla
      else if (document.implementation && document.implementation.createDocument)   {
        xmlDoc=document.implementation.createDocument("","",null);
      }
      else  {
        alert('Este browser não suporta este objetos XML');
      }
      return xmlDoc;
   }
    
   // retorna o objeto
   return this;
}


