(function($j)
{
	$j.fn.rowify = function(children)
	{
		var rows = [];
		
		this.each(function()
		{
			function handleRow()
			{
				if (row.length)
				{
					var wrapper = $j(row).wrapAll('<div />').parent();
					rows.push(wrapper[0]);
					
					row = [];
				}
			}
 
			function handleImage(invoker)
			{
				if (++completedImages === images.length)
				{
					rowify();
				}
			}
			
			function rowify()
			{
				items.each(function(i)
				{
					var
						that = $j(this),
						
						width = that.outerWidth(true);
					
					// In the same row.
					if (restWidth - width >= 0)
					{
						restWidth -= width;
					}
					// New row.
					else
					{
						restWidth = containerWidth - width;
						
						// Handle previous row.
						handleRow();
					}
					
					row.push(this);
				});
				
				handleRow();
			}
			
			var
				that = $j(this),
				
				items = that.find(children),
				
				row = [],
				
				containerWidth = that.width(),
				
				restWidth = 0,
				
				images = that.find('img'),
				
				completedImages = 0;
			
			if (images.length)
			{
				images.each(function()
				{
					if (this.complete)
					{
						handleImage.call(this);
					}
					else
					{
						this.onload = this.onerror = this.onabort = handleImage;
					}
				});
			}
			else
			{
				rowify();
			}
		});
		
		return $j(rows);
	};
})
(jQuery);

