
// require xLib.js

var Collapsible2 = {

  create: function(id,subject,expanded,visible) {
    if (typeof subject === 'string') subject = xLib.$(subject);
    var container = xLib.$(id);
    return (container.__Collapsible2 = new Collapsible2._object(id,container,subject,expanded,visible));
  },

  getInstance: function(id) {
    return xLib.$(id).__Collapsible2;
  }

};

// Collapsible2._object

Collapsible2._object = function(id,container,subject,expanded,visible) {
  this.id = id;
  this.container = container;
  this.subject = subject;
  this.expanded = expanded;
  this.visible = visible;
  this._handlers = [];
  this._containerDisplay = null;
  this._subjectDisplay = null;
};

// Collapsible2._object.prototype

Collapsible2._object.prototype.dispose = function() {
  for (var i = 0; i < this._handlers.length; i++) {
    var a = this._handlers[i];
    xLib.removeHandler(a[0],a[1],a[2]);
  }
  this._handlers = [];
};

Collapsible2._object.prototype.addTrigger = function(node,type,event) {
  if (typeof node === 'string') node = xLib.$(node);
  if (node) {
    if (!event) event = 'click';
    var h = new Function('','Collapsible2.getInstance("'+this.id+'").__on'+type+'()');
    this._handlers.push([node,event,h]);
    xLib.addHandler(node,event,h);
  }
  return this;
};

Collapsible2._object.prototype.setHandler = function(type,handler) {
  this['on'+type] = handler;
  return this;
};

//
// handler
//

Collapsible2._object.prototype.__onShow = function() {
  if (!this.visible) {
    this.visible = true;
    this.container.style['display'] = this._containerDisplay || '';
    if (typeof this.onShow === 'function') this.onShow();
  }
};

Collapsible2._object.prototype.__onHide = function() {
  if (this.visible) {
    this.visible = false;
    this._containerDisplay = this.container.style['display'] || null;
    this.container.style['display'] = 'none';
    if (typeof this.onHide === 'function') this.onHide();
  }
};

Collapsible2._object.prototype.__onCollapse = function() {
  if (this.expanded) {
    this.expanded = false;
    this._subjectDisplay = this.subject.style['display'] || null;
    this.subject.style['display'] = 'none';
    if (typeof this.onCollapse === 'function') this.onCollapse();
  }
};

Collapsible2._object.prototype.__onExpand = function() {
  if (!this.expanded) {
    this.expanded = true;
    this.subject.style['display'] = this._subjectDisplay || '';
    if (typeof this.onExpand === 'function') this.onExpand();
  }
};

Collapsible2._object.prototype.__onToggle = function() {
  this.expanded ? this.__onCollapse() : this.__onExpand();
};


// shorthand
Collapsible2._object.prototype.show = Collapsible2._object.prototype.__onShow;
Collapsible2._object.prototype.hide = Collapsible2._object.prototype.__onHide;


