var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var whitespace = " \t\n\r";
var decimalPointDelimiter = "."
var creditCardDelimiters = " "
var mPrefix = "You did not enter a value into the "
var mSuffix = " field. This is a required field. Please enter it now."
var sExpirationDate = "Expiration Date"
var sEmail = "Email"
var sCreditCardNumber = "Credit Card Number"
var sCreditCardType = "Credit Card Type"
var sCreditCardHolder = "Name of Cardholder"
var sName = "Name"
var sTelephone = "Telephone"
var sAddress = "Address"
var sCity = "City"
var sProvince = "State or Province"
var sCountry = "Country"
var sProvince = "State or Province"
var sPostalCode = "Postal Code (ZIP)"
var sAutopiaQuotationNumber = "Autopia Quotation Number"
var sQuantity = "The 'Quantity Required' field must be a postive number.  Please re-enter it now."
var sProdID = "first, 'Product Required'"

var iEmail = "This field must be a valid email address (like foo@bar.com). Please re-enter it now."
var iCreditCardPrefix = "This is not a valid "
var iCreditCardSuffix = " credit card number. Please check your card and re-enter it now."
var iDay = "This field must be a day number between 1 and 31.  Please re-enter it now."
var iMonth = "This field must be a month number between 01 and 12.  Please re-enter it now."
var iYear = "This field must be a 2 or 4 digit year number.  Please re-enter it now."
var iDatePrefix = "The Day, Month, and Year for "
var iDateSuffix = " do not form a valid date.  Please re-enter them now."
var pEntryPrompt = "Please enter a "
var pEmail = "valid email address (like foo@bar.com)."
var pCreditCard = "valid credit card number."
var pDay = "day number between 1 and 31."
var pMonth = "month number between 1 and 12."
var pYear = "2 or 4 digit year number."
var defaultEmptyOK = false

function makeArray(n) {
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isWhitespace (s)

{   var i;

    if (isEmpty(s)) return true;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    return true;
}


/*Add a leading zero to numbers in the range (0-9)*/

function addLeadingZero(x) 
{
var i = parseInt(x, 10);

return(i<0||i>9?"":"0")+i;
}


function stripCharsInBag (s, bag)

{   var i;
    var returnString = "";

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}


function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}


function isInteger (s)
{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }
    return true;
}


function isSignedInteger (s)
{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}


function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
}

// isPositiveInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer > 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isPositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isPositiveInteger.arguments.length > 1)
        secondArg = isPositiveInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a positive, not negative, number

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) > 0) ) );
}


function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    if (isWhitespace(s)) return false;
    
    var i = 1;
    var sLength = s.length;

    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function isYear (s)
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}


function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    if (!isInteger(s, false)) return false;
    var num = parseInt (s, 10);
    return ((num >= a) && (num <= b));
}


function isMonth (s)
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}


function isDay (s)
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}


function daysInFebruary (year)
{   
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}


function isDate (year, month, day)
{   
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}


function warnEmpty (theField, s)
{   theField.focus()
    alert(mPrefix + s + mSuffix)
    return false
}


function warnInvalid (theField, s)
{   theField.focus()
    theField.select()
    alert(s)
    return false
}


function checkString (theField, s, emptyOK)
{   
    if (checkString.arguments.length == 2) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value)) 
       return warnEmpty (theField, s);
    else return true;
}


function checkEmail (theField, emptyOK)
{   if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false)) 
       return warnInvalid (theField, iEmail);
    else return true;
}


function checkYear (theField, emptyOK)
{   if (checkYear.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isYear(theField.value, false)) 
       return warnInvalid (theField, iYear);
    else return true;
}


function checkMonth (theField, emptyOK)
{   if (checkMonth.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isMonth(theField.value, false)) 
       return warnInvalid (theField, iMonth);
    else return true;
}


function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
{   
    if (checkDate.arguments.length == 4) OKtoOmitDay = false;
    if (!isYear(yearField.value)) return warnInvalid (yearField, iYear);
    if (!isMonth(monthField.value)) return warnInvalid (monthField, iMonth);
    if ( (OKtoOmitDay == true) && isEmpty(dayField.value) ) return true;
    else if (!isDay(dayField.value)) 
       return warnInvalid (dayField, iDay);
    if (isDate (yearField.value, monthField.value, dayField.value))
       return true;
    alert (iDatePrefix + labelString + iDateSuffix)
    return false;
}


function checkDateIfCcNum (ccNum, year, month, day, label, OmitDay)
{   
    if (!isWhitespace(ccNum))
       return checkDate(year, month, day, label, OmitDay);
    else 
    {  
	return true;
    }
}


