/**
 * Makes sure a given object fits within its parent's parent
 *  
 * Apply class="nowrap" to SPAN's that you don't want to wrap if they can fit on their own line.
 * Apply class="nowap-constraint" to a parent element of that SPAN to define what element 
 * it should fit within.
 *
 * @author Justin Johnson <justin@fryewiles.com>, justin@booleangate.org
 * @version 0.1.0 20080328 JJ
 * 
 * @author Chuck Harper <charper@aeglive.com>
 * @Forked version 0.1.0b 20080512 CH
 * 		changed process from wrapping names to attempting to fit names.
 */

var wrapFix = {
	processs: {
		'span.nowrap': function(element) {
			if ( !wrapFix.elementFits(element) ) {
				wrapFix.fix(element);
			}
		}
	},
	
	elementFits: function(element) {
		return element.offsetWidth <= wrapFix.getWrapConstraint(element);
	},
	
	getWrapConstraint: function(element) {
		// Find a parent node with the class "nowrap-constraint"
		var node = element;
		
		while ( node.parentNode ) {
			node = node.parentNode;
			
			// if (!confirm(node.className + ':' + node.innerHTML.substr(0,30))) break;
			if ( node.className && node.className.indexOf('nowrap-constraint') >= 0 ) {
				// alert('width = ' + node.offsetWidth);
				return node.offsetWidth;
			}
		}
		
		// No constraint found, default to direct parent
		return element.parentNode.offsetWidth;
	},
	
	getWrapContainer: function(element) {
		// Find a parent node with the class "nowrap-constraint"
		var node = element;
		
		while ( node.parentNode ) {
			node = node.parentNode;
			
			if ( node.className.indexOf('nowrap-constraint') >= 0 ) {
				return node;
			}
		}
		
		// No constraint found, default to direct parent
		return element.parentNode;
	},
	
	fix: function(element) {
		// shrink this element down
		// reduce font-size by one point until it fits parent width
		fontpixels = 19;
		while (!wrapFix.elementFits(element)) {
			element.style.fontSize = fontpixels + 'px';
			fontpixels--;
		}
		fontpixels = fontpixels+1;
		
		element.style.fontSize = '100%';
		our_container = wrapFix.getWrapContainer(element);
		if (fontpixels >= 10) {
			our_container.style.fontSize = fontpixels + 'px';
		} else {
			our_container.style.fontSize = '10px';
			element.className = element.className.replace(/nowrap ?/, 'wrap ');
		}
	}
};

Behaviour.register(wrapFix.processs);