// ==UserScript==
// @name Autojustify Texts
// @author Mathias Plichta 
// @namespace http://userjs.org/ 
// @version 1.0
// @description  Justify text, if there is enough space to do so.
// @ujs:category general: enhancements
// @ujs:published 2005-11-09 23:06
// @ujs:modified 2005-11-09 23:24
// @ujs:documentation http://userjs.org/scripts/general/enhancements/autojustify-text 
// @ujs:download http://userjs.org/scripts/download/general/enhancements/autojustify-text.js
// ==/UserScript==


/* 
 * Copyright © 2005 by Mathias Plichta
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 */

document.addEventListener ('load', function() {

	/*This is the ratio of the font-size and with of the element.
	Below this, text gets left-aligned- above it, it gets justified*/
	var minWidth = 30;

	if( !document.body ) { return; }

	function findChilds(element) {
		/*Finds all childs of an element and calls itself and childTransform for every found element*/
		var childs = element.childNodes;
		for( var i = 0, j; j = childs[i]; i++ ) {
			if( j.nodeType == 1 ) {
				childTransform( j );
				if( j.firstChild ) { findChilds( j ); }
			}
		}
	}

	function childTransform(element) {
		var compStyle = window.getComputedStyle(element, null)
		if( compStyle ) {
			var width = compStyle.getPropertyValue('width');
			/*remove the 'px'*/
			width = width.replace(/px/, '');
			var size = compStyle.getPropertyValue('font-size');
			size = size.replace(/px/, '');
			if( size == 0 || width == 0 ) {
				/*Something seems to be wrong*/
				return false;
			}
			var align = compStyle.getPropertyValue('text-align');
			if( width / size < minWidth ) {
				if( align == 'justify' ) {
					element.style.textAlign='left';
					/*element.style.color='red'; //debugging */
				}
			} else {
				if( align == 'left' ) {
					element.style.textAlign='justify';
					/*element.style.color='green'; //debugging */
				}
			}
		}
	}
	/*Call it once*/
	childTransform(document.body);
	findChilds(document.body);
	/*Call it every time the window is resized*/
	document.addEventListener( 'resize', function() { childTransform(document.body); findChilds(document.body); }, false );
},false);