/**
 * Grid-A-Licious(tm)
 * Copyright (c) 2008 Suprb - info(at)suprb(dot)com
 *
 * License Agreement: By downloading Grid-A-Licious(tm),
 * you agree to the following: The copyright information
 * must remain intact in the product.
 *
 * The product may be used for personal use only, no
 * commercial projects. You are not free to remove the
 * copyright information (anywhere).
 *
 * You are not free to use or copy any of the
 * "grid-a-licious.js" (this file) code on your own products
 * without asking for permission.
 *
 * Thanks for understanding.
 */
/**
 * Modified by Daniel Frett
 *
 * cleaned up several math related issues with calculating positioning and size of boxes
 * added support for understanding centered boxes
 */

	var MIN_COLS = 5;
	var COL_WIDTH = 220;
	var GAP = 30;

	var offx, offy = 0;
	maxy = new Array();

	// on site load (DOM READY)
	$(document).ready(function() {
		offy = $('#allposts').offset().top;
		offx = $('#allposts').offset().left;
		arrange();
		$(window).load(function() {
			arrange();
		});
	});

	// on window resize, call again
	$(window).resize( function() { arrange(); } );

	function arrange() {

		// how many columns fits here?
		var columns = Math.max(MIN_COLS, parseInt($('body').innerWidth() / (COL_WIDTH+GAP)));
		$('.eachpost').css('width', COL_WIDTH);
		$('.eachpost.twocols').css('width', COL_WIDTH * 2 + GAP);
		$('.eachpost.threecols').css('width', COL_WIDTH * 3 + GAP*2);

		for (x=0; x < columns; x++) {
			maxy[x] = 0;
		}

		// lets iterate over all posts
		$('.eachpost').each(function(i) {
			var pos, cursor, w , altura= 0;

			w = (Math.floor(($(this).outerWidth() + GAP) / (COL_WIDTH + GAP)));
			pos = 0;

			var pos = -1;
			var posTop = -1;

			//find the position based on the set of columns with the highest possible top value that doesn't overlap other boxes
			for(var x=0; x < columns-(w-1); x++) {
				var top = -1;
				for(var y=x; y < x+w; y++) {
					top = (top === -1 || maxy[y] > top) ? maxy[y] : top;
				}

				if(posTop === -1 || top < posTop) {
					pos = x;
					posTop = top;
				}
			}

			//this is a centered box, so override the default position
			if($(this).hasClass('centered')) {
				pos = Math.floor((columns - w) / 2);
				posTop = -1;

				for(var x=pos; x < pos+w; x++) {
					posTop = (posTop === -1 || maxy[x] > posTop) ? maxy[x] : posTop;
				}
			}

			//place this box
			$(this).css('left', pos*(COL_WIDTH+GAP) + offx).css('top', posTop + offy);

			//update all columns that this box spans
			for(var x = pos; x < pos + w; x++) {
				maxy[x] = posTop + $(this).outerHeight() + GAP;
			}
		});
	}

