// ***********************************************************
// Edit Checking Functions:
//		The functions below are common Javascript routines to
//		perform edit checks on data entry input. The current list is:
//			1. isNum(aValue)
//			2. isNumFloat(aValue)
//			3. isDateMmYyyy(aValue)
//			4. isDateMmDdYyyy(aValue)
//			5. isNotFutureDate(aValue)
//			6. isInteger(aValue)
//			7. isTelephone(aValue)
//			8. isSSN(aValue)
//			9. isZip(aValue)
//			10. isState(aValue)
//			11. isASCIIChar(aValue)
//			12. getTodayMmDdYyyy(aValue)
//			13. getFullYear(aYear)
//			14. getNumOfDays(startDate, endDate)
//			15. firstDateIsGreater(date1, date2)
//			16. isUsername(aValue)
//			17  isEmail(aValue)
// ***********************************************************

function isNum(theString) {
    flag = true;
    for (i = 0; i < theString.length; i++) {
        if ((theString.substring(i, i+1) != '0') &&
	    (theString.substring(i, i+1) != '1') &&
	    (theString.substring(i, i+1) != '2') &&
	    (theString.substring(i, i+1) != '3') &&
	    (theString.substring(i, i+1) != '4') &&
	    (theString.substring(i, i+1) != '5') &&
	    (theString.substring(i, i+1) != '6') &&
	    (theString.substring(i, i+1) != '7') &&
	    (theString.substring(i, i+1) != '8') &&
	    (theString.substring(i, i+1) != '9'))
        {
            flag = false;
            break;
        }
    }
    return(flag);
}

function isNumFloat( numstr ) {
	// Return immediately if an invalid value was passed in
	if (numstr+"" == "undefined" || numstr+"" == "null" || numstr+"" == "")
		return false;

	var isValid = true;
	var decCount = 0;		// number of decimal points in the string

	// convert to a string for performing string comparisons.
	numstr += "";

	// Loop through string and test each character. If any
	// character is not a number, return a false result.
 	// Include special cases for negative numbers (first char == '-')
	// and a single decimal point (any one char in string == '.').
	for (i = 0; i < numstr.length; i++) {
		// track number of decimal points
		if (numstr.charAt(i) == ".")
			decCount++;

    	if (!((numstr.charAt(i) >= "0") && (numstr.charAt(i) <= "9") ||
				(numstr.charAt(i) == "-") || (numstr.charAt(i) == "."))) {
       	isValid = false;
       	break;
		} else if ((numstr.charAt(i) == "-" && i != 0) ||
				(numstr.charAt(i) == "." && numstr.length == 1) ||
			  (numstr.charAt(i) == "." && decCount > 1)) {
       	isValid = false;
       	break;
      }
   }

   	return isValid;
}

function isDateMmYyyy(str_input)
{
	int_month = parseInt(parseFloat(str_input.substring(0,2)));
	int_year = parseInt(parseFloat(str_input.substring(3,7)));
	if(!isInteger(str_input.substring(0,2)) || !isInteger(str_input.substring(3,7))) {
		return "F"
	}
	str_msg = 'Success';	//If no problems are found, Success will be returned to calling function
	str_separator_1 = str_input.substring(2,3)

	if (str_input == "") {  //blank fields are not fatal errors
		return "Success";
	}

	if (str_input.length != 7)
	{
		str_msg = 'Invalid Date.  Wrong length.'
		return str_msg;	//Can't be MM/YYYY unless 10 digits
	}

	if (!(int_month > 0 && int_month < 13))
	{
		str_msg = 'Invalid Month.';
		return str_msg;	//Not a valid month
	}
	if (!(int_year > 0 && int_year < 3000) || isNaN(int_year))
	{
		str_msg = 'Invalid Year.';
		return str_msg;	//Not a valid year
	}

	//Valid Date
	return str_msg;	//Sucess
}

