// prority/smart queue for ajax requests.. stop thumbnail update interfering with save/add to cart...
var AjaxQueueManager = Class.create({
  CLASSDEF: {
      name: 'AjaxQueueManager'
  },
  
  initialize: function AQM_initialize() {
    this.queues = {};
  },
  
  queueRequest: function AQM_queueRequest(key, mode, options) {
    var q = this.getQueue(key);
    q.addRequest(mode, options);
  },
  
  getQueue: function AQM_getQueue(key) {
    var q = this.queues[key];
    if(q == null) {
      q = new AjaxQueue(this);
      this.queues[key] = q;
    }
    return q;
  }
});

var ajaxQueueManager = new AjaxQueueManager();

var AjaxQueue = Class.create({
  CLASSDEF: {
      name: 'AjaxQueue'
  },
  
  initialize: function AQ_initialize() {
    this.queue = [];
    this.running = null;
  },
  
  addRequest: function AQ_addRequest(mode, options) {
    if(this.running == null) {
      this.run(options);
    } else {
      if(mode == 1) { //1 = remove existing...
        log("AjaxQueue: mode == 1, clearing exisitng queue");
        this.queue = [];
      } else if(mode == 2) { //2 = use existing (dont queue if already running)
        log("AjaxQueue: mode == 2, skipping request");
        return;
      } else if(mode == 3) {// 3 = remove existing with same subkey
        var sKey = options.subKey;
        log("AjaxQueue: mode == 1, Clearing existing with subKey=" + sKey);
        var i = 0;
        while(i < this.queue.length) {
          var otherSubKey = this.queue[i].subKey;
          if(otherSubKey == sKey) {
            log("Found Existing Queued Item with subKey=" + otherSubKey);
            this.queue.splice(i,1);
          } else {
            i++;
          }
        }
      } else {
        log("AjaxQueue: mode == 0, queueing request");
      }
      this.queue.push(options);
    }
  },
  
  run: function AQ_run(options) {
    log("Running Ajax Queue Item for " + options.url);
    this.running = options;
    var self = this;
    var onComplete = options.options.onComplete;
    //override the onComplete to queue requests
    options.options.onComplete = function(transport, jsonResult) {
      if(onComplete != null) { //call the original onComplete
        onComplete(transport, jsonResult);
      }
      self.running = null;
      self.runNext();
    };
    
    if(options.parameters != null) { //we have a function which makes the params...
      options.options.parameters = options.parameters();
    }
    
    if(options.mode == 0) { //request
      var req = new Ajax.Request(d.ajaxUrl(options.url), options.options);
    } else if(options.mode == 1) { //updater
      var req = new Ajax.Updater(options.target, d.ajaxUrl(options.url), options.options);
    }
  },
  
  runNext: function AQ_runNext() {
    var next = this.queue.shift();
    if(next != null) {
      log("Running Next Ajax Queue Item");
      this.run(next);
    }
  }
});
