var whitespace = " \t\n\r";

function jstrim(s) { return s.replace(/^\s+|\s+$/g, "") }

/*function CheckEmail(strEmail) 
{
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(strEmail))
	{
		return true;
	}
	return false;
}*/
function CheckEmail (emailStr) {
//var strMsg="Email address is invalid. Please enter a valid email address in the format 'someone@somewhere.com'";
/* 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 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 an atom (basically a series of
   non-special characters.) */
var atom=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 coarse 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 (strMsg);
	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("The username doesn't seem to be valid.")
    //alert (strMsg);
    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!")
	       //alert (strMsg);
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	//alert("The domain name doesn't seem to be valid.")
	//alert (strMsg);
    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), and that there's a hostname preceding 
   the domain or country. */

/* 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 ) {
   // the address must end in more than two letter word.
   //alert("The address must end in a three-letter domain, or two letter country.")
   //alert (strMsg);
   return false
}

//now we try to check if the ending part matchs any one of "edu,org,com,net" for now, 
//the list could be added more later. or, 
//if we do not need to check the actual value of the ending part, we do not need the 
//following block of code
//do not need to check it right now.
/*if ((domArr[domArr.length-1].match(/edu/i)==null)&&
	  (domArr[domArr.length-1].match(/org/i)==null)&&
	  (domArr[domArr.length-1].match(/com/i)==null)&&
	  (domArr[domArr.length-1].match(/net/i))==null)
		return false;*/

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   //alert(errStr)
   //alert (strMsg);
   return false
}

// If we've gotten this far, everything's valid!
return true;
}

function SelectField(objField)
{	//highlignt and set focus for selected field
	objField.select();
	objField.focus();
	return true;
}


function TrimSpace(strValue)
{
	while (strValue.substr(strValue.length-1) == " ") 
	{
		strValue = strValue.substring(0, strValue.length-1);
	}
	return strValue;
}

function IsInteger (s)

{   var i;

    if (IsWhiteSpace(s)==true) 
    {
	return false;
    }

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (IsDigit(c)==false) return false;
    }

    // All characters are numbers.
    return true;
}

function IsDecimal (s)

{   var i;

    if (IsWhiteSpace(s)==true) 
    {
	return false;
    }

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

		if (c!='.'){
			if (IsDigit(c)==false) return false;}
    }

    // All characters are numbers.
    return true;
}

function IsDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}


// Returns true if string s is empty or 
// whitespace characters only.

function IsWhiteSpace (s)

{   var i;
	
    // Is s empty?
    if (s=='') return true;
	if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

function ForceNumeric()
{
	if ((window.event.keyCode > 57) || (window.event.keyCode < 48))
	{		
		alert ("input must be numeric.");
		window.event.keyCode = 0;
		return false;
	}
}

function IsZipCode(strInput)
{
	var strZip=new String(strInput);
	if (IsWhiteSpace(strZip)==true) 
	{
		return false;
	}
	if (((strZip.length==5) && (IsInteger(strZip)==true))
		||((strZip.length==10)&&(IsInteger(strZip.substring(0,4))==true) &&
		(IsInteger(strZip.substring(6,9))==true) && (strZip.charAt(5)=="-")))
		return true;
	else{
		return false;}
}

function RemoveWhiteSpace(item)
{
  var tmp = "";
  var item_length = item.length;
  var item_length_minus_1 = item.length - 1;
  for (index = 0; index < item_length; index++)
  {
    if (item.charAt(index) != ' ')
    {
      tmp += item.charAt(index);
    }
    else
    {
      if (tmp.length > 0)
      {
        if (item.charAt(index+1) != ' ' && index != item_length_minus_1)
        {
          tmp += item.charAt(index);
        }
      }
    }
  }
  item = tmp;
  return item;
}

function IsDate(strDate) {	
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intDay;
	var intMonth;
	var intYear;		
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var strNewDate;	
	var blnSeparated;	
	
	blnSeparated = 0;
	
	if (strDate.length < 1) {
		return false;
	}
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) 
	{
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) 
		{
			blnSeparated = 1;
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) 
			{				
				return false;
			}
			else 
			{
				strMonth = strDateArray[0]; //assume first part is month
				strDay = strDateArray[1];	//assume second part is day
				strYear = strDateArray[2];				
			}			
		}		
	}
	
	if (blnSeparated == 0)
		return false;
	
	if (strYear.length == 2) 
	{
		if (parseInt(strYear) > 50)
			strYear = '19' + strYear;
		else
			strYear = '20' + strYear;
	}
	
	//check to see if strMonth and strDay consists of numeric characters
	if (strMonth.match(/^\d+$/) == null)
		return false;
	if (strDay.match(/^\d+$/) == null)
		return false;
	if (strYear.match(/^\d+$/) == null)
		return false;
	
	intDay = parseInt(strDay, 10);
	//if (isNaN(intDay)) 
	//	return false;
	
	intMonth = parseInt(strMonth, 10);
	//if (isNaN(intMonth))	
	//	return false;		
	
	
	//check to see if user put day first
