//=========================================================================================
//=========================================================================================
//=========================================================================================
//=========================================================================================
//=========================================================================================
//=========================================================================================
//  This js file contains the following functions:
//	1) Trim
//		Trims spaces from both sides of a  string 
//	   syntax example:  field.value = Trim(field.value);
//
//	2) RTrim
//		Trims spaces from the right side of a string 
//	   syntax example:  field.value = RTrim(field.value);
//
//	3) LTrim
//		Trims spaces from the Left side of a string 
//	   syntax example:  field.value = LTrim(field.value);
//
//	4) isEmpty
//		Tests to see if a string value is null or ''
//	   syntax example:  if (isEmpty(field.value) == true)
//
//	5) isNumber
//		Tests to see if a string value could be cast as a number
//	   syntax example:  if (isNumber(field.value) == true)
//
//	6) isInteger
//		Tests to see if a string value is a valid integer value
//	   syntax example:  if (isInteger(field.value) == true)
//
//	7) isPosInteger
//		Tests to see if a string value is a valid integer value
//			and also that it is greater than 0
//	   syntax example:  if (isPosInteger(field.value) == true)
//
//	8) IsLeapYear
//		Tests to see if a string value (Year) is a valid leap year
//	   syntax example:  if (IsLeapYear(field.value) == true)
//		IsLeapYear(yyyy)
//
//	9) isDate
//		Tests to see if a FIELD's value contains a valid date.
//		if it doesn't, this function automatically 'alerts' the user'
//		and moves to the field in question and highlights it's value.
//		if it does, it formats the date using our date formatting standard.
//	   syntax example:  if (isDate(field) == true)
//
// 	10) isStringADate
//		Tests to see if a string contains a valid date.
//	   syntax example:  if (isStringADate(field.value) == true)
//
//	11) DateDiff
//		Returns the difference between two dates in respect to a 
//		specified unit of measure.
//		Valid units of measure are:
//			DAYS
//			WEEKS
//			MONTHS
//			YEARS
//	   syntax example:  if (DateDiff('DAYS','01/02/1999','05/02/2000') > 30)
//	
//	12) replaceString
//		Returns a string with a Pattern Replaced with a specified string 
//	   syntax example:  OutputStr = replaceString(InputStr,"-","/")
//
//	13) CompareDates(BeginDate, Operation, EndDate)
//		Returns a boolean indicating if one string date how
//		one string date compares with another.
//	   syntax example:  if (CompareDates('01/01/2000', '>=', '01/05/2000') == true)
//		valid operations are:
//			>
//			>=
//			<
//			<=
//			= or ==
//			<> or !=
//			
//	14) ProperCase
//		Returns a string that is formatted using a Proper case formatting algorithm
//	   syntax example:  OutputStr = ProperCase(InputStr)
//	
//	15) isTime(TimeField)
//		Pass in a text field object and it validates the data to ensure that
//		valid time data exists in the field.
//
//	16) FormatTime(strDateTime)
//		Given a valid time string, this will format the time into a hh:mm AM/PM
//		format
//
//	17) CheckTime(strTime)
//		Given a string representing a time value, this will return true or 
//		false indicating whether or not the value is a valid time value.
//
//=========================================================================================
//=========================================================================================
//=========================================================================================
//=========================================================================================
//=========================================================================================
//=========================================================================================

function DateValidation(FieldToProcess)
{
	return isDate(FieldToProcess)
}

function TimeValidation(FieldToProcess)
{
	return isTime(FieldToProcess)
}

function IntegerValidation(FieldToProcess)
{
	if (isInteger(FieldToProcess.value) == false)
	{
		alert('Value must be an integer.');
		FieldToProcess.focus();
		FieldToProcess.select();
		return false;
	}
	else
	{
		return true;
	}
}

function NumberValidation(FieldToProcess)
{
	if (isNumber(FieldToProcess.value) == false)
	{
		alert('Value must be a number.');
		FieldToProcess.focus();
		FieldToProcess.select();
		return false;
	}
	else
	{
		return true;
	}
}




//***********************************************
// Trims spaces off of a string
//***********************************************
function Trim(inputStr) {
	return LTrim(RTrim(inputStr));
}

