/* -----------------------------------------------------------------------------------
Created by: Anh Gross @ PINT Inc.
   Modified:	 6.7.01
	 								Added new features 
							 9.10.01
							    Added Confirm function
							4.18.02
								Added checkDate function
							12.11.02 
							Kun added unset, reset for Logical OR stuff
							04.18.03
							Kun added check NS4 not support document.getElementById
----------------------------------------------------------------------------------- */

/* -----------------------------------------------------------------------------------
USAGE: include the lines between START to END in your html page:

		//START
		<script src="formcheck.js"></script>
		
		<script>
			set_variables('name','blank','Full Name','');
			set_variables('username','Minimum Length','Username','6');
			set_variables('username','Maximum Length','Username','10');
			set_variables('password','Maximum Length','Password','8');
			set_variables('password','Alpha-Numeric','Password','');
			set_variables('publish_date','Date','Publish Date: Invalid Format','');
		</script>
		//END

IMPORTANT NOTES: 
Call set_variables function for each field you want to check for. This function takes
4 parameters: name, check_for, message, extra_info.

 * name: the exact name of the form field
 * check_for: which type you want to check for. 
			Currently there are 8 types: blank, Email, US Phone, Numeric, Credit Card, Maximum Length,
			Minimum Length, Alpha-Numeric, Date, and File Extension 
			Type names are cAsE sEnSiTiVe!!!
 * message: Any error message you want to include
 * extra_info: Used in Maximum length, Minimum length, File Extension check. Leave
 			blank when not used.
			
 * for Confirm function: extra_info is the second field name used to compare with name
 		example: set_variables('password','Confirm', 'Confirm password failed', 'confirm_password');
				
Other examples of using set_variables:
set_variables('email','Email','Email Address','');
set_variables('phone','US Phone', 'Phone Number','');
set_variables('quantity', 'Numeric', 'Number of hats','');
set_variables('card_number', 'Credit Card', 'Credit Card Number','');
set_variables('prod_image','Product Image','File', 'gif,jpg');	
set_variables('sales_brief','Sales Brief','File', 'xls,txt,doc,pdf');	
----------------------------------------------------------------------------------- */


//==================== USER SHOULD NOT MODIFY BEYOND THIS POINT ====================//

// Initializing global variables
var Names = new Array();
var CheckFor = new Array();
var Errors = new Array();
var ExtraInfo = new Array();
var error_message = "";
var firstfield = "";	
var errorFontIDName = new Array();

/* -----------------------------------------------------------------------------------
Function: 		set_variables
Description:	Set variables to Names, CheckFor and Errors array
----------------------------------------------------------------------------------- */
function set_variables(name, check_for, message, extra_info)
{
	 var i = Names.length;
	 Names[i] = name; 
	 CheckFor[i] = check_for; 
	 Errors[i] = message;
	 ExtraInfo[i] = extra_info;
}
/* -----------------------------------------------------------------------------------
Function: 		unset_variables
Description:	unSet variables NOT to check this element again
----------------------------------------------------------------------------------- */
function unset_variables(name,form)
{
	 for (i = 0; i < Names.length; i++)
	 {
	 	field_name = eval('form.'+Names[i]).name;
		//type = eval('form.'+Names[i]).type;
		if (field_name == name )//|| !type)
		{
			Errors[i] = "";
			ExtraInfo[i] = "Unset";
		}
	 }
}
/* -----------------------------------------------------------------------------------
Function: 		unset_radio_variables
Description:	unSet ALL radio variables NOT to check all radios again ONLY for BARONA
----------------------------------------------------------------------------------- */
function unset_radio_variables(form)
{
	 for (i = 0; i < Names.length; i++)
	 {
		type = eval('form.'+Names[i]).type;
		if (!type)
		{
			Errors[i] = "";
			ExtraInfo[i] = "Unset";
		}
	 }
}
/* -----------------------------------------------------------------------------------
Function: 		reset_variables for logical OR
Description:	reSet variables to check this element again **** specific for sdsu only
				need to refactor for other project for reseting with 
				2 more arguments msg and extra so it can decouple this code from 
				the specific project.
				What was I thinking doing this?  Time limit and get thing to work and see
				first and lazy to go back in and refator it.
				Think it again I will refactor it now.!!!*** can't reset radio or checkbox now
----------------------------------------------------------------------------------- */
function reset_variables(name,form,check_for,message,extra_info)
{
	 for (i = 0; i < Names.length; i++)
	 {
	 	field_name = eval('form.'+Names[i]).name;
		if (field_name == name)
		{
			Errors[i] = message;
			ExtraInfo[i] = extra_info;
			CheckFor[i] = check_for;
		}
	 }
}

