/**
 * jQuery Shrink Plugin
 * v1.0
 *
 * The MIT License
 *
 * Copyright (c) 2012 ykojima
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
(function($) {
	$.fn.wsShrink = function(config) {
		var wbr = '<wbr class="wsShrink" />';

		config = jQuery.extend({
			ellipsis : '...',
			exclude : [ ' ', '\t', '\r', '\n' ]
		}, config);

		$(this).each(function() {
			var html = $(this).html();
			$(this).attr('title', $(this).text()).html('&nbsp;').css({ display: 'block'});

			var width = $(this).width();
			var height = $(this).height();

			var buf = '';
			var tag = false;
			var spchar = false;
			var wspace = false;
			for ( var i = 0; i < html.length; i++) {
				if (html.charAt(i) == '<') {
					tag = true;
				} else if (html.charAt(i) == '>') {
					tag = false;
				}
				if (html.charAt(i) == '&') {
					spchar = true;
				} else if (html.charAt(i) == ';') {
					spchar = false;
				}
				wspace = ($.inArray(html.charAt(i), config.exclude) > -1);
				buf += html.charAt(i);
				buf += (tag || spchar || wspace) ? '' : wbr;
			}
			$(this).html(buf);

			var reg = new RegExp(wbr, 'g');

			if ($(this).width() <= width && $(this).height() <= height) {
				$(this).html(buf.replace(reg, ''));
				return;
			}

			ellipsisHtml = buf;
			while (true) {
				var idx = ellipsisHtml.lastIndexOf(wbr);
				if (idx == -1) {
					break;
				}
				ellipsisHtml = ellipsisHtml.substring(0, idx) + config.ellipsis;
				$(this).html(ellipsisHtml);
				if ($(this).width() <= width && $(this).height() <= height) {
					break;
				}
			}
			$(this).html(ellipsisHtml.replace(reg, ''));

		});

	}
})(jQuery);
