function isValidTime(value) {
   var colonCount = 0;
   var hasMeridian = false;
   for (var i=0; i<value.length; i++) {
      var ch = value.substring(i, i+1);
      if ( (ch < '0') || (ch > '9') ) {
         if ( (ch != ':') && (ch != ' ') && (ch != 'a') && (ch != 'A') && (ch != 'p') && (ch != 'P') && (ch != 'm') && (ch != 'M')) {
            return false;
         }
      }
      if (ch == ':') { colonCount++; }
      if ( (ch == 'p') || (ch == 'P') || (ch == 'a') || (ch == 'A') ) { hasMeridian = true; }
   }
   if ( (colonCount < 1) || (colonCount > 2) ) { return false; }
   var hh = value.substring(0, value.indexOf(":"));
   if ( (parseFloat(hh) < 0) || (parseFloat(hh) > 23) ) { return false; }
   if (hasMeridian) {
      if ( (parseFloat(hh) < 1) || (parseFloat(hh) > 12) ) { return false; }
   }
   if (colonCount == 2) {
      var mm = value.substring(value.indexOf(":")+1, value.lastIndexOf(":"));
   } else {
      var mm = value.substring(value.indexOf(":")+1, value.length);
   }
   if ( (parseFloat(mm) < 0) || (parseFloat(mm) > 59) ) { return false; }
   if (colonCount == 2) {
      var ss = value.substring(value.lastIndexOf(":")+1, value.length);
   } else {
      var ss = "00";
   }
   if ( (parseFloat(ss) < 0) || (parseFloat(ss) > 59) ) { return false; }
   return true;
}

function getMonth(val) { 
  var monthArray = new Array("JAN","FEB","MAR","APR","MAY","JUN", 
                             "JUL","AUG","SEP","OCT","NOV","DEC"); 
  for (var i=0; i<monthArray.length; i++) { 
    if (monthArray[i] == val) { 
      return(i); 
    } 
  } 
  return(-1); 
} 
function checkDate(val) { 
  var success = true; 
  var mo, day, yy, testDate; 
  val = val.toUpperCase();

  var re = new RegExp("[0-9]{1,2}[ -][A-Z]{3}[ -][0-9]{4}", "g"); 
  if (re.test(val)) { 
    var delimChar = (val.indexOf(" ") != -1) ? " " : "-"; 
    //var delimChar = "-"; 
    var delim1 = val.indexOf(delimChar); 
    var delim2 = val.lastIndexOf(delimChar); 
    day = parseInt(val.substring(0,delim1),10); 
    mo = getMonth(val.substring(delim1+1,delim2),10); 
    yy = parseInt(val.substring(delim2+1),10); 
    testDate = new Date(yy,mo,day); 
    if (testDate.getDate() == day) { 
      if (testDate.getMonth() == mo) { 
        if (!testDate.getFullYear() == yy) { 
          alert("Invalid year entry."); 
          success = false; 
        } 
      } 
      else { 
        alert("Invalid month entry."); 
        success = false; 
      } 
    } 
    else { 
      alert("Invalid day entry."); 
      success = false; 
    } 
  } 
  else { 
    //alert("Incorrect date format.  Enter as DD-MON-YYYY or DD/MON/YYYY."); 
    success = false; 
  } 

  return(success); 
} 


// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.

// The function returns true if a valid date, false if not.
// ******************************************************************

function chkDate(dateStr) {

    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        //alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
        return false;
    }

    month = matchArray[1]; // parse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        alert("Month must be between 1 and 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        alert("Day must be between 1 and 31.");
        return false;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        alert("Month "+month+" doesn't have 31 days.")
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            alert("February " + year + " doesn't have " + day + " days.");
            return false;
        }
    }
    return true; // date is valid
}

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function isDate(month, day, year)
{
	// checks if date passed is valid
	// will accept dates in following format:
	// isDate(dd,mm,ccyy), or
	// isDate(dd,mm) - which defaults to the current year, or
	// isDate(dd) - which defaults to the current month and year.
	// Note, if passed the month must be between 1 and 12, and the
	// year in ccyy format.

    var today = new Date();
    year = ((!year) ? y2k(today.getYear()):year);
    month = ((!month) ? today.getMonth():month-1);
    if (!day) return false
    var test = new Date(year,month,day);
    if ( (y2k(test.getYear()) == year) &&
         (month == test.getMonth()) &&
         (day == test.getDate()) )
        return true;
    else
        return false
}

