(function($){

 	$.fn.extend({ 
 		
		//pass the options variable to the function
 		jGrid: function(options) {
			//Set the default values, use comma to separate the settings, example:
			var defaults = {
				padding:10,
				colWidth: 100,
				gutterWidth:10,
				minCol: 4,
			}
				
			var data = [];
			var content = [];
			var options =  $.extend(defaults, options);
			var childElems = ($(this).find('div'));
			var parent = $(this);
			$.each(
				childElems,
				function( intIndex, objValue ){
						var o = options;
						var w = Math.ceil( $(this).width() / (o.colWidth+o.gutterWidth));
						data.push( w );
						content.push( $(this).remove() );						
					}
				);
			//
			var runningTotal = 0;
			$.each(
				data,
				function( intIndex, objValue ){
						if(runningTotal+objValue >=8){
							// IF THE TOTAL COLUMNS PLUS THE COLUMNS NEEDED FOR THIS IMAGE ARE MORE THAN 8 THEN WE NEED TO DO  A SWAPAROO
							//alert("no fit!");
							//SWAP WITH PREVIOUS
							if(data[intIndex-1]==1){
								// swap the data indices
								var swapCurrent = data[intIndex];
								data[intIndex] = data[intIndex-1];
								data[intIndex-1] = swapCurrent;
								// swap the content indices
								var swapCurrentImage = content[intIndex];
								content[intIndex] = content[intIndex-1];
								content[intIndex-1] = swapCurrentImage;
								// reset running total
								runningTotal=0;
							} else if (data[intIndex+1]==1){
								// swap the data indices
								var swapCurrent = data[intIndex];
								data[intIndex] = data[intIndex+1];
								data[intIndex+1] = swapCurrent;
								// swap the content indices
								var swapCurrentImage = content[intIndex];
								content[intIndex] = content[intIndex+1];
								content[intIndex+1] = swapCurrentImage;
								// reset running total								
								runningTotal=0;								
							}
						} else {
							//OTHERWISE CARRY ON AS NORMAL
							runningTotal+=objValue
						}
					}
				);
				//
			var runningTotal = 0;
			$.each(
				content,
				function( intIndex, objValue ){
						parent.append(objValue);
					}
				);
				//
			$.each(
				childElems,
				function( intIndex, objValue ){
						var o = options;		
						var elemWidth = $(this).width();
						if(elemWidth > o.colWidth){
							var colSpan = Math.ceil(elemWidth/(o.colWidth+o.gutterWidth));
							var newWidth = (colSpan*o.colWidth)+((colSpan-1)*o.gutterWidth);
						} else {
							var colSpan = Math.ceil(elemWidth/(o.colWidth));
							var newWidth = o.colWidth;
						}
						$(this).width(newWidth);
					}
				);	
    	}
	});
})(jQuery);


