﻿
// Validates the credit card number
function checkCreditCard() {
	
	var ccElement = document.getElementById("txtCreditCardNumber");
	var val = ccElement.value;
	if (val=="") return true

	var cardType = getRadioButtonValue(document.getElementsByName("rdoCCTypes"));
	var normalizedCCN = stripCharsInBag(ccElement.value, " -_.")
	if (!isCardMatch(cardType, normalizedCCN))
		return warnInvalid(ccElement,
		 "The credit card number entered is invalid for type of credit card selected");
	if (!isCreditCard(normalizedCCN)) {
		ccElement.value = normalizedCCN
		return true;
	}
	else
		return false;
}

function isCreditCard(st) {
	// Encoding only works on cards with less than 19 digits
	if (st.length > 19)
		return (false);

	sum = 0; mul = 1; l = st.length;
	for (i = 0; i < l; i++) {
		digit = st.substring(l - i - 1, l - i);
		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)
		return (true);
	else
	{
		alert("Invalid credit card number");
		document.getElementById("txtCreditCardNumber").focus();
		return false;
	}

}

// Checks if the credit card number matches the selected card type
function isCardMatch (cardType, cardNumber)
{
		var doesMatch = true;

		if ((cardType == "Visa") && (!isVisa(cardNumber)))
					doesMatch = false;
		if ((cardType == "MasterCard") && (!isMasterCard(cardNumber)))
				doesMatch = false;
		if ((cardType == "AMEX") && (!isAmericanExpress(cardNumber)))
				  doesMatch = false;
		return doesMatch;
}

/*  ================================================================
FUNCTION:  isVisa()

INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is a valid VISA number.
                
		  false, otherwise

Sample number: 4111 1111 1111 1111 (16 digits)
================================================================ */
function isVisa(cc)
{
	if (((cc.length == 16) || (cc.length == 13)) &&
	  (cc.substring(0, 1) == 4))
		return true;
	else
		return false;
} 

/*  ================================================================
FUNCTION:  isMasterCard()

INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is a valid MasterCard
				number.
                
		  false, otherwise

Sample number: 5500 0000 0000 0004 (16 digits)
================================================================ */
function isMasterCard(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) &&
	  ((seconddig >= 1) && (seconddig <= 5)))
  	return true;
  else
  	return false;
}  

/*  ================================================================
FUNCTION:  isAmericanExpress()

INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is a valid American
				Express number.
                
		  false, otherwise

Sample number: 340000000000009 (15 digits)
================================================================ */
function isAmericanExpress(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) &&
	  ((seconddig == 4) || (seconddig == 7)))
  	return true;
  else;
	return false;
}

function getRadioButtonValue(radio) {
	for (var i = 0; i < radio.length; i++) {
		if (radio[i].checked) { break }
	}
	return radio[i].value
}

function stripCharsInBag(s, bag) {
	var i;
	var returnString = "";

	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.

	for (i = 0; i < s.length; i++) {
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}

	return returnString;
}

function warnInvalid(uiControl, message) {
	alert(message)
	uiControl.value = "";
	uiControl.focus()
	return false
}

// Validates the email address stored in the specified control
function isValidEmail(emailAddressControl) {

	if (!this.testEmail(emailAddressControl.value)) {
		emailAddressControl.focus();
		return false;
	}
	return true;
}

function testEmail (emailStr) {

	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */
	var checkTLD=1;

	/* The following is the list of known TLDs that an e-mail address must end with. */
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

	/* 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];

	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("The Email user name contains invalid characters.");
			return false;
	   }
	}

	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("The Email domain name contains invalid characters.");
			return false;
		}
	}

	// See if "user" is valid 
	if (user.match(userPat)==null) {

		// user is not valid
		alert("The Email user name 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("Email destination IP address is invalid!");
				return false;
			}
		}
		return true;
	}

	// Domain is symbolic name.  Check if it's valid. 
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i = 0; i < len; i++) {
		if (domArr[i].search(atomPat) == -1) {
			alert("The Email domain name does not seem to be valid.");
			return false;
		}
	}

	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("The Email address must end in a well-known domain or two letter " + "country.");
		return false;
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
		alert("The Email address is missing a hostname!");
		return false;
	}

	// If we've gotten this far, everything's valid!
	return true;
}

function validateScholarshipReg() {
    if (checkIfEmpty("txtFirstName", "First Name"))
        return false;

    if (checkIfEmpty("txtLastname", "Last Name"))
        return false;

    if (checkIfEmpty("txtEmailAddress", "Email Address"))
        return false;

    if (checkIfEmpty("txtEmailConfirm", "Email Confirmation"))
        return false;

    if (!isValidEmail(document.getElementById("txtEmailAddress"))) {
        return false;
    }

    if (document.getElementById("txtEmailAddress").value != document.getElementById("txtEmailConfirm").value))
    {
        alert("The email and confirmation email addresses do not match!");
        document.getElementById("txtEmailAddress").focus();
        return false;
    }

}

function validate() {

	if (checkIfEmpty("txtName", "Name"))
		return false;

	if (checkIfEmpty("txtAddress1", "Address 1"))
		return false;
		
	if (checkIfEmpty("txtCity", "City"))
		return false;
		
	if (checkIfEmpty("txtState", "State"))
		return false;
		
	if (checkIfEmpty("txtZipCode", "Zip code"))
		return false;

	if (checkIfEmpty("txtEmail", "Email"))
		return false;	
	
	if (!isValidEmail(document.getElementById("txtEmail")))
	{
		return false;
	}

	if (checkIfEmpty("txtPhone", "Telephone"))
		return false;

	if (document.getElementById("lblDollars").innerText == "Invoice Number") {
		if (checkIfEmpty("txtQuantity", "Invoice Number"))
				return false;
		if (checkIfEmpty("txtQuantity2", "Payment Amount"))
			return false;
		
	}
	else 
	{
		if ((document.getElementById("txtQuantity").value == "0" ||
			document.getElementById("txtQuantity").value == "") &&
			(document.getElementById("txtQuantity2").value == "0" ||
			document.getElementById("txtQuantity2").value == "")) 
		{
				alert("You must enter a quantity");
				document.getElementById("txtQuantity").focus();
				return false;
		}
	}

	if (checkIfEmpty("txtCreditCardNumber", "Credit Card Number"))
		return false;

	if (checkIfEmpty("txtCardExp", "Credit Card Expiration"))
		return false;
	
	if (checkIfEmpty("txtCardHolder", "Card Holder"))
		return false;
		
	return true;
}

function checkIfEmpty(elementID, description) {

	var element = document.getElementById(elementID);
	if (element.value == "") {
		alert(description + " cannot be blank");
		element.focus();
		return true;
	}
	return false;
}

function checkIfEmptyNumeric(elementID, description) {

	var element = document.getElementById(elementID);
	if (element.value == "" || element.value == "0") {
		alert(description + " cannot be blank");
		element.focus();
		return true;
	}
	return false;
}


