﻿var slidingAccordion = Class.create();
Object.extend(slidingAccordion.prototype, {
	initialize : function(_parent, _default, _options) {
		this.effectFX	= null;
		this.buttons	= Selector.handlers.tagName([_parent], null, "DT", "child");
		this.current	= _default;
		this.options	= Object.extend({
			"duration": 3000,
			"mouseover": false,
			"click": true,
			"activeStyle": {
				"backgroundColor": "#aea",
				"color": "#000"
			},
			"deactiveStyle": {
				"backgroundColor": "",
				"color": ""
			}
		}, _options || {});

		$A(this.buttons).each(
			(function(_button) {
				_button = $(_button);
				if (_default != _button) this.hide(_button);
				this.bindButtonAction(_button);
			}).bind(this)
		);
		this.afterActive(this.current);

		if (this.options.getContentFromButton)	this.getContentFromButton = this.options.getContentFromButton;
		if (this.options.afterActive)			this.afterActive = this.options.afterActive;
		if (this.options.afterDeactive)			this.afterDeactive = this.options.afterDeactive;
	},
	bindButtonAction: function(_button) {
		if (this.options.click)
			Event.observe(_button, 'click',		this.changeActive.bind(this, _button), false);
		if (this.options.mouseover)
			Event.observe(_button, 'mouseover',	this.changeActive.bind(this, _button), false);
	},
	hide: function(_button) {
		var e = this.getContentFromButton(_button);
		if (e) e.hide();
		this.afterDeactive(_button);
	},
	changeActive: function(_newButton) {
		var eNew = this.getContentFromButton(_newButton);
		var eOld;
		if (this.current) eOld = this.getContentFromButton(this.current);
		if (!eNew || eNew == eOld) { return; }

		if (this.effectFX && this.effectFX.state === "running") return;
		if (this.effectFX) $A(this.effectFX.effects).each(function(_effect) {_effect. cancel(); });
		var aryEffect = [ new Effect.BlindDown(eNew) ];
		if (eOld) {
			aryEffect.push(new Effect.BlindUp(eOld));
		}
		var that = this;
		this.effectFX = new Effect.Parallel(aryEffect, {
			"afterFinish": (function(_this, _oldButtion) { return function(_effect) {
				that.current = _newButton;
				if (_oldButtion) _this.afterDeactive(_oldButtion, _effect);
				_this.afterActive(_newButton, _effect);
			}; })(this, this.current)
		});

	},
	getContentFromButton: function(_button) {
		return _button.next();
	},
	afterActive: function(_button, _effect) {
		_button.setStyle(this.options.activeStyle);
	},
	afterDeactive: function(_button, _effect) {
		_button.setStyle(this.options.deactiveStyle);
	}
});
