
<!-- ============== Form Validation ====================== -->
//This is used to validate the forms w/ business logic
var allowTags = false;

//- This function gives the field focus
	function ffocus(field, myForm) { myForm.elements[field].focus() };

//- This function checks a value to ensure it is not an HTLM tag
	function isTag (t)
	{	return ((t != ">") && (t != "<"))   }
 
 	function fchecktag(val)
	{
		if (allowTags)
		{return true;}

		var j
	    for (j = 0; j < val.length; j++)
	   {   
	       var t = val.charAt(j);
	       if (!isTag(t)) return false;
	   }
	   // All characters are valid.
	   return true;
	} 


//- This function checks for teh double quote mark in a string
	function isQuote (t)
	{	return (t != "\"")   }

		function fCheckQuote(val)
	{
		var j
	    for (j = 0; j < val.length; j++)
	   {   
	       var t = val.charAt(j);
	       if (!isQuote(t)) return false;
	   }
	   // All characters are valid.
	   return true;
	}


//- This function makes sure that all characters ina string are numeric
	function isDigit (c)
	{   return ((c >= "0") && (c <= "9")) }
			
	function fchecknum(val)
	 {
		var i
	     for (i = 0; i < val.length; i++)
	    {   
	        // Check that current character is number.
	        var c = val.charAt(i);
	        if (!isDigit(c)) return false;
	    }
	    // All characters are numbers.
	    return true;
	 }			



//- This function checks to make sure string is not made up entirely of spaces
	function fcheckspaces(strValue)
	{
		var cntChar
	    for (cntChar = 0; cntChar < strValue.length; cntChar++)
	   {   
	       // Check to see if current character is a space
	       var vChar = strValue.charAt(cntChar);
	       if (vChar != ' ') return true;
	   }
	   return false;
	}

//- This function checks to make sure that there was data entered into a field
	function fcheckBlank(myForm, field) {
		var val = myForm.elements[field].value;
			if (!fchecktag(val))
		{ return false }
			
		if (val.length == 0)
		{ return false }
					
		if (!fcheckspaces(val))
		{ return false }
				
		else
		{ return true }
	}
			
	function fcheckBlankItem(myForm, field) {
		var indexvalue = myForm.elements[field].selectedIndex
		
		if (myForm.elements[field].size == 0 || myForm.elements[field][indexvalue].value==''
			|| myForm.elements[field][indexvalue].value == 0) {
			//false
//			return (myForm.elements[field].selectedIndex > 0)
			return (false)
		}
		else {
			//true
			return (true)
//			return (myForm.elements[field].selectedIndex > -1)
		}
	}			

	// checks to make sure that a checkbox in a list is selected
	function fcheckCheckbox(myForm, field) {
		var cntCheck
		var fieldLength = myForm.elements[field].length
		
		if (!fieldLength) {fieldLength = 1}
				
		for(cntCheck = 0; cntCheck < fieldLength; cntCheck++) {
			if (fieldLength == 1 )	{
				if (myForm.elements[field].checked) {return true}
			}
			else {
				if (myForm.elements[field][cntCheck].checked) {return true};
			}
		}
		
		return (false);
	}			
			


