var col_num = 4;
var col_width = 150;
var col_margin = 4; 
var list_x = 0;
var list_y = 0;
var list_max_x = new Array();
 
function arrange() {
 
	var columns = Math.max(col_num, parseInt(($('body').innerWidth() - 300) / (col_width + col_margin)));
	$('.item').css('width', col_width  + 'px');
	$('.twocols').css('width', col_width * 2 + col_margin + 'px');
	$('.threecols').css('width', col_width * 3 + (col_margin*2) + 'px');
	$('.forcols').css('width', col_width * 4 + (col_margin*3) + 'px');
 
	for (var i=0; i < columns; i++) {
		list_max_x[i] = 0;
	}
	
	$('.item').each(function(i) {
 
		var item_position = 0;
		var item_pointer = 0;
		var item_width = 0;
		var item_height= 0;
 
		item_width = (Math.floor($(this).outerWidth() / col_width));
		item_pointer = 0;
 
		if (item_width > 1) {
			for (i=0; i < columns - (item_width - 1); i++) {
				item_pointer = list_max_x[i] < list_max_x[item_pointer] ? i : item_pointer;
			}
			item_position = item_pointer;
			for (var i=0; i < item_width; i++) {
				item_height = Math.max(item_height, list_max_x[item_position+i]);
			}
			for (var i=0; i < item_width; i++) {
				list_max_x[item_position + i] = parseInt($(this).outerHeight()) + col_margin + item_height;
			}
			$(this).css('left', item_position * (col_width + col_margin)).css('top',item_height);
		}
		else {
			for (var i=0; i < columns; i++) {
				item_pointer = list_max_x[i] < list_max_x[item_pointer] ? i : item_pointer;
			}
			$(this).css('left', item_pointer * (col_width + col_margin)).css('top', list_max_x[item_pointer]);
			list_max_x[item_pointer] += $(this).outerHeight() + col_margin + 20;
		}
	});
}
 
$(window).load(function() {
	arrange();
});
 
$(window).resize(function() {
	arrange();
	
});
 
arrange();
