/*
 *
 * jQuery ajaxQueue
 *
 * jQueryDate: 12:05 PM 11/17/2010
 * jQueryAuthor: Greg Henle
 *
 */
(function($){
  $.fn.ajaxQueue = function(o) {
  
    // default settings
    var s = $.extend({
      refresh: false,
      spinner: false,
      queue_delay: 1000,
      refresh_target: 0,
      refresh_cycle: 30000,
      refresh_fn: function(){}
    }, o);
    
    // init fn
    var init_fn = function(t){
      if(s.spinner)
      {
        t.css({
          backgroundImage:'url('+s.spinner+')',
          backgroundPosition:'50% 50px',
          backgroundRepeat:'no-repeat'
        });
      }
    }
    // stop fn
    var stop_fn = function(t){
      var d = t.data('ajaxQueue');
      var n = ++s.refresh_target;
      
      if(s.spinner)
      {
        t.css({
          backgroundImage:'none'
        });
      }
      
      if( typeof( d[n] ) == 'object' )
      {
        setTimeout(function(){
          s.refresh_target = n;
          $.ajax( d[n] );
        }, s.queue_delay);
      }
      else if( s.refresh )
      {
        setTimeout(function(){
          t.children().slideUp('slow', function(){
            $(this).remove();
          });
        }, s.refresh_cycle-3000);
        setTimeout(function(){
          s.refresh_fn();
          s.refresh_target = 0;
          $.ajax( d[0] );
        }, s.refresh_cycle)
      }        
    }

    return this.each(function(){
      if( typeof($(this).data('ajaxQueue')) == 'object' && $(this).data('ajaxQueue').length )
      {
        var d = $(this).data('ajaxQueue');
        
        $(this).ajaxStart(function(){
          init_fn($(this));
        });
        // On a stop or error, move to the next in the queue
        $(this).ajaxStop(function(){
          stop_fn($(this));
        });
        $(this).ajaxError(function(){
          stop_fn($(this));
        });

        $.ajax( d[0] );
      }
    });
  }
})(jQuery);