/* -----------------------------------------------------------------------------------
Function: 		check_form
Description:	Main function which will process the Names, CheckFor and Errors arrays
							and call appropriate functions for specific type check.
----------------------------------------------------------------------------------- */
function check_form(form)
{
	for (i = 0; i < Names.length; i++)
	{
		type = eval('form.'+Names[i]).type;
		field = eval('form.'+Names[i]);
		msg = Errors[i];
		Xinfo = ExtraInfo[i];

		if( type == "text" || type == "textarea" || type == "password" || type == "file")
		{
			if(CheckFor[i] == "US Phone") 
				checkUSPhone(field,msg);
				
			else if(CheckFor[i] == "Email") 
				checkEmail(field,msg);
				
			else if(CheckFor[i] == "Numeric") 
				isNumeric(field,msg);
				
			else if(CheckFor[i] == "Double") 
				validateDouble(field,msg,30,2);
			
			else if(CheckFor[i] == "Not Same Number") 
				isNotSameNumber(field,msg);
				
			else if(CheckFor[i] == "Credit Card") 
				checkCard(field,msg);
				
			else if(CheckFor[i] == "Maximum Length")
				checkMaxLength(field,msg,Xinfo);
				
			else if(CheckFor[i] == "Minimum Length")
				checkMinLength(field,msg,Xinfo);
				
			else if(CheckFor[i] == "Alpha-Numeric")
				isAlphaNumeric(field,msg);
				
			else if(CheckFor[i] == "File Extension")
				checkFileExtension(field,msg,Xinfo);
				
			else if(CheckFor[i] == "Confirm")
			{
				field2 = eval('form.'+ Xinfo);	
				checkConfirm(field,field2,msg);
			}
			
			else if(CheckFor[i] == "Two Date Comparison")
			{
				field2 = eval('form.'+ Xinfo);	
				doDateCheck(field,field2,msg);
			}
			
			else if(CheckFor[i] == "Date")
				checkDate(field,msg);
			
			else if(CheckFor[i] == "History Date")
				checkHistoryDate(field,msg);
				
			else if(CheckFor[i] == "Future Date")
				checkFutureDate(field,msg);
			
			else if(CheckFor[i] == "Date Format")
				checkDateFormat(field,msg,Xinfo);
				
			else if(CheckFor[i] == "Month Year Format")
				checkMonthYearFormat(field,msg,Xinfo);
			else 
				checkText(field,msg,Xinfo);						
		}
			
		else if(type == "select-one" || type == "select-multiple")
			checkSelect(field,msg);			
			
		//checkbox/radio field has length one		
		else if(type == "checkbox" || type == "radio")	
			checkSingleRadioXBox(field,msg,Xinfo);	
	
		//checkbox/radio field has length greater than one
		else if(!type)
			checkRadioXbox(field,msg,Xinfo);	
		else{}	
	}
	
	return check_message();	
}


/* -----------------------------------------------------------------------------------
Function: 		check_message
Description:	Check to see if there is any error message collected.
							Return true if no error was found.
							Return false if error was found
----------------------------------------------------------------------------------- */
function check_message()
{
	back_event = "";
	for (i = 0; i < document.forms[0].elements.length; i++ )
		{
		if (document.forms[0].elements[i].name == "Back")
			{
			back_event = document.forms[0].elements[i].value;
			}
		}
	//alert(back_event);
	if( back_event == "back to previous page")
	{
	return true;
	}
	else if(error_message != "")
	{
		alert("Please fix the following required fields:\n" + error_message);

		//reset error message to blank
		error_message = "";
		
		if(window.focus)
		{
			if(firstfield != "")
			{
			  focusfield = firstfield;
				firstfield = "";
				//focusfield.focus();		
			}  
		}
		return false;
	}
return true;
}

