/* standard form functions */

//initialize the nameAddress section of a form
function initializeNameAddress(frm)
{
	//declare variables
	var strFieldNamePrefix="";
	
	//accept optional second parameter
	if(arguments[1])
	{
		strFieldNamePrefix=arguments[1].toString();
	}
	
	//disable country other field based on country selection
	eval("enableInputBasedOnValue(frm."+strFieldNamePrefix+"country,'other',frm."+strFieldNamePrefix+"countryOther);");
	//set initial focus
	frm.firstName.focus();
	frm.firstName.select();
}

//initialize a second nameAddress section of a form
//same as above, but does not set focus
function initializeNameAddressOther(frm)
{
	//declare variables
	var strFieldNamePrefix="";
	
	//accept optional second parameter
	if(arguments[1])
	{
		strFieldNamePrefix=arguments[1].toString();
	}
	
	//disable country other field based on country selection
	eval("enableInputBasedOnValue(frm."+strFieldNamePrefix+"country,'other',frm."+strFieldNamePrefix+"countryOther);");
}

function validNameAddress(frm)
{
	//declare variables
	var returnValue=true;
	var phoneRequired=false; //boolean argument to indicate whether phone is required
	var emailRequired=false; //boolean argument to indicate whether email address is required
	var strFieldNamePrefix=""; //string argument that should match string used to create additional nameAddress sections with prefixes (PHP).
	var strNameAddressOwner="your"; //string argument used in the error messages to indicate who's information is missing.
	
	//collect values of optional 2-4 parameters
	if(arguments[1])
	{
		phoneRequired=arguments[1];
	}
	if(arguments[2])
	{
		emailRequired=arguments[2];
	}
	if(arguments[3])
	{
		strFieldNamePrefix=arguments[3].toString();
	}
	if(arguments[4])
	{
		strNameAddressOwner=arguments[4].toString();
	}
	
	//convert to upper case
	postalZipBlur(frm.postalZip);
	
	//check for valid Name and Address content and display appropriate error messages
	if(eval("frm."+strFieldNamePrefix+"firstName").value.length==0)
	{
		alert("Please enter "+strNameAddressOwner+" first name");
		eval("frm."+strFieldNamePrefix+"firstName").focus();
		returnValue=false;
	}
	else if(eval("frm."+strFieldNamePrefix+"lastName").value.length==0)
	{
		alert("Please enter "+strNameAddressOwner+" last name");
		eval("frm."+strFieldNamePrefix+"lastName").focus();
		returnValue=false;
	}
	else if(eval("frm."+strFieldNamePrefix+"address1").value.length==0)
	{
		alert("Please enter "+strNameAddressOwner+" address");
		eval("frm."+strFieldNamePrefix+"address1").focus();
		returnValue=false;
	}
	else if(eval("frm."+strFieldNamePrefix+"city").value.length==0)
	{
		alert("Please enter "+strNameAddressOwner+" city");
		eval("frm."+strFieldNamePrefix+"city").focus();
		returnValue=false;
	}
	else if(eval("frm."+strFieldNamePrefix+"provinceState").value=="invalid" | eval("frm."+strFieldNamePrefix+"provinceState").value=="")
	{
		alert("Please select "+strNameAddressOwner+" province or state");
		eval("frm."+strFieldNamePrefix+"provinceState").focus();
		returnValue=false;
	}
	else if(eval("frm."+strFieldNamePrefix+"postalZip").value.length==0)
	{
		alert("Please enter "+strNameAddressOwner+" postal or zip code");
		eval("frm."+strFieldNamePrefix+"postalZip").focus();
		returnValue=false;
	}
	else if(!isValidPostalZipCode(eval("frm."+strFieldNamePrefix+"postalZip").value,eval("frm."+strFieldNamePrefix+"country").value))
	{
		alert("Please enter a valid postal or zip code");
		eval("frm."+strFieldNamePrefix+"postalZip").focus();
		eval("frm."+strFieldNamePrefix+"postalZip").select();
		returnValue=false;
	}
	else if(eval("frm."+strFieldNamePrefix+"country").value=="invalid" | eval("frm."+strFieldNamePrefix+"country").value=="")
	{
		alert("Please select "+strNameAddressOwner+" country");
		eval("frm."+strFieldNamePrefix+"country").focus();
		returnValue=false;
	}
	else if(eval("frm."+strFieldNamePrefix+"country").value.toLowerCase()=="other" & eval("frm."+strFieldNamePrefix+"countryOther").value.length==0)
	{
		alert("Please enter "+strNameAddressOwner+" country");
		eval("frm."+strFieldNamePrefix+"countryOther").focus();
		returnValue=false;
	}
	else if(phoneRequired && eval("frm."+strFieldNamePrefix+"phone1").value.length==0)
	{
		alert("Please enter "+strNameAddressOwner+" phone number");
		eval("frm."+strFieldNamePrefix+"phone1").focus();
		returnValue=false;
	}
	else if(emailRequired && eval("frm."+strFieldNamePrefix+"email").value.length==0)
	{
		alert("Please enter "+strNameAddressOwner+" email address");
		eval("frm."+strFieldNamePrefix+"email").focus();
		returnValue=false;
	}
	else if(eval("frm."+strFieldNamePrefix+"email").value.length!=0 && !isValidEmailAddress(eval("frm."+strFieldNamePrefix+"email").value))
	{
		alert("Please enter a valid email address");
		eval("frm."+strFieldNamePrefix+"email").focus();
		eval("frm."+strFieldNamePrefix+"email").select();
		returnValue=false;
	}
	
	return returnValue;
}

