/*!
 * Dynamic Layout Gallery v1.0
 * http://www.ilovemedia.es/
 *
 * Author: Raquel García Cabañas
 * raquel[at]ilovemedia[dot]es
 * http://www.ilovemedia.es
 * @rakelka
 *
 * License Creative Commons CC BY
 * http://creativecommons.org/licenses/by/3.0/
 *
 * Needs jQuery JavaScript Library
 * http://jquery.com/
 *
 * Date: 2011 May 1
 */

/*HTML
 *Use class="dynamicWidth" for all content you want, like body, section, etc., or only gallery
 *<head>
 *	...
 *   <!--JS-->
 *   <script type="text/javascript" src="js/jquery-1.5.1.min.js"></script>
 *   <script type="text/javascript" src="js/dynamicLayoutGallery.js"></script>
 *	...
 *</head>
 *<body class="dynamicWidth" onLoad="setLayout();">
 *	... 
 *	<div id="gallery">
 *		<div class="thumb">
 *		</div>
 *		...
 *		<div class="thumb">
 *		</div>
 *	</div>
 *	...
 */

//horizontal separation between thumbnails (change it if you want)
var separation="30px";

//minimum number of thumbnails in each row (change it if you want)
var minimNumThumbs=3;



$(document).ready(function() 
{	
	setLayout();
});

var TO = false;
$(window).resize(function() 
{
	if(TO==false)
	{
		clearTimeout(TO);
	}
	TO=setTimeout(setLayout,200);
});

function setLayout()
{
	$('.dynamicWidth').css({
		'width':'95%',
		'margin': '0 auto',
		'position': 'relative',
		'clear': 'both',
		'overflow': 'hidden'
	});
	$('.thumb').css('float','left');
	
	var numThumbs=0;
	var positionLeft = 0;
	
	//compare the positions of each thumbnail to calculate the number of thumbs in each row (numThumbs)
	$('#gallery').children().each(function()
	{
		offset=$(this).offset();
		if(offset.left>positionLeft){
			positionLeft=offset.left;
			numThumbs++;
		}
	});
	
	if (numThumbs<minimNumThumbs)
	{
		numThumbs=minimNumThumbs;
	}
			
	//if the item is in the right corner, remove the margin-right
	var numNode=1;
	$('#gallery').children().each(function()
	{
		if(numNode>=numThumbs && numNode%numThumbs==0)
		{
			$(this).css('margin-right',0);
		} else
		{
			$(this).css('margin-right',separation);
		}
		numNode++;
	});
	
	//calculate the total width of the containers, based on numThumbs in each row		
	var wide=
	(parseInt($('.thumb').css('width'))*numThumbs) +
	(parseInt($('.thumb').css('padding-left'))*numThumbs) +
	(parseInt($('.thumb').css('padding-right'))*numThumbs) +
	(parseInt($('.thumb').css('border-left-width'))*numThumbs) +
	(parseInt($('.thumb').css('border-right-width'))*numThumbs) + 
	(parseInt($('.thumb').css('margin-right'))*(numThumbs-1));
	
	$('.dynamicWidth').css('width',wide + "px");
};
