var Foldouts = {
	bgTween: undefined,
	heightTween: undefined,

	init: function () {
		if (!$$('body')[0].hasClass('hasJS')) {
			$$('body')[0].addClass('hasJS');
		}

		$$('.foldout .handle').each(Foldouts.addClickEvent);
	},

	addClickEvent: function (handle) {
		handle.addEvent('click', Foldouts.openClose);
	},

	openClose: function () {
		//get the measurements of the handle and the content
		var contentHeight;
		if (this.getNext().getHeight() > 0) {
			contentHeight = this.getNext().getHeight();

		} else if (this.getParent().get('id') == 'map-holder') {
			contentHeight = 520;

		} else {
			contentHeight = this.getNext().setStyles({'display': 'block', 'height': ''}).getHeight();
			this.getNext().setStyle('height', 0);
		}

		//the scroller
		var windowScroller = new Fx.Scroll(window, {
			transition: 'linear',
			duration: 1000
		});

		//build the height tween object
		var heightTween = new Fx.Tween(this.getNext(), {
			property: 'height',
			transition: 'linear',
			duration: (contentHeight / 2).toInt(),
			onComplete: function () {
				if (this.element.getHeight() == 0) {
					this.element.getParent().removeClass('foldedout');
				}

				this.element.setStyles({'overflow': '', 'height': '', 'display': ''});
				Background.resize();

				if (this.element.getHeight() > 0) {
					var bodyHeight     = $$('body')[0].getSize().y;
					var viewportHeight = Background._getViewportDimensions().height;
					var scrollTo       = this.element.getParent().getPosition().y - 100;

					if (scrollTo > viewportHeight - bodyHeight) {
						windowScroller.toBottom();
					} else {
						windowScroller.start(0, scrollTo);
					}
				}
			}
		});

		this.getNext().setStyle('overflow', 'hidden');

		//fold in
		if (this.getParent().hasClass('foldedout')) {
			//windowScroller.start(0, 0);
			heightTween.start(contentHeight, 0);

		//fold out
		} else {
			this.getParent().addClass('foldedout');
			heightTween.start(0, contentHeight);
		}
	}
}

window.addEvent('domready', Foldouts.init);