/*	if ((intDay <= 12) && (intMonth > 12))
	{
		var temp = intDay;
		intDay = intMonth;
		intMonth = temp;
	}
*/	
	intYear = parseInt(strYear, 10);
	//if (isNaN(intYear)) 
	//	return false;		
	
	if (intMonth>12 || intMonth<1) 
	{		
		return false;
	}
	
	//configure the new date string
	strNewDate = intMonth + "/" + intDay + "/" + intYear;
	
	
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intDay > 31 || intDay < 1)) 
	{		
		return false;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30 || intDay < 1)) 
	{		
		return false;
	}
	if (intMonth == 2) 
	{
		if (intDay < 1) 
		{			
			return false;
		}
		if (LeapYear(intYear) == true) 
		{
			if (intDay > 29) 
			{				
				return false;
			}
		}
		else 
		{
			if (intDay > 28) 
			{				
				return false;
			}
		}
	}
			
	return true;
}

function LeapYear(intYear) 
{
	if (intYear % 100 == 0) 
	{
		if (intYear % 400 == 0) 
			{ return true; }
	}
	else 
	{
		if ((intYear % 4) == 0) 
			{ return true; }
	}
	return false;
}

function IsTime(strTime)
	{	
		var varDate=new Date("1/1/2000")
		var iYear=varDate.getYear();
		var iMonth=varDate.getMonth();
		var iDate=varDate.getDate();
		
		var temp=new Date("1/1/2000" + ' ' + strTime)
		var m=temp.getMonth();		
		var d=temp.getDate();
		var y=temp.getYear();
		/*alert("iYear=" + iYear +";imonth=" + iMonth + ";iDate=" +iDate+";y=" + y + ";m=" + m + ";d=" + d); */
		if (iYear*1!=y*1||iMonth*1!=m*1||iDate*1!=d*1)
			return false;
		else
			return true;
			
	}

function FormatDateField(objField)
{
	if (IsWhiteSpace(objField.value)==false){
		var strDate = FormatDate(objField.value);
		objField.value=strDate;}
}

function FormatDate(strInput)
	{
		var strCheck=new String(strInput);
		if (((strCheck.length==6) || (strCheck.length==8)) && IsInteger(strInput))
		{	
			
			var strMonth=strCheck.substr(0,2);
			
			var strDay=strCheck.substr(2,2);
			if (strCheck.length==6)
			{
				var strYear=strCheck.substr(4,2);
				if (strYear>=20)
					{strYear='19' + strYear};
				else
					{var strYear='20' + strYear};
			}else
				var strYear=strCheck.substr(4,4);
			
			vartest = strMonth + "/" + strDay + "/" + strYear;			
			if (IsDate(vartest)==true){
				strCheck=strMonth + "/" + strDay + "/" + strYear;}
		}else{
			if (IsDate(strInput)==true)
			{
				var l=strCheck.length;
				if (strCheck.charAt(l-3)=="/")
					if (strCheck.substr(l-2,2)>=20)
						{strCheck=strCheck.substr(0,l-2) + '19' + strCheck.substr(l-2,2)};
					else
						{strCheck=strCheck.substr(0,l-2) + '20' + strCheck.substr(l-2,2)};
			}
		}
		return strCheck;
	}

function FormatTimeField(objField)
{
	if (IsWhiteSpace(objField.value)==false)
	{var strTime = FormatTime(objField.value);
	objField.value=strTime;} 
}
	
