


Accordion = Class.create({
	
	container: null,
	options: null,
	currentPanel: null,
	animating: false,
	
    initialize:function(element, options) {
    	this.container = $(element);
    	
    	if ( !this.container )
    		throw Error('Accordion element does not exist.');
    		
    	this.options = Object.extend({
    		headerClass: 'accordion_header',
    		contentClass: 'accordion_content',
    		duration: 0.5
    	}, options || {});
    	
    	this.addBehaviors();
    },
    
    addBehaviors: function() {
    	$A(this.container.getElementsByClassName(this.options.headerClass)).each( function(headerElmt) {
    		headerElmt.setStyle({cursor:'pointer'});
    		headerElmt.next().wrap(new Element('div'));
    		if ( headerElmt.hasClassName('selected') && !this.currentPanel )
    			this.currentPanel = headerElmt;
    		else
    			headerElmt.next().hide();
    		
    		// Click handler:
    		headerElmt.observe( 'click', function() {
    			this.toggleContent(headerElmt);
    		}.bindAsEventListener(this));
    		// Roll overs:
    		headerElmt.observe( 'mouseover', function() {
    			headerElmt.addClassName('hover');
    		}.bindAsEventListener(this));
    		headerElmt.observe( 'mouseout', function() {
    			headerElmt.removeClassName('hover');
    		}.bindAsEventListener(this));
    	}.bind(this) );
    },
    
    toggleContent: function( headerElmt ) {
    	if ( this.animating ) return false;
    	this.animating = true;
    	
    	if ( Object.isElement(this.currentPanel) ) {
    		new Effect.SlideUp(
    			this.currentPanel.next(), {
    				duration: this.options.duration,
    				afterFinish: function() {
    					this.currentPanel.removeClassName('selected');
    					if ( headerElmt == this.currentPanel )
    						this.currentPanel = null;
    					this.animating = false;
    				}.bind(this)
    			}
    		);
    	}
    	
    	if ( headerElmt != this.currentPanel ) {
    		headerElmt.addClassName('selected');
    		new Effect.SlideDown(
    			headerElmt.next(), {
    				duration: this.options.duration,
    				afterFinish: function() {
    					this.currentPanel = headerElmt;
    					this.animating = false;
    				}.bind(this)
    			}
    		);
    	}
    }
});
    
Accordion.Widget = Class.create({
    initialize:function(options) {
        this.options = Object.extend({
            containerClass:null
        }, options || {});
        
        this.accordions = new Array();
        $$('.' + this.options.containerClass).each(
            function(accordion){
                this.accordions.push(new Accordion(accordion, this.options));
            }.bind(this)
        );
    }
});

var AccordionWidget;
document.observe('dom:loaded', function() {
	AccordionWidget = new Accordion.Widget({
		containerClass:'accordion'
	});
});

