/*
 * jQuery Tilelist Plugin. Arranges tiles in viewport horizontal uniformly
 * http://adresvseti.ru/
 * Copyright (c) 2010 Melnikov Alexey
 * Version: 1.0 (19/08/2010)
 * Requires: jQuery v1.4.2 or later, jQuery resize event - v1.1 or later
 *
 *
 * 10.09.2010: Default values reads from tiles elements
 *
 */
;(function($) {

var ver = '1.0.1.1';

$.fn.initHMargin = null;
$.fn.initVMargin = null;

$.fn.tilelist = function(options) 
{
	return this.each(function() 
	{
        options = options || {};
		
		// merging options		
		var opts = $.extend({}, $.fn.tilelist.defaults, options);
		
		// rendering tilelist
		renderTile(this, opts);
		
		// binding resize event handler
		$(this).resize(function(e)
		{
			// re-rendering tilelist
			renderTile(this, opts);
		});
    });
};

// renders tilelist
function renderTile(tilelist, opts)
{
	// retrieving tile list width
	var tilelistWidth = $(tilelist).width();
	
	// getting children
	var children = $(tilelist).children();
	if (!children.length)
	{
		// no one child in tile
		return;
	}
	
	// retrieving tile width
	var tileWidth = $(children).width();
	if (!tileWidth)
	{
		// invalid tile width
		return;
	}
	
	// calculations
	var countPerRow = Math.floor(tilelistWidth / tileWidth);	
	var paddingSpace = tilelistWidth - countPerRow * tileWidth;
	var tilePadding = paddingSpace / (countPerRow - 1);

	// reading initial margins
	if (tilelist.initVMargin == null)
	{
		tilelist.initVMargin = parseInt($(children).css("margin-bottom"));
	}
	if (tilelist.initHMargin == null)
	{
		tilelist.initHMargin = parseInt($(children).css("margin-right"));
	}

	// adapting count per row 	
	while (tilePadding < tilelist.initHMargin)
	{
		countPerRow--;
		paddingSpace = tilelistWidth - countPerRow * tileWidth;
		tilePadding = paddingSpace / (countPerRow - 1);
	}
	
	// updating margins of tiles
	for (var i = 0; i < children.length; i++)
	{
		var tile = children[i];

		// horizontal margin
		if (((i + 1) % countPerRow) == 0)
		{
			// last tile in the row
			$(tile).css("margin-right", "0px");
		}
		else
		{
			$(tile).css("margin-right" , tilePadding + "px");
		}
		
		// vertical margin
		$(tile).css("margin-bottom" , tilelist.initVMargin + "px");
	}	
}

// returns plugin version
$.fn.tilelist.ver = function() { return ver; };

// default options
$.fn.tilelist.defaults = {
    //marginVertical:		100, // vertical space between tiles
};

})(jQuery);

