/**
 * ELIXON FIXHEIGHT
 * Project Homepage: http://www.webdevelopers.eu/jquery/fixheight
 *
 * LICENSE
 *   http://www.webdevelopers.eu/jquery/fixheight/license
 *   Commons Attribution-NonCommercial 3.0
 *
 *   Get a commercial license at
 *   http://www.webdevelopers.eu/jquery/fixheight/buy 
 *
 * DEMO
 *    http://www.webdevelopers.eu/jquery/fixheight/demo 
 * 
 * DOCUMENTATION
 *    http://www.webdevelopers.eu/jquery/fixheight/documentation
 *    
 * @project    Elixon CMS, http://www.webdevelopers.eu/
 * @package    JQuery
 * @subpackage FixHeight
 * @author     Daniel Sevcik <sevcik@webdevelopers.eu>
 * @version    1.0.6
 * @copyright  2011 Daniel Sevcik
 * @revision   $Revision: 4677 $
 * @changed    $Date: 2011-02-09 12:37:34 +0100 (Wed, 09 Feb 2011) $
 * @access     public
 */
(function($) {
	$.fn.fixHeight=function() {
		var row=0;
		function fhResize(siblings, maxSize) {
			if (!siblings.length) return siblings;
			row++;
			var col=1;
			return siblings.height(maxSize).addClass(function() {return 'fhRow' + row + ' fhCol' + col++;});
		}

		this.each(function() {
				if ($(this).data('fixHeightLock')) return true;
				$(this).data('fixHeightLock', true);
				
				var offset=0, maxSize=0, siblings=$(), row=0;
				$('> *:visible', this)
				    .attr('class', function(idx, old) {return old.replace(/(^| )fh(Col|Row)[0-9]+( |$)/g, ' ');}) // remove old classes if any
					.height('auto')
					.each(function() {
						var $this=$(this);
						if (offset != $this.position().top) {
							fhResize(siblings, maxSize);
							maxSize=$this.height();
							offset=$this.position().top;
							siblings=$();
						} else {
							if (maxSize < $this.height()) maxSize=$this.height();
						}
						siblings=siblings.add($this);
					});
				fhResize(siblings, maxSize); // remainder/last row
				
				$(this).data('fixHeightLock', false);
			});

		// after resizing some images may be loaded and this may change the layout...
		var $this=this;
		$('img', this).load(function() {
				// There can be many images so use timed fixHeight()
				clearTimeout($this.fixHeightTimeout);
				$this.fixHeightTimeout=setTimeout(function() {$this.fixHeight();}, 1000);
	    });
		
		return this;
	}

	$.fn.makeColumns=function(customOptions) {
		// Default options
		var options={
			columns: 3
		}
		if (customOptions) {
			$.extend(options, typeof customOptions == 'number' ? {columns: customOptions} : customOptions);
		}
		this.each(function() {
				var $this=$(this);
				var children=$this.children().get();
				var ordered=[];
				for(var col=Math.abs(options.columns); col; col--) {
					ordered.push([]);
					for(var i=Math.ceil(children.length / col); i; i--) {
						ordered[ordered.length - 1].push(children.shift());
					}
				}
				// Reorder
				var items=$this.children().length;
				for(var i=0; i < items; i++) {
					var item=ordered[i % options.columns].shift();
					$this.append(item);
				}
				$this.fixHeight();
			});
		return this;
	}
	
})(jQuery);

