﻿/*
author iron
version 2009-09-06
example	:

<div style="width:190px; height:60px;">
	<div class="jmBlockEllipsis">the string you wan to put in</div>
</div>

<div style="width:190px">
	<div class="jmLineEllipsis">the string you wan to put in</div>
</div>
*/
$(function(){			 
	
	jmEllipsis = function () {
		// Block
		$.each( $('.jmBlockEllipsis'), function(){
																						
			var h = $(this).parent().height(),
					h2 = $(this).parent().css('height'),
					t = $(this).html();
					
			if (h == 0) {
				return;
			}		
					
			$(this).html("<span>" + t + "</span>");
			var e = $(this).children().eq(0);
			
			if (e.height() < h) {
				jmEndBlock(e, h2);
				return;
			}
			
			var low = 0;
			var high = t.length-1;
			var mid;
			var tt;
			
			while (low <= high) {
				mid = parseInt((low+high)/2);
				tt = t.substr(0, mid);
				e.html(tt+'...');
				
				if (e.height() >= h)
				{
						high = mid-1;
				}
				else if (e.height() < h)
				{
						low = mid + 1;
				}
			}
			tt = t.substr(0, mid-1);
			e.html(tt+'...');
			
			jmEndBlock(e, h2);
		});
	
		$.each( $('.jmLineEllipsis'), function(){
					
			var marginRight = $(this).css('margin-right');
																				 
			var	w = $(this).parent().width();				// 容器的高度
			if (w == 0) {
				return;
			}
			
			$(this).css('margin-right','-10000px');
			var t = $(this).html();									// 容器的內容html碼
			$(this).html("<span>" + t + "</span>");	// 容器的內容用一個span標籤包起來方便操作
			var	e = $(this).children().eq(0);				// 就是span標籤
			
			if (e.width() < w) {
				jmEndLine($(this) ,e, marginRight);
				return;
			}
			
			var low = 0;
			var high = t.length-1;
			var mid;
			var tt;
			
			while (low <= high) {
				mid = parseInt((low+high)/2);
				tt = t.substr(0, mid);
				e.html(tt+'...');
				
				if (e.width() >= w)
				{
							high = mid-1;
				}
				else if (e.width() < w)
				{
						low = mid + 1;
				}
			}
			tt = t.substr(0, mid-1);
			e.html(tt+'...');
			
			jmEndLine($(this), e, marginRight);
			
		});

	};

	jmEndBlock = function (e, h) {
		
		h = h.substr(0, h.length-2);
		
		h = parseInt(parseInt(h) / 13 * 0.9759);
		h = h.toString() + 'em';
		
		// fix ie 6 auto height bug
		if (jQuery.browser.msie && parseInt(jQuery.browser.version) <= 6) {
			e.css('overflow', 'hidden');
			e.css('height', h);
			e.css('display', 'block');
		} 
		
	};

	jmEndLine = function (obj, e, marginRight) {
		obj.css('margin-right', marginRight);

		// fix ie 6 auto height bug
		if (jQuery.browser.msie && parseInt(jQuery.browser.version) <= 6) { 
			e.css('overflow', 'hidden');
			e.css('display', 'block');
		}
	};

	jmEllipsis();
	
	

});
