(function($){
	$.fn.extend({
		
		widthTruncate: function(options) {

			var defaults = {
				width: 'auto',
				lines: 1,
				after: '&hellip;'
			};
			var options = $.extend(defaults, options);

			var $space, $trunc, maxHeight, maxWidth, origText, i;
			
			return this.each(function() {
				// get height of one line by adding a span with a space to the end of element
				$space = $('<span>&nbsp;</span>').appendTo(this);
				// multiply line height by number of lines to get maximum height
				maxHeight = $space.height() * options.lines;
				// get line width if width not specified in options; this is done after space has been added
				// because in some cases IE8 reports a different width after space is added
				if(options.width=='auto') maxWidth = $(this).width(); else maxWidth = options.width;
				// once we have height and width, we are through with added space, so remove it
				$space.remove();
				// if height or width exceed limits, do truncation
				if($(this).height()>=(maxHeight*2) || $(this).width()>maxWidth){
					// start with a copy of the original text
					origText = $(this).text();
					$(this).attr('title',origText);
					// create inline span to test expanding text against limits
					$trunc = $('<span style="display:inline;">'+options.after+'</span>');
					// replace contents of element with testing span
					$(this).html('').append($trunc);
					// loop through the original text, adding one character at a time
					// until the width or height limits are exceeded
					i = 0;
					while ($trunc.width() < maxWidth && $trunc.height() == maxHeight) {
						$trunc.html(origText.substr(0,++i) + options.after);
					}
					// replace element's contents with last text before limits exceeded
					$(this).html($.trim(origText.substr(0,--i)) + options.after);
				}
			});
		
		}
	
	});
})(jQuery);
