/* 
 * ET: jquery.equalheights.js
 * 
 * Date: 05 Feb 2010
 */

(function($){
	
	
	$.equalHeightsArray = function(srcArray, options){
		
		tallest = options.minHeight;
		$.each(srcArray, function(){
			if ($(this).height() > tallest) {
                tallest = $(this).height();
            }
		});
		
		if ((options.maxHeight != 9999) && tallest > options.maxHeight) tallest = options.maxHeight;
		
        return $.each(srcArray, function() {
            $(this).height(tallest);
			$(this).css("overflow", options.overflow);
        });
        
	};
	
	
	$.makeEqualRows = function(srcSelectors, options) {
		
		srcSelectorsArray = srcSelectors.split("/");
		dstArray = new Array();
		
		for(i=0; i<srcSelectorsArray.length; i++){
			
			dstObjects = $(srcSelectorsArray[i]);
			dstObjectsArray = new Array();
			for(j=0; j<dstObjects.length; j++){
				dstObjectsArray.push(dstObjects[j]);
			}
			dstArray.push(dstObjectsArray);
		}
		
		
		for(i=0; i<dstArray.length; i++){
			
			arrayToEqual = dstArray[i];
			rowToEqual = new Array();
			
			
			if( options.objectsPerRow == 0 && options.rowClass.length > 0 ){
				options.objectsPerRow = $( '.' + options.rowClass + ':first > *' ).length;
			}
			else{
				options.objectsPerRow = (options.objectsPerRow > 0) ? options.objectsPerRow : arrayToEqual.length;
			}
			
			
			while(arrayToEqual.length > 0){
				
				if( arrayToEqual.length >= options.objectsPerRow ){ endIndex = options.objectsPerRow; }
				else{ endIndex = arrayToEqual.length; }
				
				rowToEqual = arrayToEqual.splice(0, endIndex);
				$.equalHeightsArray(rowToEqual, options);
			}
			
		}
		
		return true;
		
	};
	
	
	
	$.makeEqualList = function(srcSelectors, options) {
		
		srcSelectorsArray = srcSelectors.split("/");
		dstArray = new Array();
		
		for(i=0; i<srcSelectorsArray.length; i++){
			dstArray.push( $(srcSelectorsArray[i]) );
		}
		
		$.equalHeightsArray(dstArray, options);
		
		return true;
	}
	
	
	
	$.equalHeights = function(srcSelectors, useroptions){
	
		//Options ...........................
		var options = {};
		$.extend(true, options, {
			overflow: 'hidden',
			minHeight: 0,
			maxHeight: 9999,
			objectsPerRow: 0,
			rowClass: '',
			mode: 'default',
			callback: false
		}, useroptions);
		//...................................
		
		if( options.mode == 'list' ){
			$.makeEqualList(srcSelectors, options);
		}
		else{
			$.makeEqualRows(srcSelectors, options);
		}
		
		//Callback ..........................
		if( $.isFunction(options.callback) ){			
			options.callback.call();
		}
		
		return true;
		
	};	
	
	
	
})(jQuery);