/* -----------------------------------------------------------------------------------
Function: 		checkText
Description:	Check for blank value in fields of type TEXT. 
							Add error message if value in blank
----------------------------------------------------------------------------------- */
function checkText(field,error,Xinfo)
{
	if(field.value == "" && Xinfo != "Unset")	
	{
		error_message += error + "\n";	
		turnRed(field);
		if(firstfield == "")
			firstfield = field;
	}
	else
	{
		turnBlack(field);
	}
}


/* -----------------------------------------------------------------------------------
Function: 		checkSelect
Description:	Check for a selection from fields of type SELECT (One or Multiple). 
							Add error message if no selection was made.
----------------------------------------------------------------------------------- */
function checkSelect(field,error)
{
	selected = field.selectedIndex;
	
	if(field[selected].value == "")
	{
		turnRed(field);
		error_message += error + "\n";
		if(firstfield == "")
			firstfield = field;
	}
	else
	{
		turnBlack(field);
	}
}


/* -----------------------------------------------------------------------------------
Function: 		checkSingleRadioXBox
Description:	Check for a selection from fields of type RADIO or CHECKBOX with ONLY ONE
							element. 
							Add error message if no selection was made.
----------------------------------------------------------------------------------- */
function checkSingleRadioXBox(field,error,Xinfo)
{
	if(!field.checked && Xinfo != "Unset")
	{
		turnRed(field);
		error_message += error + "\n";
	}
	else
	{
		turnBlack(field);
	}
}


/* -----------------------------------------------------------------------------------
Function: 		checkRadioXbox
Description:	Check for a selection from fields of type RADIO or CHECKBOX with MORE THAN
							ONE element. 
							Add error message if no selection was made.
----------------------------------------------------------------------------------- */
function checkRadioXbox(field,error,Xinfo)
{
	var checkedOne = 0;
	//loop through the field elements to check for selection
	for(var i = 0; i < field.length; i++)
	{
		if(field[i].checked)
			checkedOne = 1;
	}
	
	if(!checkedOne && Xinfo != "Unset")
	{
		turnRed(field);
		error_message += error + "\n";	
	}
	else
	{
		turnBlack(field);
	}
}

/* -----------------------------------------------------------------------------------
Function: 		checkMaxLength
Description:	Check for maximum length of value
							Add error message if length is greater than maximum characters allowed
----------------------------------------------------------------------------------- */
function checkMaxLength(field,error,maximum)
{
	//checkText(field,error);
	if(field.value.length > maximum)
	{
		turnRed(field);
		error_message += error + "\n";
		if(firstfield == "")
			firstfield = field;
	}
	else
	{
		turnBlack(field);
	}
}

/* -----------------------------------------------------------------------------------
Function: 		checkMinLength
Description:	Check for mininum length of value
							Add error message if length is less than minimum characters required
----------------------------------------------------------------------------------- */
function checkMinLength(field,error,minimum)
{
	if(field.value.length < minimum)
	{
		turnRed(field);
		error_message += error + "\n";
		if(firstfield == "")
			firstfield = field;
	}
	else
	{
		turnBlack(field);
	}
}

/* -----------------------------------------------------------------------------------
Function: 		checkAreaCode
Description:	Check for minimum length of value
							Add error message if length is less than minimum characters required
----------------------------------------------------------------------------------- */
function checkAreaCode(field,minimum)
{
	if (minimum == "Unset")
		minimum = 3;
	if(field.value.length < minimum)
	{
		return false;
	}
	else
	{
		return true;
	}
}

