/**
 * Abbreviator jQuery Plugin (jQuery >= 1.2.x)
 *
 * Usage:
 *
 *   $('#mydiv').abbrev(); // Autofit mydiv's innerHTML content horizontally
 *
 * This work is distributed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2008 Ben Vinegar [ ben ! benlog dot org ]
 */

(function($) {
	$(function() {
		// NOTE: We have to use a <span> inside a max-width <div> for IE6
		$('body').append('<div id="abbreviator-tmp-div" style="width:9999px; left:-9999px; top:-9999px; display:block; position: absolute"><span id="abbreviator-tmp-span"></span></div>');
	});

	$.fn.abbrev = function() {
		$(this).each(function() {

			var content = $(this).html();

			$("#abbreviator-tmp-div").appendTo(this);

			var containerWidth = $(this).width();

			var contentWidth = $("#abbreviator-tmp-span").html(content).width();

			if (contentWidth <= containerWidth) {
				$('#abbreviator-tmp-div').appendTo('body');
				$(this).width('');
				return;
			}

			var coverage = containerWidth / contentWidth;
			var l = content.length;

			abbrevContent = content.substr(0, parseInt(l * coverage));

			while ($('#abbreviator-tmp-span').html(ellipsifyString(abbrevContent)).width() >= containerWidth) {
				abbrevContent = abbrevContent.substring(0, abbrevContent.length - 1);
			}

			$('#abbreviator-tmp-div').appendTo('body');

			$(this).html(abbrString(ellipsifyString(abbrevContent), htmlEscape(content)));
		});
	}
	
	// Private functions
	
	function ellipsifyString(s) {
		return s + '&hellip;';
	}

	function abbrString(s, full) {
		return '<span class="abbr" title="' + full + '">' + s + '</span>';
	}
	function htmlEscape(str) {
		return str.replace(/[&]/g, '&amp;').replace(/[<]/g, '&lt;').replace(/[>]/g, '&gt;').replace(/["]/g, '&quot;');
	}
})(jQuery);