/*
 * jSquares for jQuery
 * http://boedesign.com/
 *
 * Copyright (c) 2009 Jordan Boesch
 * Dual licensed under the MIT and GPL licenses.
 *
 * Date: December 1, 2009
 * Version: 1.2
 *
 */
(function($) {
	
	/**
	* Initialize and setup plugin 
	* @param {Object} options The set of options to pass to over-write the defaults
	*/
	$.fn.jGallery = $.fn.jGallery = function(options)
	{
		/** This will sort all of the images in the gallery */
		var gallery = this;
		var images = $(gallery).find('img');
		var limit = 3; //limit per line
		var src = 0;
		var margin = 5;
		var row = 1;
		var t_width = 0; //acts as a buffer
		//console.log(images);
		for (i=0; i<=images.length; i++)
		{
			src = i; //set the image src to the index
			
			//
			var pos_l = 0; //prev img width
			var pos_t = 0; //prev img height
			//var rand = Math.floor(Math.random()*31);
			var rand = Math.floor(Math.random()*21);
			var width = $(images[i]).width() - rand;
			t_width += $(images[i]).width();
			
			if(i!=0)
			{
				var left = parseInt($(images[i-1]).css('left'));							
				pos_l = left+$(images[i-1]).width()+(margin*2);	
				var top = parseInt($(images[i-1]).css('top'));							
				pos_t = top;	
			}
			
			if(t_width>this.width())
			{
				//we need to move the images down
				var top = parseInt($(images[i-1]).css('top'));							
				pos_t = top+$(images[0]).height()+(margin*2);	
				pos_l = 0;
				t_width = 0;
				row ++;
			}
			
			//$(images[i]).css({left: pos_l, top: pos_t, width: width});
			$(images[i]).css({width: width});
			if(i!=0&&(i+1)%3==0)
			{
				$(images[i]).after('<div class="clear"></div>');
			}		
			//document.write('<div class="clear"></div>');
			/*
			for (l=1; l<=limit; l++)
			{
				
				var rand = 0;
				var width = 0;
				
				if($(images[i]!=undefined))
				{
					if($(images[i]).attr('src')!=undefined)
					{
						var pw = 0; //prev img width
						var ph = 0; //prev img height
						rand = Math.floor(Math.random()*11);
						width = $(images[i]).width() - rand;
						
						if(i!=0)
						{
							var left = parseInt($(images[i-1]).css('left'));							
							pw = left+$(images[i-1]).width()+(margin*2);
							
						}
						$(images[i]).css({left: pw, width: width});
					}					
				}
				if($(images[i+1]!=undefined))
				{					
						if(l<limit) 
						i++;	
				}
				
				//console.log($(images[i]).attr('src'));
				
				
				
				//if(l==limit) i += src;
				
				//console.log(l+' '+i);
				
				
				//console.log($(images[i]).css({width: width}));
			}
			//html += '</li>';
			*/

		}
	};
	
})(jQuery);

