function ValidateForm(form)
{


var elemCount = form.elements.length
var i = 0;
var fieldName = '';
var sType, sValue;
var nTmpLen, nTmpIndex, nTmpChecked;

	retValue = true

	forLoop:
        for (i=0; i<elemCount; i++)
		{
			fieldName = form.elements[i].name;
			//alert('fieldName='+fieldName);
			if (eval('form.'+fieldName+'_Req') != null)
			{
				//alert(' req !- null');
				sType = eval('form.'+fieldName+ '.type');
				
				if ( typeof( sType)== "string")
				{
					//alert('in if');
					
					//alert('nTmpLen = ' +nTmpLen);
					
					if( sType.indexOf( "select") >= 0 )
					{
						sValue = eval( "form." + fieldName + ".options[ form." + fieldName + ".selectedIndex].value" );
					}
					else if ( sType.indexOf( "checkbox") >= 0 )
					{
						sValue = eval ("form."+ fieldName +".checked");
						
					}
	             	else
	             	{
						//alert('in else');
	             		sValue = Trim(eval('form.'+fieldName+ '.value'));
	             	}
	             	//alert('sValue = '+sValue);
					if ( Trim( sValue) == '')
					{
						alert (eval('form.'+fieldName+'_Req.value'));
						retValue = false;
						eval('form.'+fieldName+ '.focus()');
	
						break forLoop;
					}
				}
				else if ( typeof( sType)== "radio")
				{
					nTmpLen = eval('form.'+fieldName+ '.length')
					if ( typeof( nTmpLen) == "number")
					{
						nTmpChecked = false;
						
					    for ( nTmpIndex=0; nTmpIndex < nTmpLen; nTmpIndex++)
						{
							if ( eval('form.'+fieldName+ '[' + nTmpIndex + '].checked'))
								{
									nTmpChecked = true;
								}
						}
						if ( !nTmpChecked)
							{
								alert (eval('form.'+fieldName+'_Req.value'));
								retValue = false;
								break forLoop;
							}
					}
				}
				else
				{
					//alert('in else');
					nTmpLen = eval('form.'+fieldName+ '.length')
					//alert('nTmpLen ='+nTmpLen);
					if ( typeof( nTmpLen) == "number")
					{
						nTmpChecked = false;
						
					    for ( nTmpIndex=0; nTmpIndex < nTmpLen; nTmpIndex++)
						{
							if ( eval('form.'+fieldName+ '[' + nTmpIndex + '].checked'))
								{
									nTmpChecked = true;
								}
						}
						if ( !nTmpChecked)
							{
								alert (eval('form.'+fieldName+'_Req.value'));
								retValue = false;
								break forLoop;
							}
					}
				}
			}

			if ((eval('form.'+fieldName+'_Val') != null) && (eval('form.'+fieldName+'.value') != ''))
			{
				var MyStringtype = eval('form.'+fieldName+'_Val.value')
				var fieldType =	MyStringtype.substring(0,MyStringtype.indexOf(":"))
				
				var MyStringValue = eval('form.'+fieldName+'_Val.value')
				var num1 = MyStringValue.lastIndexOf(":")+1
				var num2 = MyStringValue.length
				var MyStringMessage = MyStringValue.substring(num1,num2)

				//retValue = checkDataType(fieldName, eval('form.'+fieldName+'.value'), MyStringtype.substring(0,MyStringtype.indexOf(":")));
				retValue = checkDataType(fieldName, eval('form.'+fieldName+'.value'), MyStringMessage, fieldType);
				
				if (retValue == false)
				{
				    eval('form.'+fieldName+ '.focus()');
     				break forLoop;
				}
			}
		}
		
	return retValue;
}


function checkDataType(FieldName, FieldValue, FieldMessage, FieldType)
{
	switch (FieldType) 
	{
		case "Date": 
		   	return isValidDate(FieldValue,FieldMessage);
		   	break;
		case "Time" : 
		   	return isValidTime(FieldValue,FieldMessage);
		   	break; 
		case "Email":
		   	return isValidEmailId(FieldValue,FieldMessage);
		   	break; 
		case "Number":
		   	return isValidNumber(FieldValue,FieldMessage);
		   	break; 
		case "PosNumber":
		   	return isPositiveNumber( Trim(FieldValue),FieldMessage);
		   	break; 
	   	case "Alpha":
	      	return isValidAlpha(FieldValue,FieldMessage);
	     	break; 
		case "AlphaNum":
	    	return isValidAlphaNumeric(FieldValue,FieldMessage);
	     	break; 
		case "Length":
			return isValidLength(FieldValue, FieldMessage);
			break;
		case "SpecialAlphaNum":  //this is for fields like first name or surname that need to accept "-" or ' or "." 
	    	return isValidSpecialAlphaNum(FieldValue,FieldMessage);
	     	break; 
		case "SpecialAlphaNumComma":  //this is for a slq in 
	    	return isValidSpecialAlphaNumComma(FieldValue,FieldMessage);
	     	break;
		case "":  //This allows for no checking.
	    	return true;
	     	break;
	    default :
	      document.write("Sorry, we are out of range<BR>");
	   }
}

