var col_num = 3;
var col_width = 240;
var col_margin = 5; 
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() - 240) / (col_width + col_margin)));
	$('.item').css('width', col_width  + 'px');
	$('.twocols').css('width', col_width * 2 + col_margin);
	$('.threecols').css('width', col_width * 3 + (col_margin * 2));

	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) + list_x).css('top',item_height + list_y);
		}
		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) + list_x).css('top', list_max_x[item_pointer] + list_y);
			list_max_x[item_pointer] += $(this).outerHeight() + col_margin + 20;
		}
	});
}

$(window).load(function() {
	list_y = $('#list_items').offset().top;
	list_x = $('#list_items').offset().left;
	arrange();
});

$(window).resize(function() {
	arrange();
	
});

arrange();