var col_num = 3;
var col_width = 160;
var col_margin = 2; 
var list_x = 0;
var list_y = 0;
var list_max_x = new Array();

function arrange() {

	// calculate number of columns that fit into the body with
	var numColumns = parseInt(($('body').innerWidth() - 382) / (col_width + col_margin))
	
	// constraint to lower bound
	var columns = Math.max(col_num, numColumns);
	// constraint to upper bound
	columns = Math.min(columns, 10);
	
	$('.item').css('width', col_width  + '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) + 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() {
	var offset = $('#list_items').offset();
	if (offset) {
		list_y = offset.top;
		list_x = offset.left;
	}
	arrange();
});

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

arrange();