function isValidDate(dateStr,FieldMessage) {
// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
// Also separates date into month, day, and year variables

// To require a 2 digit year entry, use this line instead:
//var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

//updated to 2 digit for year
//var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2})$/;

var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
//alert("Date is not in a valid format.\nEnter Date as DD/MM/YYYY");
	alert(FieldMessage);
	return false;
}
day = matchArray[1]; // parse date into variables
month = matchArray[3];
year = matchArray[4];
//update to 2 digit for year
//year = matchArray[2];
if (month < 1 || month > 12) { // check month range
	alert("Month must be a number between 1 and 12.");
	return false;
}
if (day < 1 || day > 31) {
	alert("Day must be a number between 1 and 31.");
	return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
	alert("Month "+month+" doesn't have 31 days");
	return false;
}
if (month == 2) { // check for february 29th
	var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	if (day>29 || (day==29 && !isleap)) {
		alert("February " + year + " doesn't have " + day + " days.");
		return false;
   }
}
if (year < 1755)
{
	alert("Year is incorrect - please re-enter");
	return false;
}
return true;  // date is valid
}

function isValidEmailId (emailStr,FieldMessage) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern represents the range of characters allowed as
   the first character in a valid username or domain.  I just made it
   the same as above, but if you want to add a different constraint,
   you would change it here. */
var firstChars=validChars
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents at atom (basically a series of
   non-special characters.) */
var atom="(" + firstChars + validChars + "*" + ")"
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the course pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	//alert("Email address seems incorrect (check @ and .'s)")
	alert(FieldMessage)
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert("A part of Email address seems to be invalid.")
    return false
}
/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Destination IP address is invalid.")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name for this Email address seems to be invalid.")
    return false
}
/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl).
   If there's a country code at the end of the address, the full domain
   must include a hostname and category (e.g. host.co.uk or host.pub.nl).
   If it ends in a .com or something, make sure there's a hostname.*/

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   alert("The Email address must end in a three-letter domain, or two-letter country.")
   return false
}

/* If it ends in a country code, we want to make sure there are at
   least 2 atoms preceding it (representing host ) */
if (domArr[domArr.length-1].length==2 && len<2) {
   var errStr="This address ends in two characters, which is a country"
   errStr+=" code.  Country codes must be preceded by "
   errStr+="a hostname"
   alert(errStr)
   return false
}

/* If it just ends in .com, .gov, etc., make sure there's a host name.
   This case can never actually happen because earlier checks take
   care of this implicitly, but we'll do it anyway. */
if (domArr[domArr.length-1].length==3 && len<2) {
   var errStr="This Email address is missing a hostname."
   alert(errStr)
   return false
}
// If we've gotten this far, everything's valid!
return true;
}

function isValidNumber(fieldvalue,FieldMessage) {
var valid = "0123456789"
var ok = true;
var temp;
for (var i=0; i<fieldvalue.length; i++) 
  {
    temp = "" + fieldvalue.substring(i, i+1);
     if (temp == " " || temp == "-" || temp == ".")
     	temp = "1";	
     if (valid.indexOf(temp) == "-1") ok = false;
     //alert(temp);
   }
if (ok == false) 
  {
   //alert("Invalid entry. Only Numbers are accepted.");
   alert(FieldMessage);
   }
return ok;
}


function isPositiveNumber(fieldvalue,FieldMessage) 
{
	var valid = "0123456789"
	var ok = true;
	var temp;
	for (var i=0; i<fieldvalue.length; i++) 
	  {
	    temp = "" + fieldvalue.substring(i, i+1);
	     if (temp == " " || temp == "-" || temp == ".")
		 {
		 	//alert('temp='+temp);
	     	temp = "1";	
			ok = false;
		 }
	     if (valid.indexOf(temp) == "-1") ok = false;
	     //alert(temp);
	   }
	if (ok == false) 
	  {
	   //alert("Invalid entry. Only Numbers are accepted.");
	   alert(FieldMessage);
	   }
	return ok;
}



function isValidAlpha(fieldvalue,FieldMessage) {
var valid = " abcdefghijklmnopqrstuvwxyz"
var ok = true;
var temp;
for (var i=0; i<fieldvalue.length; i++) 
  {
    temp = "" + fieldvalue.substring(i, i+1);
     if (valid.indexOf(temp.toLowerCase()) == "-1") ok = false;
   }
if (ok == false) 
  {
   //alert("Invalid entry. Only Alphabetic Characters are allowed.");
   alert(FieldMessage);
   }
return ok;
}

