/**
 * Accordion
 * 
 * @require     MooTools
 * 
 * @author      Sebastian Kenk <s.kenk@netzbewegung.com>
 * @version     1.00 beta
 */

Nb_Accordion = new Class({

    initialize: function(element)
    {
        this.element = element;
        
        this.currentExpanded = null;
        
        this.element.getElements('.accordion-title').each(function(element)
        {
            element.addEvent('click', this.onClick.create({bind: this, event: true, arguments: element}));
        }.bind(this));
    },

    onClick: function(event, titleElement)
    {
        event.stop();
        
        var textElement = titleElement.getNext('.accordion-content');
        
        if (this.currentExpanded && this.currentExpanded == textElement && titleElement.hasClass('active'))
        {
            this.collapse(this.currentExpanded);
            return;
        }
        
        if (this.currentExpanded)
        {
            this.collapse(this.currentExpanded);
        }
        
        this.expand(textElement);
    },

    expand: function(textElement)
    {
        this.currentExpanded = textElement;
        
        var titleElement = textElement.getPrevious('.accordion-title');
        
        textElement.setStyle('height',  0);
        textElement.setStyle('display', 'block');

        var textBodyElement = textElement.getChildren('.accordion-content-body')[0];
        var height = textBodyElement.getSize().y + 10;

        textElement.tween('height', height);
        
        titleElement.addClass('active');
        
    },

    collapse: function(textElement)
    {
        this.currentExpanded = null;
        
        var titleElement = textElement.getPrevious('.accordion-title');
        
        var animation = new Fx.Tween(textElement, {
            onComplete: function()
            {
                this.element.setStyle('display', 'none');
            }
        });
        
        titleElement.removeClass('active');
        
        animation.start('height', 0)
    }
});

