/**********************************************************
Author:
Adam Barry
Klestrup | partners
www.klestrup-partners.dk

Date: June 20 2008

© 2008 Adam Barry, all rights reserved

-----------------------------------------------------------

Name:
textFieldHandler script

-----------------------------------------------------------
Description:
Functions that enables dynamic style-switching when input
fields are filled.

-----------------------------------------------------------
Usage:
Simply place a link to the this script in the head-section
of the XHTML page. The script will then automatically
execute on page load.

<script type="text/javascript" src="textFieldHandler.js"></script>

<fieldset>
	<input class="text" type="text" />
</fieldset>

-----------------------------------------------------------
Dependencies:
This script depends on the windowOnLoad-script to execute

**********************************************************/

function controlInputFields() {
	if (!document.getElementsByTagName) return;

	var inputs = document.getElementsByTagName('input');

	if (!inputs) return;

	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].className.indexOf('text')>=0) {
			var me = inputs[i];
			me.onkeyup = function() {
				toggleInputClass(this);
			}

			me.onblur = function() {
				toggleInputClass(this);
			}

			/* If the page is refreshed, make sure that filled fields have a correponding classname */
			if (me.value !="") {
				me.className += " filled";
			}
		}
	}
}addLoadEvent(function(){controlInputFields();});


function toggleInputClass(element) {

	if (element.value.length > 0) {

		/* If the element contains text, but does not yet have its classname set to 'filled' */
		if (element.className.indexOf("filled") < 0) {
			element.className += " filled";
		}

		/* If an error class is set on the current element then remove it when typing occurs */
		if (element.className.indexOf("error") > -1) {
			element.className = element.className.replace(new RegExp("error\\b"), "");
		}
	}

	/* If the element does not contain any text then remove the 'filled' class */
	else {
		element.className = element.className.replace(new RegExp("filled\\b"), "");
	}

	if (element.className.indexOf("error") > -1) {
		element.className = element.className.replace(new RegExp("error\\b"), "");
	}
}
