/**
 
 * This script is free to be used by anyone anywhere at any time, no copyright credits required.
 * This script is a contribution to the open source Wordpress community.
 * If you don't like to share, then develop in some other platform, suckas.
 */

	var MIN_COLUMNS = 2;
	var COLUMN_WIDTH = 188;
	var SIDEGAP = 12; 
	var TOPGAP = 6;
	
	var offx, offy = 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() {
offy = $('#allposts').offset().top;
offx = $('#allposts').offset().left;
arrange();
});

	
	function arrange() {
	
		// how many columns fits here?
		var columns = Math.max(MIN_COLUMNS, parseInt($('body').innerWidth() / (COLUMN_WIDTH+SIDEGAP)));
		$('.eachpost').css('width',COLUMN_WIDTH  + 'px');
		$('.twocols').css('width', COLUMN_WIDTH*2 + SIDEGAP  );
		$('.threecols').css('width', COLUMN_WIDTH*3 + SIDEGAP*2);
		$('.fivecols').css('width', COLUMN_WIDTH*5 + SIDEGAP*4);

		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() / COLUMN_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()) + TOPGAP + altura;
					
				$(this).css('left', pos*(COLUMN_WIDTH+SIDEGAP) + offx).css('top',altura + offy);
			}
			else {
			
				for (x=0; x < columns; x++) {
					cursor = maxy[x] < maxy[cursor] ? x : cursor;
				}

				$(this).css('left', cursor*(COLUMN_WIDTH+SIDEGAP) + offx).css('top',maxy[cursor] + offy);
				maxy[cursor] += $(this).outerHeight() + TOPGAP;
			}
		});
	
		
	}

