/*
 * UDAJAXAgent
 *
 * Asynchronous Javascript and XML (AJAX) helper class.
 *
 * Copyright (c) 2008
 * Jeffrey T Frey
 * Network & Systems Services, University of Delaware
 *
 * $Id: UDAJAXAgent.js,v 1.4 2009/07/23 14:42:20 frey Exp $
 *
 */

/*!
  @class UDAJAXAgent
  
  A Javascript "class" that manages an asynchronous resource retrieval (AJAX)
  agent.  Note that most browsers limit just how many of these can be created
  by a page, so a single instance of UDAJAXAgent implements a request queue.
  If the agent is currently busy fetching a previous request, new requests
  enter into a queue to be serviced in order as previous requests complete.
  
  The constructor function requires the programmer to pass the name of the
  UDAJAXAgent when it is constructed -- this is a sad result of the way in which
  we need to process the request responses as they return asynchronously.  Thus
  
      myAgent = new UDAJAXAgent("myAgent");
      
  would be appropriate syntax for creating an AJAX agent.
  
  Requests are sent by specifying a URI, a flag as to whether or not the agent
  should attempt to process the text returned via the request or an actual XML
  document created from the request response.  A function which should be called
  to process the response is specified, along with a single additional variable
  which will be passed to that function (a "context", essentially a container for
  any additional data needed by the responder function).
  
  A responder function should be prototyped as
  
    function myAJAXAgentResponder(
      sourceURI,
      responseData,
      isXML,
      context
    );
  
  where isXML is true if the responseData is an XML document rather than plain text
  and context is the responderContext which was passed to the request() member
  function.
*/
function UDAJAXAgent(
  agentId
)
{
  return this.init(agentId);
}

function UDSharedAJAXAgent()
{
  if ( __UDSharedAJAXAgent == null ) {
    __UDSharedAJAXAgent = new UDAJAXAgent('__UDSharedAJAXAgent');
  }
  return __UDSharedAJAXAgent;
}

var __UDSharedAJAXAgent = null;

UDAJAXAgent.prototype = {

  init:function(
    agentId
  )
  {
    this._objectId = agentId;
    this._requestQueue = new Array();
    this._lastURI = null;
  },
  
  request:function(
    uri,
    isXML,
    responderCallback,
    responderContext,
    method,
    dataToSend
  )
  {
    // We default to a GET request:
    if ( method == null ) {
      method = 'GET';
    }
    
    if ( agent = this._getAgent() ) {
      if ( uri != this._lastURI ) {
        this._requestQueue.push( [ uri , isXML , responderCallback, responderContext ] );
      }
      if ( this._requestQueue.length > 0 ) {
        if ( (agent.readyState == 4) || (agent.readyState == 0) ) {
          var     target = this._requestQueue.shift();
          var     self = this;

          agent.open(method, target[0], true);
          agent.onreadystatechange =
function() {
  if ( agent.readyState == 4 ) {
    if ( agent.status == 200 ) {
      var     response;
      
      if ( target[1] ) {
        response = agent.responseXML;
      } else {
        response = agent.responseText;
      }
      
      /* Get the callback to process the response: */
      (target[2])(target[0], response, target[1], target[3]);
      
      /* If there are pending requests, call the request() function
         again in half a second. */
      if ( self._requestQueue.length > 0 ) {
        setTimeout(self._objectId + '.request(null,null,null,null);', 500);
      }
    }
  }
}
          agent.send(dataToSend);
          return true;
        }
      }
    }     
    return false;
  },
  
  _getAgent:function()
  {
    if ( ! this._xmlTransferAgent ) {
     // Try to get the right object for different browser
      try {
        // Firefox, Opera 8.0+, Safari, IE7+
        this._xmlTransferAgent = new XMLHttpRequest(); // xmlHttp is now a XMLHttpRequest.
      } catch (e) {
        // Internet Explorer
        try {
           this._xmlTransferAgent = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
           this._xmlTransferAgent = new ActiveXObject("Microsoft.XMLHTTP");
        }
      }
    }
    return this._xmlTransferAgent;
  }
  
};