//- 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 isDate(dateStr) {
		
	    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	    var matchArray = dateStr.match(datePat); // is the format ok?

		if (dateStr == null || dateStr == '') 
			{ return 0 } // do not check if blank
		 				
		if (matchArray == null) 
			{ return 1 }
				
	    month = matchArray[1]; // parse date into variables
	    day = matchArray[3];
	    year = matchArray[5];

	    if (month < 1 || month > 12) 
			{ return 2 }

	    if (day < 1 || day > 31) 
			{ return 3 }

	    if ((month==4 || month==6 || month==9 || month==11) && day==31) 
			{ return 4 }

	    if (month == 2) { // check for february 29th
	        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	        if (day > 29 || (day==29 && !isleap)) 
	        { return 5 }
	    }
			    
			    
	    return 0; // date is valid
	}
			

	function vfyDate(myForm, field, title) {
	    
	    // Skip field if it doesn't exist
	    if (!myForm.elements[field]) {
	        return true;
	    }
	    
		var dateStr = myForm.elements[field].value
		
		var dateType = isDate(dateStr)

		if (dateType == 0)
			{ return true } //date is valid
		else if (dateType == 1) { 
			alert(title + " is not a valid date.")
			myForm.elements[field].focus()
			return false
		}
		else if (dateType == 2) { 
			alert(title + ": Month must be between 1 and 12.")
			myForm.elements[field].focus()
			return false
		}
		else if (dateType == 3) { 
			alert(title + ': Day must be between 1 and 31.')
			myForm.elements[field].focus()
			return false
		}
		else if (dateType == 4) { 
			alert(title + ": Month "+month+" doesn't have 31 days.")
			myForm.elements[field].focus()
			return false
		}
		else if (dateType == 5) { 
			alert(title + ": February " + year + " doesn't have " + day + " days.")
			myForm.elements[field].focus()
			return false
		}																
	}



//- This function checks to make sure that there was data entered into a field
	function vfyBlank(myForm, field, title)
	{
	    
	    // Skip field if it doesn't exist
	    if (!myForm.elements[field]) {
	        return true;
	    }
	    
		var val = myForm.elements[field].value;

		if (!fcheckBlank(myForm, field))
		{
			alert('Please complete the ' + title + ' field.');
			ffocus(field, myForm);
			return false;
		}
		else
		{ return true }
	}
			
//- This function makes sure that an item was selected
	function vfyBlankItem(myForm, field, title)
	{
	    
	    // Skip field if it doesn't exist
	    if (!myForm.elements[field]) {
	        return true;
	    }
	    
		if (!fcheckBlankItem(myForm, field)) {
			alert('Please complete the ' + title + ' field.');
			ffocus(field, myForm);
			return false;
		}
		else
		{ return true }; 
	}

//- This function makes sure that an checkbox in a list was selected
	function vfyBlankCheckbox(myForm, field, title)
	{
		if (!fcheckCheckbox(myForm, field)) {
			alert('Please select an option in the ' + title + ' field.')
			return false
		}
		else
		{ return true }; 
	}
	
//- This function makes sure that a hidden field has a value
//- (for hidden fields set by other fields)
	function vfyBlankHidden(myForm, field, title, focusField)
	{
	   
		var val = myForm.elements[field].value;

		if (!fcheckBlank(myForm, field))
		{
			alert('Please complete the ' + title + ' field.');
			ffocus(focusField, myForm);
			return false;
		}
		else
		{ return true }
	}


//- This function prompts the user before a delete is made
	function fDelete(id)	{
		if (confirm('These records will be deleted. Continue?')) {
			return (true)
			
			//var Location = document.location.href
			//var Del = "&Delete=True"
			//var SecondaryId = "&SecondaryID=" + id;
			
			// RegExp to get rid of parameters already in location, 
			// otherwise they are added twice
			//DeleteExp = /&Delete=True/gi;
			//IdExp = /&SecondaryID=[0-9a-z]*/gi;
			//Location = Location.replace(DeleteExp, "")
			//Location = Location.replace(IdExp, "")
			
			// redirect location
			//document.location.href = Location + Del + SecondaryId;
		}
		return (false)
	}


//- This fucntion is used to submit a form
	function fSubmitForm(formname)	{
		document.forms[formname].submit()
	}
	
	
	
