var Accordion = Class.create({
  initialize: function(id) {
    if(!$(id)) throw("Attempted to initalize accordion with id: "+ id + " which was not found.");
    this.accordion = $(id);
    this.options = {
      toggleClass: "accordion-toggle",
      toggleActive: "accordion-toggle-active",
      contentClass: "accordion-content"
    }
    this.isAnimating = false;
    this.maxHeight   = "480"; // the max height that the first pane will expand to
    this.minHeight   = $('accordion-expander').getHeight();

    this.accordion.observe('click', this.clickHandler.bindAsEventListener(this));
  },
  
  toggleAccordion: function() {
    if ($('accordion-expander').getHeight() == this.maxHeight) {
      // we are going to be collapsing the expander
      var newHeight = this.minHeight;
    } else {
      // we are going to expand the expander
      var newHeight = this.maxHeight;
    };
    $$('.'+this.options.toggleClass).each(function(e){e.toggleClassName('open')});

    new Effect.toggle('gallery_arrows_wrapper', 'blind', {duration: 0.1});
    new Effect.Morph('accordion-expander', {
      style: 'height: '+newHeight+'px',
      duration: 0.1,
      beforeStart: function() {
        this.isAnimating = true;
      }.bind(this),
      afterFinish: function() {
        this.isAnimating = false;
      }.bind(this)
    });
  },
  
  /* Determine where a user has clicked and act based on that click */
  clickHandler: function(e) {
    var el = e.element();
    if((el.hasClassName(this.options.toggleClass) || el.up().hasClassName(this.options.toggleClass)) && !this.isAnimating) {
      // user has click on one of the accordion headings
      this.toggleAccordion();
    }
  }
});

document.observe("dom:loaded", function(){
  if ($('accordion-expander')) {
    accordion = new Accordion("galleries_and_colours");    
  }
});