(function($) {
  var defaults={
       noPerRow:4,
	   boxWidth:100,
	   boxMarginBottom:0
  };
  
  var box=[],
      height=[];  
 
	
  $.fn.smartFloat=function(params) {
     
	 defaults=$.extend(defaults,params);
	 
	   
     this.each(function() {
	    
		var $t=$(this);
		var k=0;
		var widthWrapper=$t.width();
				
		for(i=0;i<defaults.noPerRow;i++) 
                      height[i]=0;
					  
					  
		$t.find('.box').each(function(i) {
		    
		       var leftNo=i%defaults.noPerRow,
	               topHeight,
		           temp={};
				   
			   k++;
			   
			   
		
	           temp=findShortest(height);
	 
	 		   
              $(this).css({
	               top:temp.value+'px',
	               left:temp.key*defaults.boxWidth+'px'
	          });
               box[i]=$(this);  
	             $t.append(box[i]);
	 
	            topHeight=$(box[i]).height()+defaults.boxMarginBottom;	
	 
	            height[temp.key]=height[temp.key]+topHeight;
		
		     
		
		});	 
		
		temp=findLongest(height);
        $t.css('height',temp.value+'px');
		
		//if the columns are not used up, just shrink the width of the wrapper...
		/*if(k<defaults.noPerRow) {			
			var newWidth=widthWrapper/defaults.noPerRow*k;			
			$t.width(newWidth);	
			$t.parent().width(620);		
		}
		
		else
		   $t.parent().width(840);
		*/
		
	 function findLongest(heights) {
             var temp={value:0,key:0};
             for(i=0;i<defaults.noPerRow;i++) {
              if(temp.value<heights[i]) {
			         temp['value']=heights[i];
					 temp['key']=i;
			  }
     }
     return temp;
    }

    function findShortest(heights) {
           var temp={value:9999999999,key:0};
           for(i=0;i<defaults.noPerRow;i++) {
              if(temp.value>heights[i]) {
			         temp['value']=heights[i];
					 temp['key']=i;
			  }
           }
      return temp;
    }		
	 
	    
	});
	 
	 return this;  
  }; 

})(jQuery)