//- This function checks to make sure that there was data entered is a valid Email address
//- added by vivian
function vfyEmail (myForm, field, title)
{   
        // Skip field if it doesn't exist
	    if (!myForm.elements[field]) {
	        return true;
	    }
	    
		var val = myForm.elements[field].value;
		
		if (!fcheckBlank(myForm, field))
		{
			alert('Please enter a vaild Email address in the ' + title + ' field.');
			ffocus(field, myForm);
			return false;
		}
   
    // is s whitespace?
    if (!fcheckspaces(val))
    {
			alert('Please enter a vaild Email address in the ' + title + ' field.');
			ffocus(field, myForm);
			return false;
		}
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = val.length;

    // look for @
    while ((i < sLength) && (val.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (val.charAt(i) != "@")) 
    {
				alert('Please enter a vaild Email address in the ' + title + ' field.');
				return false;
		}
    else i += 2;

    // look for .
    while ((i < sLength) && (val.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (val.charAt(i) != ".")) 
    {
				alert('Please enter a vaild Email address in the ' + title + ' field.');
				return false;
		}
    else return true;
    
    
}



/*============================================================================*/
/*
This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on 
the web.

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request

*/

/*
   If a credit card number is invalid, an error reason is loaded into the 
   global ccErrorNo variable. This can be be used to index into the global error  
   string array to report the reason to the user if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "Please provide a valid credit card number";
ccErrors [2] = "Credit card number is in an invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function checkCreditCard (cardnumber, cardname) {

  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "15,16", 
               prefixes: "3,1800,2131",
               checkdigit: true};
  cards [7] = {name: "Enroute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase() == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
  
  // Check that the number is numeric, although we do permit a space to occur  
  // every four digits. 
  var cardNo = cardnumber
  var cardexp = /^([0-9]{4})\s?([0-9]{4})\s?([0-9]{4})\s?([0-9]{1,4})$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardexp.exec(cardNo);
  cardNo = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}

/*============================================================================*/


// vfyCreditCard() - returns true if the given field contains a valid credit 
// card number. Otherwise returns false, pops up an error message, and sets the
// focus to the given field. 
// 
// cardType: string, the credit card type. One of those accepted by 
//    checkCreditCard() above (e.g. "Visa", "MasterCard")

function vfyCreditCard(myForm, field, title, cardType) {
	
	// Skip field if it doesn't exist
	if (!myForm.elements[field]) {
	    return true;
	}
	
	var cardNumber = myForm[field].value;
	
	// If the credit card number is not valid...
	if (!checkCreditCard(cardNumber, cardType)) {
	
		// Display an error message and set focus to the field
		alert(title + ": " + ccErrors[ccErrorNo]);
		ffocus(field, myForm);
		
		return false;
		
	// Otherwise, the card is valid
	} else {
		return true;
	}
}


// vfyExpirationDate() - returns true if the given field is 
// in ##/## or #/## format. Otherwise displays an error 
// message, sets focus to the given field, and returns
// false. 

function vfyExpirationDate(myForm, field, title) {

    // Skip field if it doesn't exist
	if (!myForm.elements[field]) {
	    return true;
	}

	var fieldVal;		// Value of the field
	var curChar;		// Current character of field
	var isMonth;		// Should current digit be interpreted as a month?
	var monthVal = '';	// The month portion
	var yearVal = '';	// The year portion
	var isValid = true;	// Is the value a valid exp. date? Assume true.
	
	fieldVal = myForm[field].value;
	
	// Process digits as month to begin with
	isMonth = true;
	
	// For each character in the field value...
	for (i = 0; i < fieldVal.length; i++) {
		
		// Get the character
		curChar = fieldVal.charAt(i);
		
		// If it's a digit...
		if (isDigit(curChar)) {
		
			// Add it to the month or year as appropriate
			if (isMonth) {
				monthVal += curChar;
			} else {
				yearVal += curChar;
			}
			
		// If it is a slash, process next digits as year
		} else if (curChar == '/') {
			isMonth = false;
		
		// Otherwise, if it's not a digit or slash, mark the date invalid
		} else {
			isValid = false;
		}
	}
	
	// If the month is not 1-2 digits, mark the date invalid
	if (monthVal.length < 1 || monthVal.length > 2) 
		isValid = false;
	
	// If the year is not 2 digits, mark the date invalid
	if (yearVal.length != 2) 
		isValid = false;
	
	// If the month is not from 1-12 mark the date invalid
	if (monthVal < 1 || monthVal > 12)
		isValid = false;
	
	// If date is invalid, display an error, set focus, and return false
	if (!isValid) {
		alert(title + ': please enter a valid date in MM/YY format.');
		ffocus(field, myForm);
		return false;
		
	// Otherwise date is valid, so return true
	} else {
		return true;
	}
}