// Generated by CoffeeScript 1.3.3

define(['jquery', 'underscore', 'backbone'], function($, _, Backbone) {
  var _ajax;
  _ajax = Backbone.ajax;
  Backbone.ajax = function(options) {
    return this.ajax.queue(options);
  };
  Backbone.ajax.pending = false;
  Backbone.ajax.requests = [];
  Backbone.ajax.requestNext = function() {
    var args, options, promise;
    if ((args = this.requests.shift())) {
      options = args[0], promise = args[1];
      return this.request(options, promise);
    } else {
      return this.pending = false;
    }
  };
  Backbone.ajax.request = function(_options, promise, trigger) {
    var complete, error, options, params, success,
      _this = this;
    if (trigger == null) {
      trigger = true;
    }
    options = _.extend({}, _options);
    success = options.success;
    error = options.error;
    complete = options.complete;
    params = {
      complete: function(xhr, status) {
        var _ref;
        if (status === 'timeout') {
          if (App.state.ajaxAttempts < App.ajax.maxAttempts) {
            return _ajax(params);
          }
        } else if ((200 <= (_ref = xhr.status) && _ref < 300)) {
          if (complete) {
            complete.apply(_this, arguments);
          }
          if (trigger) {
            return _this.requestNext();
          }
        } else {
          return _this.pending = false;
        }
      },
      success: function() {
        if (success) {
          success.apply(this, arguments);
        }
        return promise.resolveWith(this, arguments);
      },
      error: function(xhr, status, err) {
        if (status === 'timeout' && App.state.ajaxAttempts < App.ajax.maxAttempts) {
          return App.state.ajaxAttempts++;
        } else {
          if (error) {
            error.apply(this, arguments);
          }
          return promise.rejectWith(this, arguments);
        }
      }
    };
    params = _.extend(options, params);
    _ajax(params);
    return App.state.ajaxAttempts = 1;
  };
  Backbone.ajax.queue = function(options) {
    var promise, type;
    type = (options.type || 'get').toLowerCase();
    promise = $.Deferred();
    if (type === 'get') {
      this.request(options, promise, false);
    } else if (this.pending) {
      this.requests.push([options, promise]);
    } else {
      this.pending = true;
      this.request(options, promise);
    }
    return promise;
  };
});
