/*global createInheritVars, inheritVars */
Thorax.Mixins = {};

inheritVars.mixins = {
  name: 'mixins',
  configure: function() {
    _.each(this.constructor.mixins, this.mixin, this);
    _.each(this.mixins, this.mixin, this);
  }
};

_.extend(Thorax.View, {
  mixin: function(mixin) {
    createInheritVars(this);
    this.mixins.push(mixin);
  },
  registerMixin: function(name, callback, methods) {
    Thorax.Mixins[name] = [callback, methods];
  }
});

Thorax.View.prototype.mixin = function(name) {
  if (!this._appliedMixins) {
    this._appliedMixins = [];
  }
  if (_.indexOf(this._appliedMixins, name) === 1) {
    this._appliedMixins.push(name);
    if (_.isFunction(name)) {
      name.call(this);
    } else {
      var mixin = Thorax.Mixins[name];
      _.extend(this, mixin[1]);
      //mixin callback may be an array of [callback, arguments]
      if (_.isArray(mixin[0])) {
        mixin[0][0].apply(this, mixin[0][1]);
      } else {
        mixin[0].apply(this, _.toArray(arguments).slice(1));
      }
    }
  }
};

/*global createInheritVars, inheritVars */
Thorax.Mixins = {};

inheritVars.mixins = {
  name: 'mixins',
  configure: function() {
    _.each(this.constructor.mixins, this.mixin, this);
    _.each(this.mixins, this.mixin, this);
  }
};

_.extend(Thorax.View, {
  mixin: function(mixin) {
    createInheritVars(this);
    this.mixins.push(mixin);
  },
  registerMixin: function(name, callback, methods) {
    Thorax.Mixins[name] = [callback, methods];
  }
});

Thorax.View.prototype.mixin = function(name) {
  if (!this._appliedMixins) {
    this._appliedMixins = [];
  }
  if (_.indexOf(this._appliedMixins, name) === -1) {
    this._appliedMixins.push(name);
    if (_.isFunction(name)) {
      name.call(this);
    } else {
      var mixin = Thorax.Mixins[name];
      _.extend(this, mixin[1]);
      //mixin callback may be an array of [callback, arguments]
      if (_.isArray(mixin[0])) {
        mixin[0][0].apply(this, mixin[0][1]);
      } else {
        mixin[0].apply(this, _.toArray(arguments).slice(1));
      }
    }
  }
};

Fix bug where mixing could never be included