;(function($){
	$.fn.adaptableGrid = function(options){
		var opts = $.extend({
			'getCount': function(size){
				if (size < 1200) {
					if (size < 1050) {
						return 3;
					}else{
						return 4;
					}
				}
				
				if (size >= 1200 && size < 1500) {
					if (size < 1340) {
						return 5;
					}else{
						return 6;
					}
				}
				
				if(size >= 1500){
					return 7;
				}
			}
		},options);
		
		var child1Tag = 'tr';
		var child2Tag = 'td';
		
		
		
		var reorder = function(container, items, count){
			var current = null;
			var newRows = [];
			
			for(var i in items){
				if(i % count == 0){
					current = {
						imgRow: $(document.createElement(child1Tag)).addClass('imgRow'),
						dataRow: $(document.createElement(child1Tag)).addClass('infoRow')
					};
					newRows.push(current);
				}
				if(i.length > 2){
					items[i].img.css('width',  parseInt(100 / count) + '%');
					items[i].data.css('width', parseInt(100 / count) + '%');
				}
				current.imgRow.append(items[i].img);
				current.dataRow.append(items[i].data);
			}
			container.empty();
			for(var i in newRows){
				container.append(newRows[i].imgRow);
				container.append(newRows[i].dataRow);
			}
		};
		return $(this).each(function(){
			var me = $(this);
			if(me.is('table')){
				me = me.find('tbody');
			}
			
			me.attr('currentcount', 0);
			var onResize = function(){
                                var items = [];
                                var imgItems = me.find(child1Tag + '.imgRow').children(child2Tag);
                                var infoItems = me.find(child1Tag + '.infoRow').children(child2Tag);
                                var itemCount = imgItems.size();
                                for(var i = 0; i < itemCount; i++){
                                        items.push({
                                                img: imgItems.eq(i),
                                                data: infoItems.eq(i)
                                        });
                                }

				var containerWidth = $(window).width();
				var count = opts.getCount(containerWidth);
				//$('#left').text(count + " min: " + containerWidth + " | current: " + me.attr('currentcount'));
				if (parseInt(me.attr('currentcount')) != count) {
					me.attr('currentcount', count);
					reorder(me, items, count);
				}
			}
			
			$(window).resize(onResize);
			onResize();
		});
	};
}(jQuery));
