var Shuffle = new Class({ 
	Implements: [Options],				   
	options: {
		items: '.module',
		version: '0.1',
		spacer: 1
	},	
	initialize: function(options){
		this.setOptions(options);
		this.myModules = $$(this.options.items);
		this.currentIndex = 0;
		
		this.windowSize = window.getSize();
		
		window.addEvent('resize', function(e) {
			this.windowSize = window.getSize();
			this.displayModules();
		}.bind(this));			
		
		this.displayModules();
		
	},
	displayModules: function(){
		this.matrix = new Array();
		this.x = this.y = this.options.spacer;
		this.smallElmHeight = 0;
		this.row = 1;

		this.myModules.each(function(myModule, index){
									 			
			// get the height of the smallest element in a row
			if(this.smallElmHeight > myModule.getSize().y || this.smallElmHeight == 0){
				this.smallElmHeight = myModule.getSize().y;
			}
			
			// adding another element to a row will cause a horizontal scroll
			if((this.x + myModule.getSize().x+320) > this.windowSize.x ){
				
				this.y += (this.smallElmHeight);
				this.x = this.options.spacer;

				this.row++;
				this.smallElmHeight = 0;
			}			
									 
			myModule.setStyles({
				top: this.y,
				left: this.x,
				visibility: 'visible'
			});
			
			this.matrix[index] = { coordinate: { x: this.x, y: this.y }, size : myModule.getSize(), row: this.row };
			
			this.x += (this.matrix[index].size.x + this.options.spacer)-1;
			
			while(!this.hitTest(index)){
				this.matrix[index].coordinate.y += this.options.spacer;
				myModule.setStyle('top', this.matrix[index].coordinate.y);
			}
						
		}.bind(this));		
	},
	hitTest: function(myIndex){
		var curElmInfo = this.matrix[myIndex];
		var curElemWidth = this.matrix[myIndex].size.x + this.matrix[myIndex].coordinate.x;
		var curElemHeight = this.matrix[myIndex].size.y + this.matrix[myIndex].coordinate.y;
				
		for(i = 0, len = this.matrix.length; i < len; i++){				
	
			var matrixItem = this.matrix[i];
		
			//not the element we are checking
			if(myIndex != i){
				var elmTotaly = matrixItem.coordinate.y + matrixItem.size.y;
				var elmTotalx = matrixItem.coordinate.x + matrixItem.size.x;
				
				// check y
				if((elmTotaly > curElmInfo.coordinate.y)  && curElemHeight > matrixItem.coordinate.y){
					
					// check x
					if((elmTotalx > curElmInfo.coordinate.x) && curElemWidth > matrixItem.coordinate.x){
						return false;
					}
	
				}
				
			}
		}
		
		return true;
	}
});		