function FormatTime(strInput)
	{
		var strCheck=new String(strInput);
		if (((strCheck.length==3) || (strCheck.length==4)) && IsInteger(strInput)){ 
			if (strCheck.length==3){
				var strHour=strCheck.substr(0,1);
				var strMin=strCheck.substr(1,2);}
			else{	
				var strHour=strCheck.substr(0,2);
				var strMin=strCheck.substr(2,2);}
			
			if (strHour > 12){
				strHour = strHour - 12;
				strCheck=strHour + ":" + strMin + " PM";}
			else{
				strCheck=strHour + ":" + strMin + " AM";}}
		else{
		if (strCheck.length==4 && strCheck.substr(1,1)==":"){				
			var strHour=strCheck.substr(0,1);	
			var strMin=strCheck.substr(2,2);
			if (IsInteger(strHour) && IsInteger(strMin)){
				strCheck = strHour + ":" + strMin + " AM";}}
		else if (strCheck.length==5 && strCheck.substr(2,1)==":"){			
			var strHour=strCheck.substr(0,2);	
			var strMin=strCheck.substr(3,2);
			if (IsInteger(strHour) && IsInteger(strMin)){
				if (strHour > 12){
					strHour = strHour - 12;
					strCheck = strHour + ":" + strMin + " PM";}
				else {
				strCheck = strHour + ":" + strMin + " AM";}}}}
		if (IsTime(strCheck)==true)
			{return strCheck;}
		else
			{return strInput;}		
	}	

function FormatDOB(strInput)
	{
		var strCheck=new String(strInput);
		if (((strCheck.length==6) || (strCheck.length==8)) && IsInteger(strInput))
		{	
			
			var strMonth=strCheck.substr(0,2);
			
			var strDay=strCheck.substr(2,2);
			if (strCheck.length==6)
			{
				var strYear=strCheck.substr(4,2);
				strYear='19' + strYear;
			}else
				var strYear=strCheck.substr(4,4);
			
			strCheck=strMonth + "/" + strDay + "/" + strYear;
		}else{
			if (IsDate(strInput)==true)
			{
				var l=strCheck.length;
				if (strCheck.charAt(l-3)=="/")
					{strCheck=strCheck.substr(0,l-2) + '19' + strCheck.substr(l-2,2)};
			}
		}
		return strCheck;
	}
	
function IsCurrency (f)

