﻿var collapsibles = new Array();
var fxChain = new Chain();

var Collapsible = new Class({
  Implements: [Options],

  options: {
    startClosed: true,
    closeOthers: true,
    mode: 'vertical'
  },

  element: null,
  toggler: null,
  fx: null,

  initialize: function(element, options) {
    collapsibles.push(this);

    this.setOptions(options);
    this.element = $(element);
    this.toggler = $(this.element.id.replace('content-', 'link-'));

    this.fx = new Fx.Slide(this.element, {
      duration: 500,
      transition: Fx.Transitions.Pow.easeOut,
      link: 'cancel',
      mode: this.options.mode,
      onComplete: function() { fxChain.callChain(); }
    });

    if (this.options.startClosed && !this.element.hasClass('open')) {
      this.fx.hide();
    }

    this.toggler.addEvent('click', this.toggle.bind(this));
  },

  isOpen: function() {
    return this.fx.open;
  },

  collapse: function() {
    this.fx.slideOut();
    this.collapsed = true;
  },

  toggle: function() {
    if (this.options.closeOthers) {
      collapsibles.each(function(otherCollapsible) {
        if (otherCollapsible !== this && otherCollapsible.isOpen()) {
          fxChain.chain(function() { otherCollapsible.collapse(); });
        }
      } .bind(this));
    }
    fxChain.chain(function() { this.fx.toggle(); } .bind(this));
    fxChain.chain(function() { new Fx.Scroll(window).toElement(this.element); } .bind(this));
    fxChain.callChain();
  }
});