	var MIN_COLS = 2;
	var COL_WIDTH = 220;
	var GAP = 10; 
	var images_to_load = 0;
	var MARGIN_RIGHT = 230;
	
	var offx, offy = 0;
	maxy = new Array();

	
	// on site load (DOM READY)
	$(document).ready(function(){	
		sel = $('div#wrapper div.eachpost img');
		images_to_load = sel.length;
		
		sel.load(function(){
		
			images_to_load--;
			
			
			if (images_to_load <= 0 || images_to_load % 4 == 0){
				arrange();
			}
		
		});
		
		offy = $('#allposts').offset().top;
		offx = $('#allposts').offset().left;
		arrange(); 
	});
	
	// on window resize, call again
	$(window).resize( function() { arrange(); } );
	
	arrange();
	
	function arrange() {
	
		// how many columns fits here?
		var columns = Math.max(MIN_COLS, parseInt(($('body').innerWidth() - MARGIN_RIGHT) / (COL_WIDTH+GAP)));	
		$('div#wrapper div.eachpost').css('width',COL_WIDTH  + 'px');
		$('div#wrapper div.twocols').css('width', COL_WIDTH*2 + GAP  );
		$('div#wrapper div.threecols').css('width', COL_WIDTH*3 + GAP*2);

		var total_max_y=0;
		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);
				
					if(altura + offy +  parseInt($(this).outerHeight()) > total_max_y)
						total_max_y =altura + offy +  parseInt($(this).outerHeight());
			}
			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;
				
					if(maxy[cursor] + offy > total_max_y)
						total_max_y =maxy[cursor] + offy;
			}
		});
		
	
		
		$('#wrapper').css('height', Math.floor(total_max_y) + 'px').css('margin-bottom', '40px');
		
	}