function isDateMmDdYyyy(str_input)
{
	int_month = parseInt(parseFloat(str_input.substring(0,2)));
	int_day = parseInt(parseFloat(str_input.substring(3,5)));
	int_year = parseInt(parseFloat(str_input.substring(6,10)));
if (str_input == "") {
		return (str_input);
} else {	
	if(!isInteger(str_input.substring(0,2)) || !isInteger(str_input.substring(3,5)) || !isInteger(str_input.substring(6,10))) {
		return (-1);
	}
	//str_msg = 'Success';	//If no problems are found, Success will be returned to calling function

	str_separator_1 = str_input.substring(2,3)
	str_separator_2 = str_input.substring(5,6)

	
	if (str_input.length != 10)
	{
		str_msg = 'Invalid Date.  Wrong length.'
		return (-2);	//Can't be MM/DD/YYYY unless 10 digits
	}

	if (str_separator_1 != "/" || str_separator_2 != "/")
	{
		str_msg = 'Invalid Date.  Wrong Separator, Not(/).'
		return (-3);	//Wrong kind of separator
	}

	if (!(int_month > 0 && int_month < 13))
	{
		str_msg = 'Invalid Month.';
		return (-4);	//Not a valid month
	}
	if (!(int_year > 0 && int_year < 3000) || isNaN(int_year))
	{
		str_msg = 'Invalid Year.';
		return (-5);	//Not a valid year
	}

	//If day less than zero or greater than 31 don't mess with checking for specific month
	if (!(int_day > 0 && int_day < 32) || isNaN(int_day))
	{
		str_msg = 'Invalid Day.';
		return (-6);	//Not a valid day
	}

	//Check valid day for respective month including leap year case
	if (validateDay(int_day, int_month, int_year) == false)
	{
		str_msg = 'Invalid Month.';
		return (-7);	//Not a valid day
	}
	//Valid Date
	return str_input;	//Success
	}	
}

function validateDay(str_day, int_month, str_year)
{
	//Array for valid month lengths (i.e Jan is month 1 and has 31 days so the index 1
	//of int_last_day_array array is 31) index[0] of array holds the leap year value
	int_last_day_array = new Array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	bln_leap_year = false;

	//check for leap year.  Any year divisible by 4 unless divisible by 100, and not divisible by 400
	if (str_year % 4 == 0)
	{
		bln_leap_year = true;
		if (str_year % 100 == 0)
		{
			bln_leap_year = false;
			if (str_year % 400 != 0)
			{
				bln_leap_year = true;
			}
		}
	}

	//If leap year is true, change int_last_day_array so int_last_day_array[2] = 29
	if (bln_leap_year == true)
	{
		int_last_day_array[2] = 29;
	}

	//Check for max Day of given month
	if (str_day > int_last_day_array[int_month])
	{
		return false;
	}

	return true;	//Day is valid.
}

function isNotFutureDate (str_input) {
	today = new Date();
	today = today.getTime();
	if (str_input.length == 7) {
		//Case where date is MM/yyyy
		date_input = Date.parse(str_input.substring(0,3) + '01/' + str_input.substring(3,7));
	}
	if (str_input.length == 10) {
		date_input = Date.parse(str_input);
	}
	if ((today - date_input) < 0) {
		return false;
	}
	return true;
}

function isInteger(int_input)
{
	int_flag = false; //set to 1 for number, leave 0 if not
	if(int_input.length > 0) {
		for(x = 0;x < int_input.length; x++)
		{
			chr_value = int_input.charAt(x);
			for(y = 0; y < 10; y++)  //Loop through all digits 0 - 9
			{
				if(chr_value == (y + ''))  //if this character is a digit, set the flag to 1
				{
					int_flag = true;
				}
			}
			if(int_flag == false)  	//if the character was not a number, the flag will be 0.
			{					//if the flag is 0, return false w/o checking the rest of the string.
				return false; //str_msg;
			}
			int_flag = false;  //reset for next digit
		}
		return true;  //valid int
	}
	else {
		return true;
	}


}

function isTelephone(strInput) {

	if( strInput == "" ) return "";

	strOutput="";

	for ( i=0; i < strInput.length; i++) {
		x = strInput.charAt(i);
		if( '0' <= x && x <= '9' )
			strOutput += x;
		else if( x != "(" && x != ")" && x != "-" && x != " " ) {
			return(-1)
		}
	}

	if(strOutput.length == 7)
		return(-2);
	else if(strOutput.length != 10)
		return(-3);
	else
		return(strOutput);  // valid phone number
}

function isSSN(str_input) {
	if(str_input == "") {
		return true;
	}
	var digit_flag; //set to true if a digit
	temp_string = new String;

	for (i=0; i < str_input.length; i++) {
		chr_value = str_input.charAt(i);
		digit_flag = false;
		for(y = 0; y < 10; y++)  //Loop through all digits 0 - 9
		{
			if(chr_value == (y + ''))
			{
				digit_flag = true;
				continue;
			}
		}

		if(digit_flag == false && chr_value != "-")
		{
			return false;  //not a digit or separator
		}

		if(digit_flag == true) {
			temp_string += chr_value;
		}
	}
	if(temp_string.length != 9) {
		return false;
	}
	return true;  //valid SSN
}