//***********************************************
// Trims spaces off of the right side of a string
//***********************************************
function RTrim(inputStr) {
	var MyInputStr	=  inputStr;
	var strTemp	= '';
	var Length = MyInputStr.length;
	var blnContinue = true;
	while (blnContinue == true)
	{
		if (Length > 0)
		{
			if (MyInputStr.substring(Length - 1,Length) == ' ') 
			{
				if (Length != 1)
				{
					strTemp = MyInputStr.substring(0,Length - 1);
					MyInputStr = strTemp;
					Length = MyInputStr.length;
				}
				else
				{
				 	MyInputStr = '';
					blnContinue = false;	
				}
			}
			else
			{
				blnContinue = false;
			}
		}
		else
		{
			blnContinue = false;
		}
	}
	return  MyInputStr
}

//***********************************************
// Trims spaces off of the right side of a string
//***********************************************
function LTrim(inputStr) {
	var MyInputStr	=  inputStr;
	var strTemp	= '';
	var Length = MyInputStr.length;
	var blnContinue = true;
	while (blnContinue == true)
	{
		if (Length != 0)
		{
			if (MyInputStr.substring(0,1) == ' ') 
			{
				if (Length != 1)
				{
					strTemp = MyInputStr.substring(1,Length);
					MyInputStr = strTemp;
					Length = MyInputStr.length;
				}
				else
				{
					MyInputStr = '';
					blnContinue = false;
				}
			}
			else
			{
				blnContinue = false;
			}
		}
		else
		{
			blnContinue = false;
		}
	}
	return  MyInputStr;
}


//***********************************************
// Checks to see if a string is empty
//***********************************************
function isEmpty(inputStr) {
	if (inputStr == null || Trim(inputStr) == "") {
		return true
	}
	return false
}

//***********************************************
// Checks to see if a value is a Number
//***********************************************
function isNumber(inputVal) {
	oneDecimal = false
	inputStr = inputVal.toString()
	for (var i = 0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i)
		if (i == 0 && oneChar == "-") {
			continue
		}
		if (oneChar == "." && !oneDecimal) {
			oneDecimal = true
			continue
		}
		if (oneChar < "0" || oneChar > "9") {
			return false
		}
	}
	return true
}



//***********************************************
// Checks to see if a value is an Integer
//***********************************************
function isInteger(inputVal) {
	var inputStr = new String();
	inputStr = inputVal.toString()
	for (var i = 0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i)
		if (i == 0 && oneChar == "-") {
			continue
		}
		if (oneChar < "0" || oneChar > "9") {
			return false
		}
	}
	return true
}


//***********************************************
// Checks to see if an Integer is positive
//***********************************************
function isPosInteger(inputVal) {
	inputStr = inputVal.toString()
	for (var i = 0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i)
		if (oneChar < "0" || oneChar > "9") {
			return false
		}
	}
	return true
}

//*******************************************************************
// Returns the Number of Days in the Month of the Date Supplied
//*******************************************************************
function GetDaysInMonth(vDate) {
	var varCurrentMonth;
	
	varCurrentMonth = vDate.getMonth();
	
	if (	varCurrentMonth  == 4 || 
		varCurrentMonth  == 6 || 
		varCurrentMonth  == 9 || 
		varCurrentMonth  == 11
	   )
	{
		return 30
	}
	if (	varCurrentMonth  == 2
	   )
	{
		if (IsLeapYear(vDate.getYear()) == true)
		{
			return 29
		}
		else
		{
			return 28
		}
	}
	else
	{
		return 31
	}
	
}


//***********************************************
// Checks to the length of the Month field compared
//***********************************************
function checkMonthLength(mm,dd) {
	var months = new Array("","January","February","March","April","May","June","July","August","September","October","November","December")
	if ((mm == 4 || mm == 6 || mm == 9 || mm == 11) && dd > 30) {
		alert(months[mm] + " has only 30 days.")
		return false
	} else if (dd > 31) {
		alert(months[mm] + " has only 31 days.")
		return false
	}
	return true
}

//***********************************************
// Checks for a Leap Year in february
//***********************************************
function checkLeapMonth(mm,dd,yyyy) {
	
	if ((IsLeapYear(yyyy) == false) && (dd > 28)) {
		alert("February of " + yyyy + " has only 28 days.")
		return false
	} else if (dd > 29) {
		alert("February of " + yyyy + " has only 29 days.")
		return false
	}
	return true
}


