﻿var AutoFit = Class.extend
({
	offsetHeight: 0,
	minHeight: 300,
	containerId: null,
	padding: 5,

	init: function(config) {
		jQuery.extend(this, config);

		if (this.containerId == null)
			return;

		window.auinUse = false;
		this.registerEvents();
		this.onWindowResize(true);
	},

	get_container: function() {
		return $('#' + this.containerId);
	},

	get_size: function(control) {
		return { width: control.width(), height: control.height() };
	},

	registerEvents: function() {
		var ds = this;
		$(window).bind("resize.inner.af", function(event) { ds.onWindowResize(true); });
		$(window).bind("resize.af", function(event) { ds.onWindowResize(false); });
	},

	onWindowResize: function(inner) {
		if (window.auinUse)
			return;
		if (this.containerId == null)
			return;

		window.auinUse = true;

		var windowHeight = this.get_size($(window)).height;
		var resizeHeight = this.get_size(this.get_container()).height;
		var childHeight = resizeHeight;

		var child = this.get_container().attr("firstChild");

		while (child != null && child.tagName != 'DIV')
			child = child.nextSibling;

		if (child != null)
			childHeight = child.scrollHeight + this.padding;

		var height = resizeHeight;

		if (this.offsetHeight > 0)
			height = windowHeight - this.offsetHeight;

		if (this.minHeight > height)
			height = this.minHeight;

		if (resizeHeight <= childHeight && resizeHeight >= height) {
			this.get_container().css("height", "auto");
			window.setTimeout("this.auinUse = false;", 100);
			return;
		}

		if ((resizeHeight <= height || childHeight <= height) && inner == true) {
			this.get_container().css("height", height + "px");
		}
		window.setTimeout("this.auinUse = false;", 100);
	}
})
