/*
 *	autoHeight
 *	a customized version of "fixHeight.js"
 *
 *	Oct 20, 2009 customized by Ankh Davis
 *
 *	original auther: Koji Kimura http://www.starryworks.co.jp/
 *
 *	licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 */
 
$.fn.extend({
	autoHeight: function(useAuto) {
		opt = {
			groups : [],
			textHeight: 0,
			fontSizeDiv: null,
			auto: useAuto
		};
		
		$(this).each(function(){
			var $this = $(this);
			var $children = $(".autoHeightChild",$this);
			if ( !$children.length ) $children = $this.children();
			if ( !$children.length ) return;
			var n = -1;
			opt.groups.push({ parent:this, children:$children, n:n });
		});	
		
		opt.fontSizeDiv = $(document).append('<div>s</div>');
		
		/*	for realtime adjusting
		if (realtime) {
			setInterval(this.check,1000);
			$(window).resize(this.check);
		}
		*/
			
		this.check(opt);
	},
	
	check: function(opt) {
		if ( opt.fontSizeDiv.height() == opt.textHeight ) return;
		textHeight = opt.fontSizeDiv.height();
		$.each(opt.groups,function(){
			var $children = this.children;
			var n = this.n;
			
			if (opt.auto) {
				$children.css("height","auto");
			}
			
			var maxHeight = 0;
			
			if ( n == -1 ) {
				var top = 0, cnt = 0, st = 0, i = 0;
				$children.each(function(){
					if ( top != $(this).position().top ) {
						if ( cnt > st ) for ( i = st; i < cnt; i++ ) $children.eq(i).css("height",maxHeight+"px");
						top = $(this).position().top;
						maxHeight = 0;
						st = cnt;
					}
					if ( $(this).height() > maxHeight ) maxHeight = $(this).height();
					cnt++;
				});
				if ( cnt > st ) for ( i = st; i < cnt; i++ ) $children.eq(i).css("height",maxHeight+"px");
			} else {
				var maxHeights = [];
				$children.each(function(index){
					if ( index != 0 && index % n == 0 ) {
						maxHeights.push(maxHeight);
						maxHeight = 0;
					}
					if ( $(this).height() > maxHeight ) maxHeight = $(this).height();
				});
				maxHeights.push(maxHeight);
				$children.each(function(index){
					$(this).css("height",maxHeights[Math.floor(index/n)]+"px");
				});
			}
		});
	}
});

