/**********************************************************
Author:
Adam Barry
Klestrup partners
www.klestrup-partners.dk

Date: March 9 2009

© 2009 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 type="text" class="text" />
</fieldset>

-----------------------------------------------------------
Dependencies:
windowOnLoad.js

-----------------------------------------------------------
Revision history:

2009-05-18: Maxlength-functionality for input and password
fields added

**********************************************************/

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].type == "text" || inputs[i].type == "password") {
			var me = inputs[i];
			me.onkeydown = function(event) {
				var evt = event || window.event;

				toggleInputClass(this);

				if (this.getAttribute("maxlength")) {
					var maxlength = this.getAttribute("maxlength");

					if (evt.keyCode >= 48 && this.value.length >= maxlength) {
						focusOnNextElement(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"), "");
	}
}


function focusOnNextElement(element) {

	if (!element.form) return;

	var elements = element.form.elements;

	if (!elements) return;

	for (var i = 0; i < elements.length; i++) {
		if (elements[i] == element && elements[i+1]) {
			elements[i+1].focus();
		}
	}
}
