/**
 * Grid-A-Licious(tm) v1.1
 * Copyright (c) 2008-09 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 = 3;
	var COL_WIDTH = 240;
	var GAP = 0; 
	var offx = 40;
	var offy = 100;
	maxy = new Array();

	$(function() {
		COL_WIDTH = parseInt($('.eachpost:first').outerWidth());
//		offy = $('#grid').offset().top - 120; 
//		offx = 40; 
		arrange(); 
		$('img').bind('load', function() { arrange(); })
	});
	
	$(window).bind('resize', function() {
		arrange();
	})

	function arrange() {
	    
		var columns = Math.max(MIN_COLS, (Math.ceil(($(window).width() - offx) / (COL_WIDTH)) - 1));
		var leftm;
		var eachpostcount;
		
		$('.eachpost').css('width',COL_WIDTH  + 'px');
		$('.pag').css('width', COL_WIDTH*columns + GAP*(columns-1));

		eachpostcount = $('.eachpost').size();

		$("#mnu").css("right", ($(window).width() - ((columns) * COL_WIDTH)) );
		
		$("#infopopup div").css("padding-left", (offx + ((columns - 1)* COL_WIDTH)) - 530);
		
		
		for (x=0; x < columns; x++) {
			maxy[x] = 0;
		}
		
		$('.eachpost').each(function(i){
		
			$(this).css('visibility','visible');
			
			var pos, cursor, w , altura= 0;
			w = (Math.round($(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;
				}
	
				$(this).css('left', cursor*(COL_WIDTH+GAP) + offx).css('top',maxy[cursor] + offy);
				maxy[cursor] += $(this).outerHeight() + GAP;
			}
		});
		
		
		
	}
