var cacheOutput = function(func) {
	var cache = {};
	return function() {
		var args = [].splice.call(arguments, 0);
		var key = args.length+'|'+args.join('|');
		if (cache[key] === undefined)
			cache[key] = func.apply(this, arguments);
		return cache[key];
	};
};

var SectionTreeTree = function(el) {
	var that = this;
	el = jQuery(el);

	var getItems = cacheOutput(function() {
		var items = [];
		el.children('ul').children('li').each(function() {
			var item = new SectionTreeLi1(this, that);
			items.push(item);
		});
		return items;
	});

	var adjust = function() {
		var items = getItems();
		for (var i = 0; i < items.length; i++)
			items[i].adjust();

		var activeItem = getActiveItem();
		if (activeItem) {
			var height = activeItem.el.children('ul').height() + 8;
			var origHeight = el.height();
			var isIe7 = $.browser.msie && $.browser.version.slice(0, 1) == '7';
			if (height > origHeight && !isIe7)
				el.css({ height: height });
		}
	};

	var getActiveItem = function() {
		var items = getItems();
		for (var i = 0; i < items.length; i++) {
			var li = items[i].el;
			if (!li.find('li').length)
				continue;
			if (!li.hasClass('active-parent') && !li.hasClass('active'))
				continue;
			return items[i];
		}
		return null;
	};

	var initialize = function() {
		adjust();
	};

	initialize();
};

var SectionTreeLi1 = function(el, tree) {
	var that = this;
	that.el = jQuery(el);

	that.getChildren = cacheOutput(function() {
		var children = [];
		that.el.children('ul').children('li').each(function() {
			var child = new SectionTreeLi2(this, that);
			children.push(child);
		});
		return children;
	});

	that.adjust = function() {
		var ul = that.el.children('ul');
		if (!ul.length)
			return;
		var a = that.el.children('a');
		var left = a.width() + 7;
		ul.css({ left: left + 'px' });
	};
};

var SectionTreeLi2 = function(el, parent) {
	var that = this;
	that.el = jQuery(el);
};

