/*
 * Expandbox
 */

if(typeof Effect == "undefined") throw ("DI.ExpandBox works with Scriptaculous Effects.");
if(typeof DI == "undefined"){
	var DI = {};
	var self = "di-expandbox.js";
	var path = $$("head script[src*='" + self + "']").first().src.replace(self, '');
	document.write('<script type="text/javascript" src="' + path + 'di-framework.js"><\/script>');
}

Object.extend(DI, {
	ExpandBox : Class.create({
		_container	: null,
		_options	: null,
		_boxes		: null,
		_effects	: null,
		_animating	: null,
		_state		: null,
		
		initialize : function(container, options) {
			if(typeof container == "string") container = $(container);
			this._container = container;
			this._options = Object.extend({
				boxClassname	: "expand-box",
				duration		: 1
			}, options);
			this._boxes = [];
			this._animating = false;
			this._state = "collapsed";
			
			$$("." + this._options.boxClassname).each(function(node){
				node.setStyle({
					height : 0
				});
				this._boxes.push(node);
			}, this);
		},
		
		expandAll : function() {
			if(this._animating) return;
			
			this._effects = [];
			
			this._boxes.each(function(node){
				node.setStyle({
					display : "block"
				});
				var optionsFX = {
					sync			: true,
					scaleFrom		: 0,
					scaleContent	: false,
					transition		: Effect.Transitions.sinoidal,
					scaleMode : {
						originalHeight	: node.scrollHeight
					},
					scaleX			: false,
					scaleY			: true
				};
				this._effects.push(new Effect.Scale(node, 100, optionsFX));
			}, this);
			
			new Effect.Parallel(this._effects, {
				duration	: this._options.duration,
				queue		: {
					position	: "end",
					scope		: "expandBoxAnimation"
				},
				beforeStart	: function() {
					this._animating = true;
					this._state = "expanded";
				}.bind(this),
				afterFinish : function() {
					this._animating = false;
				}.bind(this)
			});
		},
		
		collapseAll : function() {
			if(this._animating) return;
			
			this._effects = [];
			
			this._boxes.each(function(node){
				var optionsFX = {
					sync			: true,
					scaleContent	: false,
					transition		: Effect.Transitions.sinoidal,
					scaleMode : {
						originalHeight	: node.offsetHeight
					},
					scaleX			: false,
					scaleY			: true
				};
				this._effects.push(new Effect.Scale(node, 0, optionsFX));
			}, this);
			
			new Effect.Parallel(this._effects, {
				duration	: this._options.duration,
				queue		: {
					position	: "end",
					scope		: "expandBoxAnimation"
				},
				beforeStart	: function() {
					this._animating = true;
					this._state = "collapsed";
				}.bind(this),
				afterFinish : function() {
					this._animating = false;
				}.bind(this)
			});
		},
		
		toggle : function() {
			if(this._state == "collapsed"){
				this.expandAll();
			}else{
				this.collapseAll();
			}
			return this._state;
		}
	})
});