function isZip(str_input) {
	if(str_input == "") {
		return true;
	}
	var digit_flag; //set to true if a digit
	temp_string = new String;

	for (i=0; i < str_input.length; i++) {
		chr_value = str_input.charAt(i);
		digit_flag = false;
		for(y = 0; y < 10; y++)  //Loop through all digits 0 - 9
		{
			if(chr_value == (y + ''))
			{
				digit_flag = true;
				continue;
			}
		}

		if(digit_flag == false && chr_value != "-")
		{
			alert("Invalid Zip Code:e.g.,98006 or 980068393");
			return false;  //not a digit or separator
		}

		if(digit_flag == true) {
			temp_string += chr_value;
		}
	}
	if(temp_string.length != 5 && temp_string.length !=9) {
		alert("Invalid Zip Code:e.g.,98006 or 980068393");
		return false;
	}
	return true;  //valid Zip Code
}

function isState(str_input) {
//alert("isState = " + str_input);
	if(str_input == "") {
		return true;
	}
	str_valid_state_array = new Array('al','ak','az','ar','ca','co','ct','de','dc','fl','ga','hi','id','il','in','ia','ks','ky','la','me','md','ma','mi','mn','ms','mo','mt', 'ne', 'nv', 'nh', 'nj', 'nm', 'ny', 'nc', 'nd', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'vt', 'va', 'wa', 'dc', 'wv', 'wi', 'wy', 'n\a', 'fc');
	bln_valid_state = false;
	str_input = str_input.toLowerCase();
	for(int_index = 0; int_index < str_valid_state_array.length; int_index++)
	{
		if(str_input == str_valid_state_array[int_index])  //if this char is in array flag to true
		{
			bln_valid_state = true;
			break;
		}
	}
	return bln_valid_state;
}

function isASCIIChar(str_input)
{
	//Array to hold valid ascii values for upper and lower case a - z.
	str_valid_chr_array = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," ", "-", "'");

	//index of ascii values for upper case to make sure currenct char is alpha only
	var int_index;

	//bln_valid_chr is a flag to set to true if char is found in array of valid char
	bln_valid_chr = false;

	/*Loop through all char a - z both upper and lower case in Array.
	*Compare lowercase of str_input to each value in array and set flag to true
	*if char found in array.
	*/
	//convert str_input to lower case string
	str_input = str_input.toLowerCase();
	for(i = 0; i < str_input.length; i++) {
		for(int_index = 0; int_index < str_valid_chr_array.length; int_index++)
		{
			bln_valid_chr = false;
			if(str_input.charAt(i) == str_valid_chr_array[int_index])  //if this char is in array flag to true
			{
				bln_valid_chr = true;
				break;
			}
		}
		if (bln_valid_chr == false) {
		return false;
		}
	}
	return true;
}

function getTodayMmDdYyyy() {
	var aDate = new Date();
	var thisMonth = parseInt(parseFloat(aDate.getMonth())) + 1;
	var thisDay = parseInt(parseFloat(aDate.getDate()));
	var today;
	if (thisDay < 10) { thisDay = "0" + thisDay; }
	if (thisMonth < 10) { thisMonth = "0" + thisMonth; }
	today = thisMonth + "/" + thisDay + "/" + getFullYear(aDate);
	return today;
}

function getFullYear(year) {
	var fullYear = year.getYear();
	if (fullYear < 1000) { fullYear += 1900;}
	return fullYear;
}

function getNumOfDays(startDate, endDate) {
	elapse = Date.parse(endDate) - Date.parse(startDate);
	theNumOfDays = Math.round(elapse / ( 86400000 )); //  86400000 = 24 * 60 * 60 * 1000
	return theNumOfDays;
}

function firstDateIsGreater(date1, date2) {
	if (date1 != "" && date2 != "") {
		if ( (Date.parse(date1) - Date.parse(date2)) > 0 ) {
			return true;
		}
		else
			return false;
	}
}

function isUsername(str_input) {

	for (i=0; i < str_input.length; i++) {
		ch = str_input.charAt(i);
		if (((ch < "a" || "z" < ch) && (ch < "A" || "Z" < ch)) && (ch < '0' || ch > '9') && (ch != "_") && (ch != " ") && (ch != "'") && (ch != "."))
		{
		    //alert('You have entered invalid characters in your username.');
		    return false;
		    i = str_input.length;
		}
  }

	/*
	if (i < 4 || i > 15)	{
		alert('Username should be between 4 and 15 characters length.');
		return false;
	}
  */
	return true;
}

function isEmail(strInput) {

	if( strInput == "" ) return "";

	strInput = strInput.toLowerCase();

	for( at=0,dot=0,i=0; i < strInput.length; i++ ) {
		x = strInput.charAt(i);

		if(  ('a' <= x && x <= 'z')  ||  ('0' <= x && x <= '9')  ||  x=='_'  ||  x=='-'  )
			continue;
		else if( x == "@" ) {
			if( ++at != 1 )
				return(-1);
		}
		else if( x == "." ) {
			if( at == 1 )
				dot++;
		}
		else {
			return(-1);
		}

	}

	if( at==0 || dot==0 )
		return(-2);
	else
		return(0);	// valid phone number
}