/* -----------------------------------------------------------------------------------
Function: 		checkPhone
Description:	Check for minimum length of value
							Add error message if length is less than minimum characters required
----------------------------------------------------------------------------------- */
function checkPhone(field,minimum)
{
	if (minimum == "Unset")
		minimum = 7;
	if(field.value.length < minimum)
	{
		return false;
	}
	else
	{
		return true;
	}
}

/* -----------------------------------------------------------------------------------
Function: 		checkExtension
Description:	Check for minimum length of value
							Add error message if length is less than minimum characters required
----------------------------------------------------------------------------------- */
function checkExtension(field,minimum)
{
	if (minimum == "Unset")
		minimum = 5;
	if(field.value.length < minimum)
	{
		return false;
	}
	else
	{
		return true;
	}
}



/* -----------------------------------------------------------------------------------
Function: 		CheckCard
Description:	Check to see if credit card number is either a valid Visa, MasterCard
							or American Express.
							Add error message if card number is invalid
----------------------------------------------------------------------------------- */
function checkCard(field,error)
{
	var card = field.value;
	
	if(!( isVisa(card) || isMasterCard(card) || isAmericanExpress(card) ))
	{
		turnRed(field);
		error_message += error + ": invalid card number\n";
		if(firstfield == "")
			firstfield = field;
	}
	else
	{
		turnBlack(field);
	}
}


/* -----------------------------------------------------------------------------------
Function: 		isCreditCard
Description:	Check to see if credit card number is valid.
							Return true if a valid number.
							Return false if not a valid number.
----------------------------------------------------------------------------------- */
function isCreditCard(st) 
{
  
	// Encoding only works on cards with less than 19 digits
  if (st.length > 19)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);

}


/* -----------------------------------------------------------------------------------
Function: 		isVisa
Description:	Check for valid Visa card number.
							Add error message if not a valid Visa number.
----------------------------------------------------------------------------------- */
function isVisa(cc)
{
  
	//strip all non-digit characters
	cc = stripNotAllowable(cc, "1234567890");
	
	if (((cc.length == 16) || (cc.length == 13)) && (cc.substring(0,1) == 4))
	  return (isCreditCard(cc))
	return false;		
}


/* -----------------------------------------------------------------------------------
Function: 		isMasterCard
Description:	Check for valid MasterCard number.
							Add error message if not a valid MasterCard number.
----------------------------------------------------------------------------------- */
function isMasterCard(cc)
{
  
	//strip all non-digit characters
	cc = stripNotAllowable(cc, "1234567890");
	
	firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) && ((seconddig >= 1) && (seconddig <= 5)))
    return (isCreditCard(cc))
	return false;
}


/* -----------------------------------------------------------------------------------
Function: 		isAmericanExpress
Description:	Check for valid American Express number.
							Add error message if not a valid American Express number.
----------------------------------------------------------------------------------- */
function isAmericanExpress(cc)
{
  
	//strip all non-digit characters
	cc = stripNotAllowable(cc, "1234567890");
	
	firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) && ((seconddig == 4) || (seconddig == 7)))
  	return (isCreditCard(cc))
	return false;
}


/* -----------------------------------------------------------------------------------
Function: 		stripNotAllowable
Description:	Stripping all characters not allowed in a list of allowed characters.
							Return the cleaned up string.
----------------------------------------------------------------------------------- */
function stripNotAllowable(s, allowable)
{ 
	var returnString = "";

  // Search through string's characters one by one.  If character is allowable, append to returnString.	
	for (var i = 0; i < s.length; i++)
	{   
	   var c = s.charAt(i);
	   if (allowable.indexOf(c) != -1) 
		 	returnString += c;
	}
	
	return returnString;
}


