TaxonomyTree = {
  initialize: function() {
    this.taxonomy_parents = []
    $$('div#inventory ul li.parent').each(function(tp) {
      this.taxonomy_parents.push(new TaxonomyParent(tp, this))
    }.bindAsEventListener(this))
  }
}

var TaxonomyParent = Class.create({
  initialize: function(e, tree) {
    this.e = e
    this.tree = tree
    var id = this.e.id.split("_")[1]
    this.children = $('children_'+id)
    this.status = this.e.down('A').hasClassName('current') ? 'open' : 'closed'
    
    this.e.observe('click', this.click.bindAsEventListener(this))
  },
  
  click: function(event) {
    if(event.target.up().id.match('taxon_')) { // IE6 hack to prevent event from binding to siblings
      event.stop()
      if(this.status == 'closed') {
        this.open()
        this.tree.taxonomy_parents.each(function(t) { if(t.status == 'open') t.close() })
      }
    }
  },
  
  open: function() {
    this.status = 'transit'
    this.e.down().addClassName('open');
    new Effect.BlindDown(this.children, { duration: 0.3, afterFinish: this.finish_open.bindAsEventListener(this) })
  },
  finish_open: function() {
    this.status = 'open'
  },
  
  close: function() {
    this.status = 'transit'
    this.e.down().removeClassName('open');
    new Effect.BlindUp(this.children, { duration: 0.3, afterFinish: this.finish_close.bindAsEventListener(this) })
  },
  finish_close: function() {
    this.status = 'closed'
  }
})

document.observe('dom:loaded', TaxonomyTree.initialize)