function isValidAlphaNumeric(fieldvalue,FieldMessage) {
var valid = " -0123456789abcdefghijklmnopqrstuvwxyz"
var ok = true;
var temp;
for (var i=0; i<fieldvalue.length; i++) 
  {
    temp = "" + fieldvalue.substring(i, i+1);
     if (valid.indexOf(temp.toLowerCase()) == "-1") ok = false;
   }
if (ok == false) 
  {
//   alert("Invalid entry. Only Numbers and Characters are allowed.");
   alert(FieldMessage);
   }
return ok;
}


// note: the extra dashes are not minus –—­
function isValidSpecialAlphaNumComma(fieldvalue,FieldMessage) {
var valid = " -'.0123456789abcdefghijklmnopqrstuvwxyz,+_#:=?!()&@/\\–—­";
var ok = true;
var temp;
for (var i=0; i<fieldvalue.length; i++) 
  {
    temp = "" + fieldvalue.substring(i, i+1);
     if (valid.indexOf(temp.toLowerCase()) == "-1") ok = false;
   }
if (ok == false) 
  {
//   alert("Invalid entry. Only Numbers and Characters are allowed.");
   alert(FieldMessage);
   }
return ok;
}


function isValidSpecialAlphaNum(fieldvalue,FieldMessage) {
var valid = " -'.0123456789abcdefghijklmnopqrstuvwxyz"
var ok = true;
var temp;
for (var i=0; i<fieldvalue.length; i++) 
  {
    temp = "" + fieldvalue.substring(i, i+1);
     if (valid.indexOf(temp.toLowerCase()) == "-1") ok = false;
   }
if (ok == false) 
  {
//   alert("Invalid entry. Only Numbers and Characters are allowed.");
   alert(FieldMessage);
   }
return ok;
}

function isValidLength (sFieldvalue, sFieldMessage)
{

}
function isValidTime(timeStr) {
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?$/;

var matchArray = timeStr.match(timePat);
if (matchArray == null) {
alert("Time is not in a valid format.");
return false;
}
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];

if (second=="") { second = null; }
if (ampm=="") { ampm = null }

if (hour < 0  || hour > 23) {
alert("Hour must be between 0 and 23.");
return false;
}
if (minute<0 || minute > 59) {
alert ("Minute must be between 0 and 59.");
return false;
}
if (second != null && (second < 0 || second > 59)) {
alert ("Second must be between 0 and 59.");
return false;
}
return true;
}



function checkMaxLength(t) {
	var displayStart, displayCounting, rtn=true;

	if (t+"" != 'undefined') {
		if (!t.maxlength) {
			t.maxlength = 512;
		}
		
		if (t.value.length > t.maxlength) {
			t.style.color='red';
			displayCounting = ' - Remove ' + (t.value.length - t.maxlength) + ' characters.'		
			rtn = false;
		}	
		else {
			t.style.color='';
			displayCounting = ' - You can add up to ' + (t.maxlength - t.value.length) + ' characters.'		
		}
		
		displayStart 	= 'Input Field: ' + t.name + '. Length: ' + t.value.length + '.  Max:' + t.maxlength ;
		//t.title			= displayStart + displayCounting;
		defaultStatus	= displayStart + displayCounting;
	}
	
	return rtn;
}


function fnDisplayMaxLength(t) {
	var displayStart, displayCounting, rtn=true;
	
	if (t+"" != 'undefined') {
		if (!t.maxlength) {
			t.maxlength = 512;
		}
		
		
		if (t.value.length > t.maxlength) {
			t.style.color='red';
			displayCounting = ' Remove ' + (t.value.length - t.maxlength) + ' character(s).'		
			rtn = false;
		}	
				
		if (!rtn)
		{
			alert(displayCounting);
			t.focus();
		}
	}
	
	return rtn;
}


function Trim(TRIM_VALUE)
{
	if(TRIM_VALUE.length < 1){
		return"";
	}
	
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	
	if(TRIM_VALUE==""){
		return "";
	}
	else{
		return TRIM_VALUE;
	}
} //End Function

function RTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	
	if(v_length < 0){
		return"";
	}
	
	var iTemp = v_length -1;

	while(iTemp > -1){
		if(VALUE.charAt(iTemp) == w_space)
		{}
		else{
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}
		iTemp = iTemp-1;

	} //End While
	return strTemp;

} //End Function

function LTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
	
	if(v_length < 1){
		return"";
	}
	
	var v_length = VALUE.length;
	var strTemp = "";

	var iTemp = 0;

	while(iTemp < v_length)
	{
		if(VALUE.charAt(iTemp) == w_space){
		}
		else
		{
			strTemp = VALUE.substring(iTemp,v_length);
			break;
		}
		iTemp = iTemp + 1;
	} //End While
	
	return strTemp;
} //End Function