/* -----------------------------------------------------------------------------------
Function: 		checkUSPhone
Description:	Check for valid US phone numbers (consists of ten digits)
							Add error message if not a valid number
----------------------------------------------------------------------------------- */
function checkUSPhone(field, error)
{
	
	//make sure that field value exists
	checkText(field,error + ' can not be empty');
	
	if (field.value.length > 0)
	{
		var badformat = 0;
		
		//checking for non-allowable characters
		var str = stripNotAllowable(field.value, "1234567890.()- ");
		badformat = (str.length < field.value.length)?1:0;
		
		//checking for 10 digits
		USPhone = stripNotAllowable(field.value, "1234567890");
		// 01.30.02 - M. Richard, allowed us Phone numbers to a length of 7
		badformat = ( (USPhone.length != 10 && USPhone.length != 7) || badformat )?1:0;

		if (badformat) 
		{
			turnRed(field);
			error_message += error +": wrong format\n";	
			if(firstfield == "")
				firstfield = field;
		}
		else
		{
			turnBlack(field);
		}
	}
}


/* -----------------------------------------------------------------------------------
Function: 		checkEmail
Description:	Check for valid email addresses
							Add error message if not a valid email address
----------------------------------------------------------------------------------- */
function checkEmail(field,error)
{
	
	//make sure that field value exists
	checkText(field,error + ' can not be empty');
	
	if (field.value.length > 0)
	{
		var email = field.value;
		var len = email.length;
		var badformat = false;
		
		//check for illegal characters in email
		illegalChars = stripNotAllowable(email, "'\"\\/()`~!#$%^&*+}{|:;?><,[]");
		
		firstChar = stripNotAllowable(email.charAt(0), ".@");
		lastChar = stripNotAllowable(email.charAt(len - 1), ".@");
		
		//email length must be > 5, there must be an @ and a . and they can not be at the end of the email string
		if (len < 5 || email.indexOf('@') == -1 || firstChar != "" || lastChar != "")
	  	badformat = true;
		else
		{
			var firstAt = email.indexOf('@');
			var afterAt = email.substring(firstAt +1, len);
			
			var Atcounts = stripNotAllowable(afterAt, "@");
			var Pcounts	 = stripNotAllowable(afterAt, ".");
			
			// more @ after first @ or no . after first @ or period is found right after first @ set badformat to true
			badformat = (Atcounts.length > 0 || Pcounts == 0 || email.charAt(firstAt+1)== '.' || illegalChars != '')? true:false;
	
		}
		
		if(badformat)
		{
				turnRed(field);
				error_message += error +": wrong format\n";	
				if(firstfield == "")
					firstfield = field;
		}
		else
		{
			turnBlack(field);
		}
	}
}

/* -----------------------------------------------------------------------------------
Function: 		checkConfirm
Description:	Making sure that 2 field values matche. Use for confirming passord, email, etc.
							Add error message if values do not match
----------------------------------------------------------------------------------- */
function checkConfirm(field, field2, error)
{ 
	
	if (field.value.toLowerCase() != field2.value.toLowerCase())
	{
		turnRed(field);
		error_message += error + "\n";	
		if(firstfield == "")
			firstfield = field2;
	}
	else
	{
		turnBlack(field);
	}
}	

/* -----------------------------------------------------------------------------------
Function: 		isNumeric
Description:	Checking for numeric value.
							Add error message if value is not numeric
----------------------------------------------------------------------------------- */
function isNumeric(field, error)
{ 
	//make sure that field value exists
	checkText(field,error + ' can not be empty');
	
	if (field.value.length > 0)
	{
		if(isNaN(field.value))
		{
			turnRed(field);
			error_message += error + " must be numeric\n";	
				if(firstfield == "")
					firstfield = field;
		}
		else
		{
			turnBlack(field);
		}
	}
}	

/* -----------------------------------------------------------------------------------
Function: 		isNotSameNumber
Description:	Checking for all zeros.
							Add error message if value is same number
Programmer:     Kun Puparussanon (Barona ssn# Only)
----------------------------------------------------------------------------------- */
function isNotSameNumber(field, error)
{ 
	//make sure that field value exists
	//checkText(field,error + ' can not be empty');
	
	if (   field.value == '000000000' || field.value == '111111111' 
		|| field.value == '222222222' || field.value == '333333333'
		|| field.value == '444444444' || field.value == '555555555'
		|| field.value == '666666666' || field.value == '777777777'
		|| field.value == '888888888' || field.value == '999999999'
		|| field.value == '123456789')
	{
		turnRed(field);
		error_message += error + " must NOT the same numbers\n";	
			if(firstfield == "")
				firstfield = field;
	}
	else
	{
		turnBlack(field);
	}
}	


