/**
 * Pageload
 */ 
window.addEvent('domready', function() {
  $$('.info-block').each(function(el){
    var block = new ASNSlider(el);
    
    block.title.addEvents({
      'click': function(){
        if( ($time() - this.lastRun) > this.duration ) this.toggle();
      }.bind(block),
      
      'mouseover': function(){
        this.setStyle('cursor', 'pointer')
      }
    });
  });
});


/**** Class definition ****/

/**
 * Creates necessary functions for the custom accordion for ASN Bank
 * 
 * @param {Object} el
 */
var ASNSlider = new Class({
  collapsed : false,
  title     : null,
  duration  : 250,
  lastRun   : null,
  
  initialize: function(el){
    this.infoBlock = el;
    this.title     = el.getFirst();
    this.content   = this.title.getNext();
    
    if( el.hasClass('collapse-block') ) this.collapsed = true;
    
    this.slide = new Fx.Slide(this.content, {duration: this.duration});
    
    if( this.collapsed ){
      this.slide.hide();
      this.infoBlock.addClass('block-collapsed');
      this.title.addClass('collapsed');
      
      if(! $defined(this.infoBlock.getNext()) ){
        this.title.addClass('collapsed-last');
      }
    }
    else {
      this.title.addClass('normal'); // so the toggling goes right
    }
  },
  
  toggle: function(){
    this.lastRun = $time();
    
    this.infoBlock.toggleClass('block-collapsed');
    this.slide.toggle();
    this.title.toggleClass('collapsed');
    this.title.toggleClass('normal');
    
    // check if this is last item-block, or if theres an open block after it
    if(! $defined(this.infoBlock.getNext()) ||
        ($defined(this.infoBlock.getNext()) && this.infoBlock.getNext().getFirst().hasClass('normal')) ){
      this.title.addClass('collapsed-last');
    }
    else{
      this.title.removeClass('collapsed-last');
    }
    
    // check if previous item-block is collapsed or not
    if( $defined(this.infoBlock.getPrevious()) && this.infoBlock.getPrevious().getFirst().hasClass('collapsed') ){
      if( this.infoBlock.hasClass('block-collapsed') ){
        this.infoBlock.getPrevious().getFirst().removeClass('collapsed-last');
      }
      else {
        this.infoBlock.getPrevious().getFirst().addClass('collapsed-last');
      }
    }
  }
});
