// JavaScript Document
var AutoLayout = function(boxes, gridTileSize)
{
	this.gridCache = new AutoLayout.GridCache(gridTileSize);
	this.boxes = boxes;
	this.currentPage = 0;
	this.totalHeight = 0;
	this.totalWidth = 0;
	this.lastBoxTopOffset = 0;
	this.pageEdges = [];
};
/*
AutoLayout.rearrange = function(boxes, gridTileSize)
{
	return new AutoLayout(boxes, gridTileSize).arrange();
};
AutoLayout.prototype.onResize = function()
{
	this.arrange();
	this.draw(1000);
};*/
AutoLayout.prototype.arrange = function()
{
	this.totalHeight = 0;
	this.totalWidth = 0;
	this.gridCache.clear();
	var w = $(window).width();
	for(var i = 0; i < this.boxes.length; i++)
		if(this.boxes[i].width > w)
			w = this.boxes[i].width;

	this.currentPage = 0;
	var lastBox = null;
	for(var i = 0; i < this.boxes.length; i++)
	{
		var b = this.boxes[i];
		var targetPosition = this.calculateTarget(b, w);
		var e = this.pageEdges[b.page];
		if(e == undefined || targetPosition.y > e)
			this.pageEdges[b.page] = targetPosition.y;
		b.x = targetPosition.x;
		b.y = targetPosition.y;
		
		if(b.y + b.height > this.totalHeight)
			this.totalHeight = b.y + b.height;
		
		if(b.x + b.width > this.totalWidth)
			this.totalWidth = b.x + b.width;
		lastBox = b;
	}
	if(lastBox !== null)
		this.lastBoxTopOffset = this.totalHeight - lastBox.height;
};
AutoLayout.prototype.calculateTarget = function (box, w)
{
	//if(w < this.tileSize)
	//	throw "Window width must be above tileSize";
	var y = 0;
	if(box.page > 0 && this.pageEdges[box.page - 1] != undefined)
		y = this.pageEdges[box.page - 1];
	//Ali.log("Y: " + y);
	while(true && y < 100000)
	{
		for(var x = 0; x < w; x+= this.gridCache.tileSize)
		{
			if(typeof box.width != "number" || typeof box.height != "number")
			{
				alert ("numberfail");
				return null;
			}
			if(x + box.width < w && this.gridCache.isFree(x, y, box.width, box.height))
			{
				this.gridCache.setUsed(x, y, box.width, box.height);
				//this.gridCache.setFree(xIndex, yIndex, false);
				return{ x: x, y: y };
			}
			
		}//if(this.isFree(xIndex, yIndex))
		y+= this.gridCache.tileSize;
	}
	alert("fail");
};
