/* --------------------------------------------------------
 * HRC-JS Framework
 * --------------------------------------------------------
 * Auteur                :        Hondsrug Colleg
 * E-mail                :        matthias@hondsrugcollege.nl
 * Copyright             :        (C) 2007 - Hondsrugcollege
 * --------------------------------------------------------
 */




if (!window.XMLHttpRequest)
{
        window.XMLHttpRequest = function()
        {
                var types =
                          [
                           'MSXML2.XMLHTTP.6.0',
                           'MSXML2.XMLHTTP.3.0'
                          ];

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

                return undefined;
        }
}



function Ajax( )
{
        if ( this == window )
             return new Ajax;

        // Singleton methode..
        if ( Ajax.instance )
              return Ajax.instance;


        // Standaard instellingen voor het Ajax object
        this.instellingen =
        {
              methode      :  'GET',
              contentType  :  'application/x-www-form-urlencoded',
              cache        :  false,
              type         :  'text',
              ansync       :  false
        };

        // Scope variabelen
        this.aanvraagObject = null;
        this.wachtrij = [];
        this.bezig = false;

        return ( Ajax.instance = this );
}



Object.extend(Ajax.prototype,
{
      maakRequestObject : function( forceer )
      {
            requestObj = 'aanvraagObject';

            if ( this[ requestObj ] === null || forceer )
                   this[ requestObj ] = new XMLHttpRequest();

            return this[ requestObj ];
      },

      stuurAanvraag : function( url, opties, data )
      {
             aanvraagObj = this.maakRequestObject();

             opties = Object.extend( opties || {}, this.instellingen );

             if ( aanvraagObj )
             {
                   // Zo te zien is er een aanvraag aan de gang
                   // deze aanvraag komt in de wachtrij..
                   if ( opties[ 'ansync' ] && this.bezig )
                   {
                          this.vulWachtrij( url, opties, data );
                   }
                   else
                   {
                          if ( opties[ 'ansync' ] )
                                this.bezig = true; // Geef aan dat het object bezet is

                          // Definieer een aantal variablen
                          // Als ze handmatig zijn opgegeven overrulen deze de standaard instellingen (this.instellingen)
                          methode = opties[ 'methode' ] || this.instellingen[ 'methode' ];
                          headers = opties[ 'headers' ] || {};
                          nocache = opties[ 'cache' ]   || this.instellingen[ 'cache' ];

                          if ( methode.toUpperCase( ) == 'POST' )
                          {

                          }
                          else
                          {
                                 url += system.urlParameters(url, { nocache : new Date().getTime() });
                                 url += system.urlParameters(url, data);
                          }

                          aanvraagObj.open( methode, url, opties[ 'ansync' ] );

                          if ( opties[ 'ansync' ] )
                          {
                                  aanvraagObj.onreadystatechange = this.standaardHandler.bind( this, opties );
                                  aanvraagObj.send( data );
                          }
                          else
                          {
                                  aanvraagObj.send( data );
                                  return this.standaardHandler( opties );
                          }

                   }

                   return true;
             }

             return false;
      },

      vulWachtrij : function ( url, opties, parameters )
      {
             this.wachtrij.push( {url : url, opties : opties, parameters : parameters} );
      },

      laadWachtrij : function ( )
      {
            // Alleen de aanvraag sturen als het object weer vrij is
            if ( !this.bezig && this.wachtrij.length )
            {
                  aanvraag = this.wachtrij.shift( );
                  this.stuurAanvraag( aanvraag[ 'url' ], aanvraag[ 'opties' ], aanvraag[ 'data' ] );
            }
      },

      standaardHandler : function( opties )
      {
            aanvraagObj = this.maakRequestObject();
            result = null;

            // Alleen uitvoeren wanneer het object succesvol is geinitialiseerd
            if ( aanvraagObj.readyState == 4 )
            {

                  if ( aanvraagObj.status >= 200 && aanvraagObj.status < 400 )
                  {
                        type = opties[ 'type' ].toLowerCase( );

                        switch( type )
                        {
                              case "text":
                              default:
                                   result =  aanvraagObj.responseText;
                        }

                        if ( opties[ 'handler' ] )
                               result = opties[ 'handler' ]( aanvraagObj.responseText );

                        if ( opties[ 'ansync' ] )
                        {
                                // Geef aan dat het object weer *vrij* is
                                this.bezig = false;
                                aanvraagObj.onreadystatechange = function( ) {}

                                // Probeer de volgende aanvraag uit de wachtrij te halen
                                this.laadWachtrij();
                        }
                  }
            }

            return result;
      },

      // -- Debug functies
      printWachtrij : function ( )
      {
           var wachtrij = 'Aanvragen in de wachtrij: (system::Ajax::wachtrij)\n\n';
           for ( var actie in this.wachtrij )
           {
                 wachtrij += actie + '. URL: ' +  this.wachtrij[ actie ][ 'url' ] + "\n";
           }

           alert( wachtrij );
      }
});