function checkExpiredIfCcNum(ccNum,yearValue,monthValue)
{   
    if (!isWhitespace(ccNum))
       return checkExpired(yearValue,monthValue);
    else 
    {  
	return true;
    }
}


function checkExpired(year,month)
{
 var expired = false;
 var result = true;
 var inputMonth = parseInt(month);
 var inputYear = parseInt(year);
 			
	if (year.length == 2)

		inputYear += 2000;
 			
 	var now = new Date();
 			
	var nowMonth = now.getMonth() + 1;
	var nowYear = now.getFullYear();
			
	expired = (nowYear > inputYear) || ((nowYear == inputYear ) && (nowMonth > inputMonth));

 		
	if (expired)
		{
 			result = false;
 			alert('This credit card appears to have expired. Please check and re-enter the expiration date.');
			document.OrderForm.ExpirationMonth.focus();
			document.OrderForm.ExpirationMonth.select();
		}
	
  return result;
}

function checkQuantity (form,numFieldsToCheck,prodFieldName,prodQtyFieldName)
{   
    var i;
    var prod;
    var prodFieldName;
    var prodQtyFieldName;
    var qntField;
    var qnt;
    var qntval;
    var numFields = numFieldsToCheck + 1;
    var result = true;



    for (i = 1; i < numFields; i++)
    {   
     prod = prodFieldName + i;

	if (!isWhitespace(form.elements[prod].value)){

        	// Get the next quantity field.
        	qnt = prodQtyFieldName + i;
		qntField = form.elements[qnt];
		qntVal = form.elements[qnt].value;

        	//Check it
        	if (!isPositiveInteger(qntVal, false))
		{
		warnInvalid (qntField, sQuantity);
 		result = false;
		break;
		}
	}
    }
    return result;
}

function printOrder(form,numFieldsToCheck,prodFieldName,prodQtyFieldName)
{   
    var i;
    var prod;
    var prodFieldName;
    var prodQtyFieldName;
    var qntField;
    var qnt;
    var qntval;
    var message = "";
    var numFields = numFieldsToCheck + 1;

    for (i = 1; i < numFields; i++)
    {   
     prod = prodFieldName + i;

	if (!isWhitespace(form.elements[prod].value)){

        	// Get the next quantity field.
        	qnt = prodQtyFieldName + i;
		qntField = form.elements[qnt];
		qntVal = form.elements[qnt].value;

		message += "Product ID: " + form.elements[prod].value + "    Quantity: " + qntVal + "\n";
        }
    }
    return message;
}


function checkIfCcNum (ccNum, theField, s, emptyOK)
{   
    if (!isWhitespace(ccNum))
       return checkString(theField, s, emptyOK);
    else 
    {  
	return true;
    }
}


function getSelectOptionValue (selection)
{   for (var i = 0; i < selection.length; i++)
    {   if (selection[i].selected) { break }
    }
    return selection[i].value
}


function checkCreditCard (selection, theField)
{   var cardType = getSelectOptionValue (selection)
    var normalizedCCN = stripCharsInBag(theField.value, creditCardDelimiters)
    if (!isCardMatch(cardType, normalizedCCN)) 
       return warnInvalid (theField, iCreditCardPrefix + cardType + iCreditCardSuffix);
    else 
    {  theField.value = normalizedCCN
       return true
    }
}


function isCreditCard(st) {
  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
    return (false);
}


function isVisa(cc)
{
  if (((cc.length == 16) || (cc.length == 13)) &&
      (cc.substring(0,1) == 4))
    return isCreditCard(cc);
  return false;
}


function isMasterCard(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) &&
      ((seconddig >= 1) && (seconddig <= 5)))
    return isCreditCard(cc);
  return false;
}


function isAmericanExpress(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7)))
    return isCreditCard(cc);
  return false;
}


function isDinersClub(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 14) && (firstdig == 3) &&
      ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))
    return isCreditCard(cc);
  return false;
}


function isCardMatch (cardType, cardNumber)
{
	cardType = cardType.toUpperCase();
	var doesMatch = true;

	if ((cardType == "VISA") && (!isVisa(cardNumber)))
		doesMatch = false;
	if ((cardType == "MASTERCARD") && (!isMasterCard(cardNumber)))
		doesMatch = false;
	if ( ( (cardType == "AMERICANEXPRESS") || (cardType == "AMEX") )
                && (!isAmericanExpress(cardNumber))) doesMatch = false;
	if ((cardType == "DINERSCLUB") && (!isDinersClub(cardNumber)))
		doesMatch = false;
	return doesMatch;
}