(function() {

	SL.ui.Expandable = Class.create(SL.Component, {

		init : function() {

			this.config.setDefault('duration', 0);
			this.config.setDefault('state_url', null);
			this.config.setDefault('css_prefix', 'expandable');
			this.config.setDefault('button_class', this.config.get('css_prefix') + '_btn');

			var head = this.e.down();
			var btns = this.e.select('.' + this.config.get('button_class'));

			this.img = btns[0] ? btns[0].down() : false;
			this.body = head.next().down();

			var style = this.body.getStyle('display');
			this.expanded = !style || style == 'block';
		},

		toggle : function() {
			if (this.expanded) {
				this.hide();
			} else {
				this.show();
			}

			var stateURL = this.config.get('state_url');

			if (stateURL) {
				var url = stateURL + '&args.state=';
				if (this.expanded) {
					url += 'true';
				} else {
					url += 'false';
				}
				new Ajax.Request(url, {
					method : 'get'
				});
			}
		},

		_getImgURL : function(img) {
			if (!this.img) {
				return;
			}

			var pos = this.img.src.lastIndexOf('/');
			var pos2 = this.img.src.lastIndexOf('_');

			if (pos2 > pos) {
				pos = pos2;
			}

			if (pos < 0) {
				return;
			}

			return this.img.src.substring(0, pos + 1) + img + '.png';
		},

		show : function() {
			this.e.addClassName('active');
			this.e.removeClassName('inactive');

			var duration = this.config.get('duration');
			if (duration <= 0) {
				this.body.setStyle('display:block');
			} else {
				SL.effects.resetCurrent(this.body);
				this.body.setStyle({
					overflow : 'hidden'
				});
				SL.effects.registerCurrent(Effect.BlindDown(this.body, {
					'duration' : duration / 1000.0
				}));
			}
			this.img.src = this._getImgURL('up');
			this.expanded = true;
		},

		hide : function() {
			this.e.removeClassName('active');
			this.e.addClassName('inactive');

			var duration = this.config.get('duration');
			if (duration <= 0) {
				this.body.setStyle('display:none');
			} else {
				SL.effects.resetCurrent(this.body);
				this.body.setStyle({
					overflow : 'hidden'
				});
				SL.effects.registerCurrent(Effect.BlindUp(this.body, {
					'duration' : duration / 1000.0
				}));
			}
			this.img.src = this._getImgURL('down');
			this.expanded = false;
		}
	});

})();

