(function() {
  var Toggle;

  Toggle = (function() {
    var COOKIE_NAME;

    COOKIE_NAME = 'cms-toggle-ids';

    Toggle.loadAndMarkPacked = function() {
      var element, existing, id, j, len, ref, results;
      existing = [];
      ref = Toggle.load();
      results = [];
      for (j = 0, len = ref.length; j < len; j++) {
        id = ref[j];
        element = $('#' + id);
        if (element.length > 0) {
          existing.push(id);
          results.push(this.get(element).pack(0));
        } else {
          results.push(void 0);
        }
      }
      return results;
    };

    Toggle.get = function(element) {
      var el;
      el = $(element);
      return el.data('toggle') || new Toggle(el);
    };

    function Toggle(el1) {
      this.el = el1;
      if (!this.el) {
        throw new Error('ThreeScale.Toggle needs an element');
      }
      this.id = this.el.attr('id');
      if (!this.id) {
        throw new Error('ThreeScale.Toggle needs element with an ID');
      }
      this.el.data('toggle', this);
    }

    Toggle.prototype.save = function() {
      var i, ids;
      ids = Toggle.load();
      if (this.el.hasClass('packed')) {
        if (ids.indexOf(this.id) < 0) {
          ids.push(this.id);
        }
        this.el.trigger('toggle:pack');
      } else {
        i = ids.indexOf(this.id);
        if (i >= 0) {
          ids.splice(i, 1);
        }
        this.el.trigger('toggle:unpack');
      }
      if (!_(ids).isEqual(Toggle.load())) {
        return Toggle.save(ids);
      }
    };

    Toggle.prototype.pack = function(speed) {
      return this.el.slideUp(speed, (function(_this) {
        return function() {
          _this.el.addClass('packed');
          return _this.save();
        };
      })(this));
    };

    Toggle.prototype.unpack = function(speed) {
      return this.el.slideDown(speed, (function(_this) {
        return function() {
          _this.el.removeClass('packed');
          return _this.save();
        };
      })(this));
    };

    Toggle.prototype.toggle = function(speed, callback) {
      return this.el.slideToggle(speed, (function(_this) {
        return function() {
          _this.el.toggleClass('packed');
          _this.save();
          if ('function' === typeof callback) {
            return callback.call(_this, _this.el);
          }
        };
      })(this));
    };

    Toggle.serialized_ids = function() {
      return $.cookie(COOKIE_NAME, {
        path: '/'
      }) || '[]';
    };

    Toggle.save = function(ids) {
      this.cached_ids = ids;
      return $.cookie(COOKIE_NAME, JSON.stringify(ids), {
        expires: 30,
        path: '/'
      });
    };

    Toggle.load = function() {
      this.cached_ids || (this.cached_ids = JSON.parse(this.serialized_ids()));
      return this.cached_ids.slice(0);
    };

    return Toggle;

  })();

  window.ThreeScale.Toggle = Toggle;

}).call(this);