/* -----------------------------------------------------------------------------------
Function: 		isAlphaNumeric
Description:	Checking for alpha-numeric value.
							Add error message if value is not alpha-numeric
----------------------------------------------------------------------------------- */
function isAlphaNumeric(field, error)
{ 
	
	//make sure that field value exists
	checkText(field,error + ' can not be empty');
	
	if (field.value.length > 0)
	{
		Alpha = stripNotAllowable(field.value, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
		Numeric = stripNotAllowable(field.value, "0123456789");
		
		if(Alpha.length == 0 || Numeric.length == 0 || (Alpha.length + Numeric.length) < field.value.length)
		{
			turnRed(field);
			error_message += error +  " must be alpha-numeric\n";	
				if(firstfield == "")
					firstfield = field;
		}
		else
		{
			turnBlack(field);
		}
	}
}	

/* -----------------------------------------------------------------------------------
Function: 		checkFileExtension
Description:	Checking for a valid file extension when uploading a file.
							Add error message if file extension is not in the allowable extension list
----------------------------------------------------------------------------------- */
function checkFileExtension(field, error, extensions)
{ 
	checkText(field,error + ' can not be empty');
	if (field.value.length > 0)
	{
		var extArray = new Array();
		var extFound = 0;
		
		extensions = extensions.toLowerCase();
		
		// full path of file being uploaded
		file = field.value.toLowerCase();	
		
		// getting the extension for file being uploaded
		ext = file.substring(file.indexOf('.') +1, file.length);
		
		// store allowable extensions in a temp variable
		tempext = extensions;
		
		// get the first comma
		var commaIndex = tempext.indexOf(',');
	
		while (commaIndex > 0)
		{
			sublist = tempext.substring(0, commaIndex);
			extArray[extArray.length] = sublist;	
			tempext = tempext.substring(commaIndex +1,tempext.length);
			commaIndex = tempext.indexOf(',');
			if(commaIndex < 0)
				extArray[extArray.length] = tempext;			
		}
		
		for(var i=0; i < extArray.length; i++)
		{
			if(extArray[i] == ext)		
				extFound = 1;
		}
		
		if(!extFound)
		{
			turnRed(field);
			error_message += error +  ": wrong file extension\n";	
				if(firstfield == "")
					firstfield = field;
		}
		else
		{
			turnBlack(field);
		}
	}
}	


/* -----------------------------------------------------------------------------------
Function: 		checkDate
Description:	Check for valid date format
----------------------------------------------------------------------------------- */
function checkDate(field, error)
{ 
	if (field.value.length > 0)
	{
		var date = Date.parse(field.value);
		
		if(isNaN(date))
		{
			turnRed(field);
			error_message += error + "\n";	
				if(firstfield == "")
					firstfield = field;
		}
		else
		{
			turnBlack(field);
		}
	}
}
/* -----------------------------------------------------------------------------------
Function: 		checkDateFormat
Description:	Check for valid date format
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */
function checkDateFormat(field, error, Xinfo)
{ 
	//check format as mm/dd/yyyy only
	if (field.value.length > 0 || Xinfo == "Required")
	{
		var dateString = field.value;
		var month = dateString.substring(0,2)-1;
		var slash1 = dateString.substring(2,3);
		var slash2 = dateString.substring(5,6);
		var day = dateString.substring(3,5);
		var year = dateString.substring(6);
		var date = new Date(year,month,day,0,0,0,0);
		var full_year = takeYear(date);
		if(isNaN(date) || month != date.getMonth() || /*full_year != year || */ //reason is not valid before 1970
		   day != date.getDate() || slash1 != '/' || slash2 != '/' || field.value.length != 10)
		{
			turnRed(field);
			error_message += error + "\n";	
				if(firstfield == "")
					firstfield = field;
		}
		else
		{
			turnBlack(field);
		}
	}
}
/* -----------------------------------------------------------------------------------
Function: 		checkMonthYearFormat
Description:	Check for valid date format
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */
function checkMonthYearFormat(field, error, Xinfo)
{ 
	//check format as mm/yyyy only
	if (field.value.length > 0 || Xinfo == "Required")
	{
		var dateString = field.value;
		var month = dateString.substring(0,2)-1;
		var day = 1;
		var slash = dateString.substring(2,3);
		var year = dateString.substring(3);
		var date = new Date(year,month,day,0,0,0,0);
		var full_year = takeYear(date);
		if(isNaN(date) || month != date.getMonth() || /* full_year != year || */ //reason is not valid before 1970
		   field.value.length != 7 || slash != '/')
		{
			turnRed(field);
			error_message += error + "\n";	
				if(firstfield == "")
					firstfield = field;
		}
		else
		{
			turnBlack(field);
		}
	}
}
/* -----------------------------------------------------------------------------------
Function: 		takeYear
Description:	Since it is supported by all browsers, always use getYear(). 
				Divide the outcome by 100 and take the modulus, so that now we have a number from 0 to 99. 
				If this number is smaller than 38, add 2000, if it's larger add 1900. 
				This always gives the correct year. (Why 38? Because Epoch Time will end in 2038. 
				You can also use 70, because in the Epoch Time system no date can be before 1970).
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */
function takeYear(theDate)
{
	x = theDate.getYear();
	var y = x % 100;
	y += (y < 38) ? 2000 : 1900;
	return y;
}


/* -----------------------------------------------------------------------------------
Function: 		turnRed
Description:	change text color of font of each form element to be red
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */
function turnRed(field)
{
	var field_name = field.name + '_font';
	if(field_name) 
	{
		if (!document.layers)// NS4 not support getElementById
		{
			if(document.getElementById(field_name))
			{
				document.getElementById(field_name).style.color='red';
			}
		}
	}
}
/* -----------------------------------------------------------------------------------
Function: 		turnBlack
Description:	change text color of font of each form element to be black
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */
function turnBlack(field)
{
	var field_name = field.name + '_font';
	if(field_name) 
	{
		if (!document.layers)// NS4 not support getElementById
		{
			if(document.getElementById(field_name))
			{
				document.getElementById(field_name).style.color='red';
			}
		}
	}
}
/* -----------------------------------------------------------------------------------
Function: 		numbersOnly
Description:	not allow any characters but the numbers
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */
function numbersOnly(field, event)
{
 var key,keychar;

 if (window.event)
   key = window.event.keyCode;
 else if (event)
    key = event.which;
 else
    return true;
 keychar = String.fromCharCode(key);
  // check for special characters like backspace etc.
 if ((key==null) || (key==0) || (key==8) || 
     (key==9) || (key==13) || (key==27) )
   return true;
  else if ((("0123456789").indexOf(keychar) > -1))
         {
           window.status = "";
           return true;
         }
       else
         {
           window.status = "Field only accept numbers"; 
           return false;
         }
 }
/* -----------------------------------------------------------------------------------
Function: 		decimalOnly
Description:	not allow any characters but the number and .
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */
function decimalOnly(field, event)
{
 var key,keychar;

 if (window.event)
   key = window.event.keyCode;
 else if (event)
    key = event.which;
 else
    return true;
 keychar = String.fromCharCode(key);
  // check for special characters like backspace etc.
 if ((key==null) || (key==0) || (key==8) || 
     (key==9) || (key==13) || (key==27) )
   return true;
  else if ((("0123456789.").indexOf(keychar) > -1))
         {
           window.status = "";
           return true;
         }
       else
         {
           window.status = "Field only accept decimal number"; 
           return false;
         }
 }
 /* -----------------------------------------------------------------------------------
Function: 		numbersSlashOnly
Description:	not allow any characters but the number and /
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */
function numbersSlashOnly(field, event)
{
 var key,keychar;

 if (window.event)
   key = window.event.keyCode;
 else if (event)
    key = event.which;
 else
    return true;
 keychar = String.fromCharCode(key);
  // check for special characters like backspace etc.
 if ((key==null) || (key==0) || (key==8) || 
     (key==9) || (key==13) || (key==27) )
   return true;
  else if ((("0123456789/").indexOf(keychar) > -1))
         {
           window.status = "";
           return true;
         }
       else
         {
           window.status = "Field only accept decimal number"; 
           return false;
         }
 }
/* -----------------------------------------------------------------------------------
Function: 		validateDouble
Description:	as the name tell
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */
 function validateDouble(field, error, len, precision) {
 	var number 		   = field.value;
    var num_pieces     = number.split(".");
    var num_length     = number.length;
	
	if( number == "")
		return true;
    // Generic number check
    if( (number == "") || (number < 0) || (isNaN(number)) ) {
		turnRed(field);
			error_message += error +  "This is not a valid number.\n";	
				if(firstfield == "")
					firstfield = field;
         //alert("This is not a valid number.");
         //return false;
    }
	else {
		turnBlack(field);
	}

    // Check decimal count
    if(num_pieces.length != 2) {
		turnRed(field);
			error_message += error +  " Please insert the number with 2 digit decimal.\n";	
				if(firstfield == "")
					firstfield = field;
    }
	else {
		turnBlack(field);
	}
         //alert("There are too many decimals in your number.");
         //return false;
 
    // Check full length
    num_length -= (num_pieces.length == 2 && num_pieces[1].length <= 0) ? 1:0; // handle trailing decimal
    if(num_length > len) {
		turnRed(field);
			error_message += error +  "This number is too large!\n";	
				if(firstfield == "")
					firstfield = field;
    }
	else {
		turnBlack(field);
	}
         //alert("This number is too large!");
        // return false;

    // Check decimal places
    if( (num_pieces.length == 2) && (num_pieces[1].length != precision)) {
		turnRed(field);
			error_message += error +  " Please enter with 2 digits decimal!\n";	
				if(firstfield == "")
					firstfield = field;
    }
	else {
		turnBlack(field);
	}
         //alert("This number has too many decimal places.");
         //return false;

    // Successful
	//return true;
    //alert(number + " is a valid number."); */
}

/* -----------------------------------------------------------------------------------
Function: 		doDateCheck
Description:	if the end date come after start date
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */

function doDateCheck(startDate,endDate,error) 
	{
		if ( startDate.value.length > 0 ) 
		{
			var prefix = new String("1/");
			var startDateString = prefix.concat(startDate.value);
			var endDateString = prefix.concat(endDate.value);
			if (Date.parse(startDateString) > Date.parse(endDateString))
				{
				turnRed(startDate);
					error_message += error + "\n";	
						if(firstfield == "")
							firstfield = startDate;
				}
			else
				{
				turnBlack(startDate);
				}
		}
	}
/* -----------------------------------------------------------------------------------
Function: 		checkHistoryDate
Description:	if the end date come after start date
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */

function checkHistoryDate(field,error) 
	{
		if ( field.value.length > 0 ) 
		{
			var dateString = field.value;
			var month = dateString.substring(0,2)-1;
			var day = 1;
			var year = dateString.substring(3);
			var theDate = new Date(year,month,day,0,0,0,0);
			var todayDate = new Date();
			if (Date.parse(theDate) > todayDate )
				{
				turnRed(field);
					error_message += error + "\n";
						if(firstfield == "")
							firstfield = field;
				}
			else
				{
				turnBlack(field);
				}
		}
	}
	
/* -----------------------------------------------------------------------------------
Function: 		checkHistoryDate
Description:	if the end date come after start date
Programmer:		Kun Puparussanon
----------------------------------------------------------------------------------- */

function checkFutureDate(field,error) 
	{
		if ( field.value.length > 0 ) 
		{
			var todayDate = new Date();
			if (Date.parse(field.value) < todayDate )
				{
				turnRed(field);
					error_message += error + "\n";
						if(firstfield == "")
							firstfield = field;
				}
			else
				{
				turnBlack(field);
				}
		}
	}

