/*
 * fixHeight - Library with jQuery
 *
 * Version 1.0.1 on 2009.12.17
 *
 * Author Koji Kimura @ STARRYWORKS inc.
 * http://www.starryworks.co.jp/
 *
 * Licensed under the MIT License
 *
 */


(function(){
	
	var groups = [];
	var textHeight = 0;
	var $fontSizeDiv;
	
	function check() {
		if ( $fontSizeDiv.height() == textHeight ) return;
		textHeight = $fontSizeDiv.height();
		$.each( groups, function(){
			var $children = this.children;
			var n = this.n;
			if ( n == 0 ) {
				
				//$childrenを全部同じ高さに
				$children.fixHeight();
				
			} else if ( n == -1 ) {
				
				//$childrenのY座標が同じものは同じ高さに
				var childrenGroup = [];
				var childrenGroups = [];
				var top = 0;
				$children.each(function(){
					if ( top != $(this).position().top ) {
						if ( childrenGroup.length ) childrenGroups.push(childrenGroup);
						childrenGroup = [];
						top = $(this).position().top;
					}
					childrenGroup.push(this);
				});
				if ( childrenGroup.length ) childrenGroups.push(childrenGroup);
				$.each( childrenGroups, function(){ $(this).fixHeight() });
				
			} else {
				
				//$childrenをn個ずつグループ化して同じ高さに
				var childrenGroup = [];
				var childrenGroups = [];
				$children.each(function(index){
					if ( index != 0 && index % n == 0 ) {
						if ( childrenGroup.length ) childrenGroups.push(childrenGroup);
						childrenGroup = [];
					}
					childrenGroup.push(this);
				});
				if ( childrenGroup.length ) childrenGroups.push(childrenGroup);
				$.each( childrenGroups, function(){ $(this).fixHeight() });
			}
		});
	}
	
	$.fn.fixHeight = function() {
		var maxHeight = 0;
		this.css("height","auto");
		this.each(function(){
			if ( $(this).height() > maxHeight ) maxHeight = $(this).height();
		});
		this.height(maxHeight);
		return this;
	}
	
	$.fn.initFixHeight = function() {
		this.each(function(){
			var $this = $(this);
			var $children = $this.find(".fixHeightChild");
			if ( !$children.length ) $children = $this.children();
			if ( !$children.length ) return;
			var n = 0;
			if ( $(this).hasClass("fixHeightNAuto") ) n = -1;
			else if ( $this.attr("class").match(/fixHeightN([0-9]+)/) ) n = parseInt($this.attr("class").match(/fixHeightN([0-9]+)/)[1]);
			else if ( !$(this).hasClass("fixHeight") ) return;
			groups.push({ parent:this, children:$children, n:n });
		});
		return this;
	}
	
	function init() {
		$(".fixHeight, .fixHeightNAuto, *[class*=fixHeightN]").initFixHeight();
		$fontSizeDiv = $(document).append('<div>s</div>');
		//setInterval(check,1000);
		$(window).resize(check);
		check();
	}
	
	$(init);
	
})();