//***********************************************
// Checks for a Leap Year
//***********************************************
function IsLeapYear(yyyy)
{
	if (yyyy % 4 == 0) 
	{
		if (yyyy % 100 == 0) 
		{
			if (yyyy % 400 == 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
			return true;
		}
	}
	else
	{
		return false;
	}
}

function FormatTime(strDateTime)
{
	var strReturn = new String;


		var myDate = new Date(Date.parse('01/01/1999 ' + strDateTime))
		
		if (isNaN(myDate) == true) 
		{
			strReturn = strDateTime ;			
			return strReturn;
		}

		strHours = myDate.getHours()

		if (strHours >= 12)
		{
			strHours = strHours - 12
			strMeridian = "PM"
		}
		else
		{
			strMeridian = "AM"
		}
		
		if (strHours == 0)
		{
			strHours = 12
		}

		if (strHours < 10)
		{
			strReturn = "0" + strHours
		}
		else
		{
			strReturn = "" + strHours
		}


		
		strMinutes = myDate.getMinutes()

		if (strMinutes < 10) 
		{
			strReturn = strReturn + ':0' + strMinutes
		}
		else
		{
			strReturn = strReturn + ':' + strMinutes
		}
		
		strReturn = strReturn + ' ' + strMeridian		

	return strReturn;
}


function CheckTime(strTime)
{
	var blnReturn = false
	var myDate = new Date(Date.parse('01/01/1999 ' + strTime));

	if (isNaN(myDate) == true)
	{
		blnReturn = false;
	}
	else
	{
		blnReturn = true;
	}
	return blnReturn;
}
		



//***********************************************
//	Validates a Time field
//***********************************************
function isTime(TimeField)
{
		var strTemp	= new String;

		TimeField.value = Trim(TimeField.value);
		TimeField.value = TimeField.value.toUpperCase();
		
		if (isEmpty(TimeField.value) == false)
		{

			var blnIsDate	= false;
			var strInputStr	= TimeField.value;
	
			if (CheckTime(strInputStr) == true) 
			{
				TimeField.value = FormatTime(strInputStr);
				return true;
			}
			else
			{

				if ((strInputStr.length <=5) && (strInputStr.indexOf(":") < 0))
				{
					if (strInputStr.length == 5)
					{
						strTemp = Trim(strInputStr.substring(0,2)) + ":00" + Trim(strInputStr.substring(2,5))
					}
					else
					{
						if (strInputStr.length == 4)
						{
							if (strInputStr.indexOf("M") == strInputStr.length - 1)
							{
								strTemp = Trim(strInputStr.substring(0,2)) + ":00" + strInputStr.substring(2,4)
							}
							else
							{
								if (strInputStr.substring(0,2) == "24")
								{
									strTemp = "00:" + strInputStr.substring(2, 4)
								}
								else
								{
									strTemp =   strInputStr.substring(0,2) + ":" + strInputStr.substring(2, 4)
								}
							}
						}
						else
						{
							if (strInputStr.length == 3)
							{
								strTemp = strInputStr.substring(0,1) + ":" + strInputStr.substring(1,3)
							}
							else
							{
								strTemp = strInputStr + ":00"
							}
						}
					}
					
					if (CheckTime(strTemp) == true) 
					{
						TimeField.value = FormatTime(strTemp);
						return true;
					}
					else
					{
						alert('"' + TimeField.value + '" is an Invalid Time Format.');
						TimeField.focus();
						TimeField.select();
						return false;
					}
				}
				else
				{
					alert('"' + TimeField.value + '" is an Invalid Time Format.');
					TimeField.focus();
					TimeField.select();
					return false;
				}
			}
		}
		else
		{
			return true
		}

}



// date field validation (called by other validation functions that specify minYear/maxYear)
function isDate(DateField) {
	var inputStr = DateField.value
	
	if (isEmpty(inputStr) == true)
	{
		return true;
	}
	// convert hyphen delimiters to slashes
	while (inputStr.indexOf("-") != -1) {
		inputStr = replaceString(inputStr,"-","/")
	}
	var delim1 = inputStr.indexOf("/")
	var delim2 = inputStr.lastIndexOf("/")
	if (delim1 != -1 && delim1 == delim2) {
		// there is only one delimiter in the string
		alert("The date entry is not in an acceptable format.\n\nYou can enter dates in the following formats: mmddyyyy, mm/dd/yyyy, or mm-dd-yyyy.  (If the month or date data is not available, enter \'01\' in the appropriate location.)")
		DateField.focus()
		DateField.select()
		return false
	}
	if (delim1 != -1) {
		// there are delimiters; extract component values
		var mm = parseInt(inputStr.substring(0,delim1),10)
		var dd = parseInt(inputStr.substring(delim1 + 1,delim2),10)
		var yyyy = parseInt(inputStr.substring(delim2 + 1, inputStr.length),10)
	} else {
		// there are no delimiters; extract component values
		var mm = parseInt(inputStr.substring(0,2),10)
		var dd = parseInt(inputStr.substring(2,4),10)
		var yyyy = parseInt(inputStr.substring(4,inputStr.length),10)
	}
	if (isNaN(mm) || isNaN(dd) || isNaN(yyyy)) {
		// there is a non-numeric character in one of the component values
		alert("The date entry is not in an acceptable format.\n\nYou can enter dates in the following formats: mmddyyyy, mm/dd/yyyy, or mm-dd-yyyy.")
		DateField.focus()
		DateField.select()
		return false
	}
	if (mm < 1 || mm > 12) {
		// month value is not 1 thru 12
		alert("Months must be entered between the range of 01 (January) and 12 (December).")
		DateField.focus()
		DateField.select()
		return false
	}
	if (dd < 1 || dd > 31) {
		// date value is not 1 thru 31
		alert("Days must be entered between the range of 01 and a maximum of 31 (depending on the month and year).")
		DateField.focus()
		DateField.select()
		return false
	}

	// validate year, allowing for checks between year ranges
	// passed as parameters from other validation functions
	if (yyyy < 100) {
		// entered value is two digits, which we allow for 1950-2049
		if (yyyy >= 50) {
			yyyy += 1900
		} else {
			yyyy += 2000	
		}
	}

	if (!checkMonthLength(mm,dd)) {
		DateField.focus()
		DateField.select()
		return false
	}
	if (mm == 2) {
		if (!checkLeapMonth(mm,dd,yyyy)) {
			DateField.focus()
			DateField.select()
			return false
		}
	}

	DateField.value = monthDayFormat(mm) + "/" + monthDayFormat(dd) + "/" + yyyy
	return true
}


function isStringADate(DateField) {
	var inputStr = DateField
	// convert hyphen delimiters to slashes
	while (inputStr.indexOf("-") != -1) {
		inputStr = replaceString(inputStr,"-","/")
	}
	var delim1 = inputStr.indexOf("/")
	var delim2 = inputStr.lastIndexOf("/")
	if (delim1 != -1 && delim1 == delim2) {
		// there is only one delimiter in the string
		return false
	}
	if (delim1 != -1) {
		// there are delimiters; extract component values
		var mm = parseInt(inputStr.substring(0,delim1),10)
		var dd = parseInt(inputStr.substring(delim1 + 1,delim2),10)
		var yyyy = parseInt(inputStr.substring(delim2 + 1, inputStr.length),10)
	} else {
		// there are no delimiters; extract component values
		var mm = parseInt(inputStr.substring(0,2),10)
		var dd = parseInt(inputStr.substring(2,4),10)
		var yyyy = parseInt(inputStr.substring(4,inputStr.length),10)
	}
	if (isNaN(mm) || isNaN(dd) || isNaN(yyyy)) {
		// there is a non-numeric character in one of the component values
		return false
	}
	if (mm < 1 || mm > 12) {
		// month value is not 1 thru 12
		return false
	}
	if (dd < 1 || dd > 31) {
		// date value is not 1 thru 31
		return false
	}

	// validate year, allowing for checks between year ranges
	// passed as parameters from other validation functions
	if (yyyy < 100) {
		// entered value is two digits, which we allow for 1950-2049
		if (yyyy >= 50) {
			yyyy += 1900
		} else {
			yyyy += 2000	
		}
	}

	if (!checkMonthLength(mm,dd)) {
		return false
	}
	if (mm == 2) {
		if (!checkLeapMonth(mm,dd,yyyy)) {
			return false
		}
	}
	DateField = monthDayFormat(mm) + "/" + monthDayFormat(dd) + "/" + yyyy
	return true
}


function monthDayFormat(NumberToFormat)
{
	var strText;
	strText = NumberToFormat.toString();


	if (strText.length < 2) 
	{
		strText = '0' + strText;
	}
	return strText;
}




//***********************************************************************
//DAYS
//WEEKS
//MONTHS
//YEARS
//***********************************************************************

function DateDiff(UnitOfMeasure, BeginDate, EndDate)
{
	var lngResult = null;

	UnitOfMeasure = UnitOfMeasure.toUpperCase();
	

	if (isStringADate(BeginDate) && isStringADate(EndDate))
	{
		var dtmBeginDate = new Date(BeginDate);
		
		var dtmEndDate = new Date(EndDate);
		
		var lngBeginMS = dtmBeginDate.getTime();
		var lngEndMS = dtmEndDate.getTime();
		var lngDiffenceInMS = lngEndMS - lngBeginMS;
		var lngMulitplicationFactor = 0;

		if (UnitOfMeasure == 'DAYS')
		{
			lngMulitplicationFactor = 1000 * 60 * 60 * 24;  // 1 Day in Milliseconds
			var lngNbrResult = lngDiffenceInMS / lngMulitplicationFactor;
			lngResult = Math.floor(lngNbrResult);
		}
		else if (UnitOfMeasure == 'WEEKS')
		{
			lngMulitplicationFactor = 1000 * 60 * 60 * 24 * 7;  // 1 Day in Milliseconds
			var lngNbrResult = lngDiffenceInMS / lngMulitplicationFactor;
			lngResult = Math.floor(lngNbrResult);
		}
		else if (UnitOfMeasure == 'MONTHS')
		{
			var lngBeginMonth = dtmBeginDate.getMonth();
			var lngEndMonth = dtmEndDate.getMonth();
			var lngBeginYear = dtmBeginDate.getYear();
			var lngEndYear = dtmEndDate.getYear();
			
			lngBeginYear = ConvertYearTo4Digits(lngBeginYear);
			lngEndYear = ConvertYearTo4Digits(lngEndYear);

			lngResult = ((lngEndYear - lngBeginYear) * 12) + (lngEndMonth - lngBeginMonth);
		}
		else if (UnitOfMeasure == 'YEARS')
		{
			var lngBeginYear = dtmBeginDate.getYear();
			var lngEndYear = dtmEndDate.getYear();
			
			lngBeginYear = ConvertYearTo4Digits(lngBeginYear);
			lngEndYear = ConvertYearTo4Digits(lngEndYear);

			lngResult = lngEndYear - lngBeginYear;
		}

	}
	return lngResult;
}

function ConvertYearTo4Digits(yyyy)
{
	if (yyyy < 100)
	{
		if (yyyy < 50)
		{
			return yyyy + 2000;
		}
		else
		{
			return yyyy + 1900;
		}
	}
	return yyyy;
}

function replaceString(inputStr,SearchPattern,ReplaceWith)
{
	return inputStr.replace(SearchPattern,ReplaceWith);
}

function CompareDates(BeginDate, Operation, EndDate)
{
	var blnReturn = false;

	if ((isStringADate(BeginDate) == true) && (isStringADate(EndDate) == true))
	{
		var lngDifference = DateDiff('DAYS',BeginDate,EndDate);

		Operation = Operation.toUpperCase();
		
		if (Operation == '>')
		{
			if (lngDifference < 0)
			{
				blnReturn = true;
			}
		}
		else if (Operation == '>=')
		{
			if (lngDifference <= 0)
			{
				blnReturn = true;
			}
		}
		else if (Operation == '<=')
		{
			if (lngDifference >= 0)
			{
				blnReturn = true;
			}
		}
		else if (Operation == '<')
		{
			if (lngDifference > 0)
			{
				blnReturn = true;
			}
		}
		else if ((Operation == '=') || (Operation == '=='))
		{
			if (lngDifference == 0)
			{
				blnReturn = true;
			}
		}
		else if ((Operation == '!=') || (Operation == '<>'))
		{
			if (lngDifference != 0)
			{
				blnReturn = true;
			}
		}
	}

	return blnReturn
}

function ProperCase(InputStr)
{
	var strHolder = '';
  	var strTemp = Trim(InputStr);
	var strArray = strTemp.split(' ');

	lngUpperBound = strArray.length;
	strTemp = '';
	for (var lngCounter = 0; lngCounter < lngUpperBound; lngCounter++)
	{
		strTemp = strArray[lngCounter].toUpperCase();
		strInnerArray = strTemp.split('-');
		lngInnerUpperBound = strInnerArray.length;
		
		for (var lngInnerCounter = 0; lngInnerCounter < lngInnerUpperBound; lngInnerCounter++)
		{
			strTemp = strInnerArray[lngInnerCounter].toUpperCase();
			strInnerArray2 = strTemp.split("/");
			lngInnerUpperBound2 = strInnerArray2.length;

			for (var lngInnerCounter2 = 0; lngInnerCounter2 < lngInnerUpperBound2; lngInnerCounter2++)
			{
				strTemp = strInnerArray2[lngInnerCounter2].toUpperCase();
			        strInnerArray3 = strTemp.split("\\");
        			lngInnerUpperBound3 = strInnerArray3.length;
				
				for (var lngInnerCounter3 = 0; lngInnerCounter3 < lngInnerUpperBound3; lngInnerCounter3++)
				{
					strTemp = strInnerArray3[lngInnerCounter3].toUpperCase();
					
					lngLength = strTemp.length;
					
					if (
						(strTemp == "I") 	||
						(strTemp == "II") 	||
						(strTemp == "III") 	||
						(strTemp == "IV") 	||
						(strTemp == "V") 	||
						(strTemp == "VI") 	||
						(strTemp == "VII") 	||
						(strTemp == "VIII") 	||
						(strTemp == "IX") 	||
						(strTemp == "X") 	||
						(strTemp == "JR") 	||
						(strTemp == "JR.") 	||
						(strTemp == "SR") 	||
						(strTemp == "SR.")
					)
					{
						
					}
					else
					{
						if (lngLength >= 2)
						{
							strFirstTwo = strTemp.substring(0,2);
							if ((strFirstTwo == 'MC') || (strFirstTwo == 'O\''))
							{
								strTemp = strTemp.toLowerCase();
										
								if (lngLength >= 4)
								{
									strTemp =  	strTemp.substring(0,1).toUpperCase() + 
											strTemp.substring(1,2) + 
											strTemp.substring(2,3).toUpperCase() + 
											strTemp.substring(3);
									
								}
								else
								{
									if (lngLength == 3)
									{
							                    strTemp = 	strTemp.substring(0,1).toUpperCase() +
											strTemp.substring(1,2) +
											strTemp.substring(2).toUpperCase();
									}
									else
									{
										strTemp = strTemp.substring(0,1).toUpperCase() + strTemp.substring(1);
									}
								}
							}
							else
							{
								strTemp = strTemp.toLowerCase();
                						strTemp = strTemp.substring(0,1).toUpperCase() + strTemp.substring(1);
							}
						}
						else
						{
							strTemp = strTemp.toUpperCase();
						}
					}
				
					if ((lngInnerUpperBound3 > 0) && (lngInnerCounter3 != lngInnerUpperBound3 - 1))
					{
						strTemp = strTemp + "\\";
					}
					if ((lngInnerUpperBound2 > 0) && (lngInnerCounter2 != lngInnerUpperBound2 - 1))
					{
						strTemp = strTemp + "/";
					}
					if ((lngInnerUpperBound > 0) && (lngInnerCounter != lngInnerUpperBound -1 ))
					{
						strTemp = strTemp + "-";
					}
          				if ((lngInnerUpperBound == lngInnerCounter + 1) && (lngInnerUpperBound2 == lngInnerCounter2 + 1) && (lngInnerUpperBound3 == lngInnerCounter3 + 1))
					{
						strHolder = strHolder + strTemp + " ";
					}
					else
					{
						strHolder = strHolder + strTemp;
					}

				} 
			}
		}
	}
  	strHolder = Trim(strHolder);
	return strHolder;
}
