// JavaScript Document	

var maxLength = 400; //global textarea length
function SetMaxLength()
{
	var x = document.getElementsByTagName('textarea');
	var lengthCounter = document.createElement('div'); // create p to put the counter in
	lengthCounter.className = 'counter'; // give the div the "counter" class
	for (var i=0;i<x.length;i++)
	{
			var lengthCounterClone = lengthCounter.cloneNode(true);
			lengthCounterClone.relatedElement = x[i];
			lengthCounterClone.innerHTML = "<span>" + maxLength + " of " + maxLength + " characters left.</span>";
			x[i].parentNode.insertBefore(lengthCounterClone,x[i].nextSibling);
			x[i].relatedElement = lengthCounterClone.getElementsByTagName('span')[0];

			x[i].onkeyup = x[i].onchange = CheckMaxLength;
			x[i].onkeyup();
	}
}

function CheckMaxLength()
{
	var extraNote = "They";
	var currentLength = this.value.length;
	if (currentLength > maxLength)
	{
		this.relatedElement.className = 'error'; // if there is too much text, apply this class to the span
		
		if (currentLength-maxLength==1) {extraNote = "It";}
		
		this.relatedElement.firstChild.nodeValue = (currentLength - maxLength) + " too many characters. " + extraNote +" will be removed when you submit this form.";
	}
	else
	{
		this.relatedElement.className = '';
		
		if (currentLength==maxLength) {this.relatedElement.className = 'error';} //Changes the text when the maxLenght is reached.
		
		this.relatedElement.firstChild.nodeValue = maxLength - currentLength + " of  " + maxLength + " characters left."; // changes the text inside the span to this
	}
}
		
addLoadEvent(SetMaxLength);	// run SetMaxLength () onLoad
