// accordion.js v2.0
//
// Copyright (c) 2007 stickmanlabs
// Author: Kevin P Miller | http://www.stickmanlabs.com
// 
// Accordion is freely distributable under the terms of an MIT-style license.
//
// I don't care what you think about the file size...
//   Be a pro: 
//	    http://www.thinkvitamin.com/features/webapps/serving-javascript-fast
//      http://rakaz.nl/item/make_your_pages_load_faster_by_combining_and_compressing_javascript_and_css_files
//

/*-----------------------------------------------------------------------------------------------*/

if (typeof Effect == 'undefined') 
	throw("accordion.js requires including script.aculo.us' effects.js library!");

var accordion = Class.create();
accordion.prototype = {
	showAccordion : null,
	currentAccordion : null,
	duration : null,
	effects : [],
	animating : false,
	initialize: function(container, options) {
		if (!$(container)) {
			throw(container+" doesn't exist!");
			return false;
		}  
		this.options = Object.extend({
			resizeSpeed : 9,
			classNames : {
				toggle : 'accordion_toggle',
				toggleActive : 'accordion_toggle_active',
				content : 'accordion_content'
			},
			onEvent : 'click'
		}, options || {});
		this.duration = ((11-this.options.resizeSpeed)*0.15);
		var accordions = $$('#'+container+' .'+this.options.classNames.toggle);
		accordions.each(function(accordion) {
			Event.observe(accordion, this.options.onEvent, this.activate.bind(this, accordion), false);
			if (this.options.onEvent == 'click') {
				accordion.onclick = function() { return false; };
			}
		}.bind(this));
	},
	activate : function(accordion) {
		if (this.animating) return false;		
		this.effects = [];
		this.currentAccordion = $(accordion.next(0));		
		this.currentAccordion.previous(0).addClassName(this.options.classNames.toggleActive);
		if (this.currentAccordion == this.showAccordion) {
			this.deactivate();
		} else {
			this._handleAccordion();
		}
	},
	deactivate : function() {
   	 	this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);
		new Effect.BlindUp(this.showAccordion, { duration: this.duration });
		this.showAccordion = null;
	},
	_handleAccordion : function() {
		if(this.currentAccordion) {
			this.effects.push(
				new Effect.BlindDown(this.currentAccordion, { duration: this.duration })
			);
		}
		if(this.showAccordion) {
			this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);
			this.effects.push(
				new Effect.BlindUp(this.showAccordion, { duration: this.duration })
			);				
		}
		if(this.effects.length > 0) {
			new Effect.Parallel(this.effects, {
				duration: this.duration,
				queue: {
					position: 'end', 
					scope: 'accordionAnimation'
				},
				beforeStart: function() {
					this.animating = true;
				}.bind(this),
				afterFinish: function() {
					this.showAccordion = this.currentAccordion;
					this.animating = false;
				}.bind(this)
			});
		}
	}
}
	