/*
 * jQuery WidowFix Plugin
 * http://matthewlein.com/widowfix/
 * Copyright (c) 2010 Matthew Lein
 * Version: 1.2 (10/6/2010)
 * Dual licensed under the MIT and GPL licenses
 * Requires: jQuery v1.4 or later
 */

(function( $ ){

	jQuery.fn.widowFix = function(userOptions) {
		
		var defaults = {
			letterLimit: null,
			linkFix: false 
		};
		
		var wfOptions = $.extend(defaults, userOptions);
		
		return this.each(function(){
			if (wfOptions.linkFix) {
				//find the anchors and wrap them up with a <var> tag to find it later
				$(this).find('a:last').wrap( '<var>');
				//store the anchor inside
				var $lastLink = $('var').html();
				//remove the anchor
				$('var').each(function() {
					$(this).find('a').contents().unwrap();
				});
			}
			
			var content = '';
			var contentArray = $(this).html().split(' ');
			var lastWord = contentArray.pop();
			
			//if the last word is longer than the limit, stop the script
			if (wfOptions.letterLimit !==null && lastWord.length >= wfOptions.letterLimit) {
				return;
			}
			
			function checkSpace(){
				if (lastWord === ''){
					//trailing space found, pop it off and check again
					lastWord = contentArray.pop();
					checkSpace();
				}
			}
			checkSpace();
			
			content = contentArray.join(' ') + '&nbsp;' + lastWord;
			$(this).html(content);
			
			if (wfOptions.linkFix) {
				//find the var and put the anchor back in, then unwrap the <var>
				$('var').each(function(){
					$(this).contents().replaceWith($lastLink);
					$(this).contents().unwrap();
				});
			}
			
		});
		
	};

})( jQuery );
