﻿function update()
{

	var formNum;				// name of the form
	var elementNum;			// number of elements within the form
	var maxName;				// name of hidden form control containing default character count
	var charName;				// name of form control displaying character count
	var fieldName;				// name of text area
	
	formNum = document.forms.length;
	
	if (formNum != 0)
	{
		for (i = 0; i < formNum; i++)
		{
			formName = document.forms[i].name;
			elementNum = document.forms[i].elements.length;
			if (elementNum !=0)
			{
				for (j=0; j < elementNum; j++)
				{
					/* This part of the code searches for form elements with the "char_" and "max_" prefix.
						It assumes that any form elements with a "char_" prefix will have a form element
						with a "max_" prefix immediately preceding it.
					*/
					if(document.forms[i].elements[j].name.substr(0,5)=="char_" && document.forms[i].elements[j+1].name.substr(0,4)=="max_")
					{ 
						charName = document.forms[i].elements[j].name;
						maxName = document.forms[i].elements[j+1].name;
						fieldName = document.forms[i].elements[j].name.substr(5);
						
						/* If the required form controls do not exist the function will be
							abandoned and the character count will not work.
						*/
						if (!document.forms[formName]) return;
						if (!document.forms[formName].elements[charName]) return;
						if (!document.forms[formName].elements[charName].value) return;
						if (!document.forms[formName].elements[maxName]) return;
						if (!document.forms[formName].elements[maxName].value) return;
						if (!document.forms[formName].elements[fieldName]) return;
						
						maxlimit = document.forms[formName].elements[maxName].value;
						
						if (document.forms[formName].elements[fieldName].value.length > maxlimit)
							// cut string to max limit
							document.forms[formName].elements[fieldName].value = document.forms[formName].elements[fieldName].value.substring(0, maxlimit);
							
						document.forms[formName].elements[charName].value = maxlimit - document.forms[formName].elements[fieldName].value.length + " chars remaining";
					}
				}
			}
			
		}
	} 

}


/* if any events occur update function is called to update character count. This is required here
	so that reset button works properly for textareas that contain characters to begin with.
*/
if(window.Event)
document.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP | Event.KEYDOWN | Event.KEYUP | Event.MOUSEMOVE);

document.onmousemove = update;
document.onmousedown = update;
document.onmouseup = update;
document.onkeydown = update;
document.onkeyup = update;