/* global Prototype Ajax timeout catcher 
   see also atomic.js where this is implemented as part of the class
*/

// timeout stuff based on http://codejanitor.com/wp/2006/03/23/ajax-timeouts-with-prototype/
  
var Atomic = {
  Version: '2.0.0',
  prototypeVersion: parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1])
};

if((typeof Prototype=='undefined') || Atomic.prototypeVersion < 1.4)
      throw("Atomic JS requires the Prototype JavaScript framework >= 1.4");

Atomic.ajax = Class.create();

var AtomicAjaxTimeOutSet = 0;
  
Atomic.ajax.prototype = {

    initialize: function( param )
    {
        this.timeout     = param.timeout || 5000;    // 5 seconds
        this.error       = 0;
        this.error_id    = param.error_id || 'error';
        
        if (! typeof param.ajax_request == 'undefined' )
        {
            throw("ajax_request required to initialize Atomic.ajax");
        }
        
        if (! AtomicAjaxTimeOutSet)
            this.set_ajax_timeout();
        
    },
    
    ajax_in_progress: function (xhr)
    {
        switch (xhr.readyState)
        {
            case 1: case 2: case 3:
                return true;
            break;
            default:
                return false;
            break;
        }
        return false;
    },
            
    ajax_timed_out: function ()
    {
        this.error = 1;
        $(this.error_id).innerHTML =
             "The network appears to have failed. Please try again.";
                         
        this.cancel_ajax();
    },
    
    /* 
        NOTE this is global, which means if user tries to activate
        an ajax request while another is still pending, the timeouts
        can get screwy.
        that will happen so seldom in this application that we don't worry.
        we could also set the timeout value to something lower than 5 seconds
        by default, assuming that user will be patient for N seconds.
    */
    set_ajax_timeout: function ()
    {   
        var self = this;
        AtomicAjaxTimeOutSet = 1;
        
        Ajax.Responders.register({
        onCreate: function(request) 
        {
            request['timeout_id'] = setTimeout(
             function() 
             {
                // If we have hit the timeout and the AJAX request is active, 
                // abort it and let the user know
                if (self.ajax_in_progress(request.transport)) 
                {
                    request.transport.abort();
                    request.is_aborted  = true;
                    self.ajax_timed_out();
                    // Run the onFailure method if we set one up 
                    // when creating the AJAX object
                    if (request.options['onFailure']) 
                    {
                        request.options['onFailure'](request.transport, request.json);
                    }
                }
             },
             self.timeout
            );
        },
        onComplete: function(request) 
        {
            // Clear the timeout, the request completed ok
            clearTimeout(request['timeout_id']);
            alert("ajax completed");
        }
        });
    },
    
    debug_ajax: function()
    {

        Ajax.Responders.register({
        onCreate: function(){
            alert('a request has been initialized!');
        }, 
        onComplete: function(){
            alert('a request completed');
        },
        onLoaded: function(ajax, xhr){
            alert('a request loaded');
            var head = xhr.requestHeaders;
            alert('request headers: ' + head);
        },
        onLoading: function(){
            alert('a request loading');
        },
        onException: function(aj,err){
            alert('request threw exception: ' + err);
            if (err instanceof errorType1)
                alert("errorType1");
            else if (err instanceof errorType2)
                alert("errorType2");
            else if (err instanceof errorType3)
                alert("errorType3");
            else if (err instanceof errorType4)
                alert("errorType4");
            else if (err instanceof errorType5)
                alert("errorType5");
            else if (err instanceof errorType6)
                alert("errorType6");
            else
                alert("unknown error type");
                
            alert('error name: ' + err.name);
            alert('error msg: ' + err.message);
            alert('error num: ' + err.number );
        }
        });

    },
    
    cancel_ajax: function()
    {
        if (! this.ajax_request.is_aborted)
        {
            alert("ajax not yet aborted");
            this.ajax_request.transport.abort();
        }
                       
    }

};