function initializeNameEmail(frm)
{
	//set initial focus
	frm.firstName.focus();
}

function validNameEmail(frm)
{
	var returnValue=true;
	
	//check for valid name and email address and display appropriate error messages
	if(frm.firstName.value.length==0)
	{
		alert("Please enter your first name");
		frm.firstName.focus();
		returnValue=false;
	}
	else if(frm.lastName.value.length==0)
	{
		alert("Please enter your last name");
		frm.lastName.focus();
		returnValue=false;
	}
	else if(frm.email.value.length==0)
	{
		alert("Please enter your email address");
		frm.email.focus();
		returnValue=false;
	}
	else if(!isValidEmailAddress(frm.email.value))
	{
		alert("Please enter a valid email address");
		frm.email.focus();
		frm.email.select();
		returnValue=false;
	}
	
	return returnValue;
}

function validComments(frm)
{
	var returnValue=true;
	
	if(frm.comments.value.length==0)
	{
		alert("Please enter your comments or questions in the comments field");
		frm.comments.focus();
		returnValue=false;
	}
	
	return returnValue;
}

function validVerification(frm)
{
	var returnValue=true;
	
	if(frm.verification.value.length==0)
	{
	}
	else
	{
		alert("The Verification field has been filled in.  Please leave this field blank.");
		returnValue=false;
	}
	
	return returnValue;
}

//convert postal code to upper case
function postalZipBlur(input)
{
	input.value=input.value.toUpperCase();
}

function enableInputBasedOnValue(input,enableValue,inputEnable)
{
	//takes two input fields (input, inputEnable) and a string (enableValue).
	//if the value of input is equal to enableValue, then inputEnable is enabled, and 
	//focus is set to it, otherwise it is disabled.
	if(input.value.toLowerCase()==enableValue)
	{
		inputEnable.disabled=false;
		inputEnable.select();
		inputEnable.focus();
	}
	else
	{
		inputEnable.disabled=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
    http://www.blackmarket-press.net/info/plastic/check_digit.htm 
where the details of other cards may also be found.

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Web Site:	http://www.braemoor.co.uk/software/creditcard.shtml

*/

/*
   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] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function isValidccNumber(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: "MC", 
               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};
               
  // 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
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      var 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;
}

/*============================================================================*/