/**
 * 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.
 */

	var MIN_COLS = 1;
	var COL_WIDTH = 320;
	var GAP = 10; 
	var started=false;
	var offx = 0;
	var offy = 0;
	var columns=0;
	maxy = new Array();
	
	// on site load (DOM READY)
	$(function() { 
		offy = $('#allposts').offset().top;
		offx = $('#allposts').offset().left;
		arrange();
		
	});
	
	// on window resize, call again
	$(window).resize( function() { arrange();started=true; } );
	
	arrange();
	
	function arrange() {
		var z=0;
		// how many columns fits here?
		var columns = Math.max(MIN_COLS, parseInt($('body').innerWidth() / (COL_WIDTH+GAP)));
		var space=Math.max(0,$('body').innerWidth()-columns*(COL_WIDTH+GAP)-offx-GAP);
		
		$('.eachpost').css('width',COL_WIDTH  + 'px');
		$('.twocols').css('width', COL_WIDTH*2 + GAP  );
		$('.threecols').css('width', COL_WIDTH*3 + GAP*2);
		//alert(space);
		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() / COL_WIDTH));
			cursor = 0;

			if (w>1) {
				for (x=0; x < columns-(w-1); x++) {
					cursor = maxy[x] < maxy[cursor] ? x : cursor;
				}
				pos = cursor;
				
				for (var x=0; x<w; x++) {
					altura = Math.max(altura, maxy[pos+x]);
				}
				for (var x=0; x<w; x++) 
					maxy[pos+x] = parseInt($(this).outerHeight()) + GAP + altura;
					
				$(this).css('left', pos*(COL_WIDTH+GAP) + offx).css('top',altura + offy);
			}
			else {
			
				for (x=0; x < columns; x++) {
					cursor = maxy[x] < maxy[cursor] ? x : cursor;
				}
				//*from left to right
				//cursor=z%columns;
				//z++;
			
				//$(this).css('left', cursor*(COL_WIDTH+GAP) + offx).css('top',maxy[cursor] + offy);
				
				if(started){
					$(this).stop().animate({
						left:cursor*(COL_WIDTH+GAP) + offx+space/2,
						top:maxy[cursor] + offy},200+i*20);
				}else{
					$(this).css('left', cursor*(COL_WIDTH+GAP) + offx+space/2).css('top',maxy[cursor] + offy);
				}
				maxy[cursor] += $(this).outerHeight() + GAP;
			}
		
		});
			$('#becklyn').css('margin-left',space/2);
			$('#becklyn').css('margin-right',space/2);
		var maxH=0;
		for(i=0;i<maxy.length;i++){
			if(maxy[i]>maxH){
				maxH=maxy[i];
			}
			
		}
		$('#footer').css('top',maxH+offy);
	
	}