{   	

	// http://javascript.internet.com/forms/iscurrency.html
	var nNum = 0;			// Total numbers for currency value.
	var nDollarSign = 0;	// Total times a dollar sign occurs.
	var nDecimal = 0;		// Total times a decimal point occurs.
	var nCommas = 0;		// Total times a comma occurs.
	var txtLen;				// Length of string passed.
	var sDollarVal;			// Assigned dollar amount with or without commas.
	var bComma;				
	var decPos;				// Assigned value of numbers or positions after decimal point.
	var nNumCount = 0;		// Total number between commas.
	var i;					// For forloop indexing.
	var x;					// Assigned each indivual character in string.    
	
	
	//alert(f);
	txtLen = f.length;
	//alert(txtLen);
	for(i = 0; i < txtLen; i++)
	{
		// Assign charater in substring to x.
		x = f.substr(i, 1);
		if(x == "$")
			nDollarSign = nDollarSign + 1; // Sum total times dollar sign occurs.
		else if(x == ".")
			nDecimal = nDecimal + 1; // Sum total times decimal point occurs.
		else if(x == ",")
			nCommas = nCommas + 1; // Sum total times comma occurs.
		else if(parseInt(x) >= 0 || parseInt(x) <= 9)
			nNum = nNum + 1; // If the character is a number sum total times a number occurs.
		else
		{
			// Error occurs if any other character value is in the string
			// other than the valid characters.
			alert("Co-pay amount is invalid.  \n\nPlease enter only: Dollar" +
				  " Signs, Commas, Decimal Points, and numbers between 0...9");
			return false;
		} // end else
	} // end for
	
	if(nDollarSign > 1)
	{
		alert("Co-pay amount is invalid. \n\nOnly one dollar sign is allowed.");
		return false;
	} // end if

	if(nDecimal > 1)
	{
		alert("Co-pay amount is invalid. \n\nOnly one decimal point is allowed.");
		return false;
	} // end if

	if(nDollarSign == 1)
	{
		// Make sure dollar sign in the first character in string
		// if there is a dollar sign present.
		if(f.indexOf("$") != 0)
		{
			alert("Co-pay amount is invalid. \n\nDollar sign is not in the correct position.");
			return false;
		} // end if
	}// end if	
	
	if(nDecimal == 1)
	{
		// Get the number of numbers after the decimal point in
		// the string if there is a decimal point present
		decPos = (txtLen - 1) - f.indexOf(".");

		// Floating point cannot be more then two.
		// Valid format after decimal point.
		/**********************************/
		/*   $#.##, $#.#, $.#, $#., $.##  */
		/**********************************/

		if(decPos > 2)
		{
			alert("Co-pay amount is invalid. \n\nOnly two digits are allowed after the decimal point.");			
			return false;
		} // end if
	} // end if	
	
	if(nCommas == 0)
	{
		// If no commas are present value is a valid US currency.
		return true;
	}

	else

	{
		// Get total number of dollar number(s), removing
		// floating point numbers or cents.
		nNum = nNum - decPos;

		// Determine if dollar sign is in string so to be 
		// removed.

		// After determining dollar sign, assign sDollarVal
		// numbers and comma(s)

		if(f.indexOf("$", 0) == 0)
			sDollarVal = f.substr(1, (nNum + nCommas));
		else
			sDollarVal = f.substr(0, (nNum + nCommas));

		// Determine if a zero is the first number or if a
		// comma is the first or last character in the string.

		if(sDollarVal.lastIndexOf("0", 0) == 0 )
		{
			alert("Co-pay amount is invalid. \n\nYou cannot start the dollar amount out with a zero.");
			return false;
		}
		
		else if(sDollarVal.lastIndexOf(",", 0) == 0)

		{

			alert("Co-pay amount is invalid \n\nYou cannot start the dollar amount out with a comma.");
			return false;

		}

		else if(sDollarVal.indexOf(",", (sDollarVal.length - 1)) == (sDollarVal.length - 1))

		{

			alert("Co-pay amount is invalid. \n\nYou have a mis-placed comma.");
			return false;

		}

		else

		{

			// Initialize bComma indicating a comma has not been occured yet.

			bComma = false;

			for(i = 0; i < sDollarVal.length; i++)

			{

				// Assign charater in substring to x.

				x = sDollarVal.substr(i, 1);

				if(parseInt(x) >= 0 || parseInt(x) <= 9)

				{

					// If x is a number add one to the number counter.

					nNumCount = nNumCount + 1;

					// Since comma(s) are present number counter cannot 
					// be more then three before the first or next comma.

					if(nNumCount > 3)

					{

						alert("Co-pay amount is invalid. \n\nYou have a mis-placed comma.");
						return false;

					} // end if

				}

				else

				{

					// If the number counter is less then three and
					// the comma indicator is true the comma is either
					// mis-placed or there are not enough values.

					if(nNumCount != 3 && bComma)

					{

						alert("Co-pay amount is invalid. \n\nYou have a mis-placed comma.");

						return false;

					} // end if

					

					// Reset the number counter back to zero.

					nNumCount = 0;

					

					// Set the comma indicator to true indicating
					// that the first comma has been found and that
					// there now MUST be three numbers after each
					// comma until the loop hits the end.

					bComma = true;

				} // end if

			} // end for

			
			// Determine if after the loop ended that there
			// was a total of three final numbers after the
			// last comma.

			if(nNumCount != 3 && bComma)

			{
				alert("Co-pay amount is invalid. \n\nYou have a mis-placed comma.");
				return false;

			} // end if

		} // end if

	} // end if

	

	// Return true indicating that the value is a valid currency.

	return true;
}	

function isUSPhoneNumber (s)
{   
	var digitsInUSPhoneNumber = 10;
	s = s.replace("(", "");
	s = s.replace(")", "");
	s = s.replace("-", "");
	s = s.replace(" ", "");
    return (IsInteger(s) && s.length == digitsInUSPhoneNumber)
}