function emailCheck (emailStr) {
/* 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)")
	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.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        //alert("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	//alert("The domain name doesn't seem to be valid.")
    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 || 
    domArr[domArr.length-1].length>4) {
   // the address must end in a two letter or three letter word.
   // changed to allow 4 letter ending for .aero email addresses
   //alert("The address must end in a three-letter domain, or two letter country.")
   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)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}

//will strip out spaces parens and dashes from a string
function trim(word){
	var newvalue = "";
	for (i=0; i<word.length; i++ )
	{
		if (word.charAt(i) != "(" && word.charAt(i) != ")" && word.charAt(i) != "-" && word.charAt(i) != " ")
			newvalue = newvalue + word.charAt(i);
	}
	return newvalue
}
function isNumeric(x)
{
  	var numbers="0123456789";
	// is x a String or a character?
	if(x.length>1)
	{
		// remove negative sign
		x=Math.abs(x)+"";
		for(j=0;j<x.length;j++) 
		{
			// call isNumeric recursively for each character
			number=isNumeric(x.substring(j,j+1));
			if(!number) return number;
		}
		return number;
	}
	else 
	{
		// if x is number return true
		if(numbers.indexOf(x)>=0) return true;
			return false;
	}
}
function isAlpha(str)
{
  var alphaChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  for ( var c=str.length-1; c>=0; c-- )
    if ( alphaChars.indexOf(str.charAt(c))==-1 )
      return false;
  return true;
}

/////////////////////////////////////////////////////////////////////
// Form Field Validation Functions:
//
// isValidExpDate(formField,fieldLabel,required)
//   -- checks for date in the format MM/YY or MM/YYYY against the current date
// isValidCreditCardNumber(formField,ccType,fieldLabel,required)
//   -- checks for valid credit card format using the Luhn check and known digits about various cards
//

function validRequired(formField,fieldLabel)
{
	var result = true;
	
	if (formField.value == "")
	{
		//alert('Please enter a value for the "' + fieldLabel +'" field.');
		formField.focus();
		result = false;
	}
	
	return result;
}


function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset)
{
	var result = true;
	
	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}
	
	return result;
}

function isValidExpDate(formFieldMonth, formFieldYear,fieldLabel,required)
{
	var result = true;
	var formValue = formFieldMonth.value;

	if (required && !validRequired(formFieldMonth,fieldLabel))
		result = false;
  
 	if (result)
 	{
 		//var elems = formValue.split("/");
 		
 		//result = (elems.length == 2); // should be two components
 		var expired = false;
 		
 		if (result)
 		{
			var month = formFieldMonth.value; //parseInt(elems[0],10);
 			var year = formFieldYear.value; //parseInt(elems[1],10);
			//alert(month);
			//alert(year);
 			//if (elems[1].length == 2)
 			//	year += 2000;
 			
 			var now = new Date();
 			
 			var nowMonth = now.getMonth() + 1;
 			var nowYear = now.getFullYear();
 			
 			expired = (nowYear > year) || ((nowYear == year ) && (nowMonth > month));
 			
			//result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
			//		 allDigits(elems[1]) && ((elems[1].length == 2) || (elems[1].length == 4));
 		}
 		
  		//if (!result)
 		//{
 		//	alert('Please enter a date in the format MM/YYYY for the "' + fieldLabel +'" field.');
		//	formFieldMonth.focus();
		//}
		if (expired)
		{
 			result = false;
 			//alert('The date for "' + fieldLabel +'" has expired.');
			formFieldMonth.focus();
		}
	} 
	
	return result;
}

function isValidCreditCardNumber(formField,ccType,fieldLabel,required)
{
	var result = true;
 	var ccNum = formField.value;

	if (required && !validRequired(formField,fieldLabel))
		result = false;
 
  	if (result && (formField.value.length>0))
 	{ 
 		if (!allDigits(ccNum))
 		{
 			//alert('Please enter only numbers (no dashes or spaces) for the "' + fieldLabel +'" field.');
			formField.focus();
			result = false;
		}	

		if (result)
 		{ 
 			
 			if (!LuhnCheck(ccNum) || !validateCCNum(ccType,ccNum))
 			{
 				//alert('Please enter a valid card number for the "' + fieldLabel +'" field.');
				formField.focus();
				result = false;
			}	
		} 

	} 
	
	return result;
}

function LuhnCheck(str) 
{
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++) 
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var 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)
    result = false;
    
  return result;
}



function GetRadioValue(rArray)
{
	for (var i=0;i<rArray.length;i++)
	{
		if (rArray[i].checked)
			return rArray[i].value;
	}
	
	return null;
}


function validateCCNum(cardType,cardNum)
{
	var result = false;
	cardType = cardType.toUpperCase();
	
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);

	switch (cardType)
	{
		case "VISA":
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case "AMEX":
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "MASTER":
		case "MASTERCARD":
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case "DISCOVER":
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case "DINERS":
			var validNums = "068";
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
	}
	return result;
}

function validCCForm(ccTypeField,ccNumField,ccExpFieldMonth, ccExpFieldYear)
{
	var result = isValidCreditCardNumber(ccNumField,ccTypeField.value,"Credit Card Number",true) &&
		isValidExpDate(ccExpFieldMonth, ccExpFieldYear,"Expiration Date",true);
	return result;
}