// JavaScript Document
/*
	Author: Willy
	Modified: 2008/11/28
*/
tagala.packs.push('layout');
tagala.Layout = Class.create(
{
	initialize:function ()
	{
		this.splitter = new tagala.Splitter();
		this.splitter.register(
		{
			onResize:this.adjustByFx.bind(this)
		});
		$$('div[splitter]').each(function(el)
		{
			this.splitter.createResizeHandles(el, $(el).readAttribute('splitter'));
		}, this);

		Event.observe(window, 'resize', this.adjustByFx.bind(this));
		this.adjustByFx();
	},

	adjustByFx:function ()
	{
		$$('div').each(this.resizeBlock.bind(this));
		this.resizeBlock(document.body);
		if (Object.isFunction(window.onResizeWin)) onResizeWin();
	},

	resizeBlock:function (el)
	{
		var fx, styles = {};
		if (!(el = $(el))) return;

		if (fx = el.readAttribute('topFx'))
			styles.top = this.caculateFx(fx, 'top', 0) + 'px';
		if (fx = el.readAttribute('leftFx'))
			styles.left = this.caculateFx(fx, 'left', 0) + 'px';
		if (fx = el.readAttribute('heightFx'))
			styles.height = this.caculateFx(fx, 'height', 0) + 'px';
		if (fx = el.readAttribute('widthFx'))
			styles.width = this.caculateFx(fx, 'width', 0) + 'px';
		if (fx = el.readAttribute('minHeightFx'))
			styles.minHeight = this.caculateFx(fx, 'height', 0) + 'px';
		if (fx = el.readAttribute('minWidthFx'))
			styles.minWidth = this.caculateFx(fx, 'width', 0) + 'px';
		if (fx = el.readAttribute('marginLeftFx'))
			styles.marginLeft = this.caculateFx(fx, 'width') + 'px';
		if (fx = el.readAttribute('marginRightFx'))
			styles.marginRight = this.caculateFx(fx, 'width') + 'px';
		if (fx = el.readAttribute('marginTopFx'))
			styles.marginTop = this.caculateFx(fx, 'height') + 'px';
		if (fx = el.readAttribute('marginBottomFx'))
			styles.marginBottom = this.caculateFx(fx, 'height') + 'px';
		el.setStyle(styles);
	},

	caculateFx:function (fx, mode, min)
	{
		var regExp = /\b\w+\b/g, matchResult;
		var node, size, result = 0;
		fx.match(regExp).each(function (nodeId)
		{
			var node;
			if (node = (nodeId === 'body') ? $(document.body) : $(nodeId))
				fx = fx.replace(nodeId, node[['top', 'left'].include(mode) ? 'cumulativeOffset' : 'getDimensions']()[mode]); 
		});
		try
		{
			result = eval(fx);
			if (!isNaN(min) && result < min) result = min;
		}
		catch (ex) {}
		return result;
	}
});
