//Does initial card number validation before Luhn Check
function validateCCNum(cardType, cardNum){
	var result = false
	cardType = cardType.charAt(0).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 "V": //Visa
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4")
			break
		/*
		case "AMEX":
			var validNums = "47"
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig) >= -1)
			break
		*/
		case "M": //Master
			var validNums = "12345"
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig) >= -1)
			break
		case "D": //Discover
			result = (cardLen == 16) && (first4digs == "6011")
			break
		/*
		case "DINERS":
			var validNums = "068"
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig) >= -1)
			break
		*/
	}
	return result
}

//Makes sure expiration date is sometime after this month
function validateCCExpDate(strMonth, strYear){
  //If the month or the year is empty, fail
  if (isBlank(strMonth) || isBlank(strYear)){
    return false
  }
  //First get the date in slash format
  var month = parseInt(strMonth, 10)
  var year = parseInt(strYear, 10)
  if (strYear.length == 2){
    year += 2000
  }
  //Get the current date
	var now = new Date()
	//Get the current month and year
	var nowMonth = now.getMonth() + 1
	var nowYear = now.getFullYear()
	//See if the expiration month and year are prior to this month and year
	expired = (nowYear > year) || ((nowYear == year ) && (nowMonth > month))
	//Return negative expired.  If expired is true, it's NOT a valid date
	return !expired
}

//Function to make sure cc# is valid format
function LuhnCheck(str) {
  var result = true
  var digit
  var tproduct
  var sum = 0 
  var mul = 1 
  var strLen = str.length
  
  for (i = 0; i < strLen; i++) {
    digit = str.substring(strLen-i-1,strLen-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){
    result = false
  }
  return result
}

function validateField(formField, fieldLabel, minLength, maxLength, isRequired){
  var msg = ""
  var strBadChars = ""
  var bAllowSpace = true
  var strName = formField.name
  var strNameLower = formField.name.toLowerCase()
  var strValue = GetObjValue(formField)
  var strNoSpace = "zip,cnumber,code"
  var strNoAlpha = ""
  
//Check some general things first...
/////////////////////////////////////////////////////////////////////////////////////
  //Make sure it's not blank.  If it is and it's required, rtn msg and get out.
  if (isBlank(strValue)){
    if (isRequired){
      return "--- Please enter a value for "+fieldLabel+".\n"
    }else{
      return ""
    }
  }
  
  //If it's a drop down
  if (formField.type == "select-one"){
    //If it's required, but it's on the first selection
    if (isRequired && formField.selectedIndex < 1){
      return "--- Make a selection for "+fieldLabel+"\n"
    }else{
      return msg
    }
  }
  
  //Make sure it's within length params if it's not a phone field.
  //Phone fields have their own check below.
  if ((minLength * maxLength != 0) && (strNameLower.indexOf("phone") == -1)){
    msg += chkLength(strValue, fieldLabel, minLength, maxLength)
  }
  
//Now check some field-specific things...
/////////////////////////////////////////////////////////////////////////////////////
  //If it's a phone field
  /********************************************************
  * * * NON-US PHONES HAVE DIFFERENT FORMAT * * *
  if (strNameLower.indexOf("phone") > -1){
    //Make sure phone field is correct length and format
    msg += numFilter(formField, fieldLabel, "###-###-####")
  }
  *********************************************************/
  
  //If it's a zip field, make sure it's all numbers but allow a dash for zip + 4
  /********************************************************
  * * * SOME OVERSEAS ZIPS HAVE ALPHA CHARACTERS * * *
  if (strNameLower.indexOf("zip") > -1){
    if (!allDigits(strValue, true)){
      msg += "--- "+fieldLabel+" must be all numbers.\n"
    }
  }
  *********************************************************/
  
  //If it's the cc code field, make sure it's all numbers
  if (strNameLower == "cc_code"){
    if (!allDigits(strValue, false)){
      msg += "--- "+fieldLabel+" must be all numbers.\n"
    }
  }
  
  //If it's the email field
  if (strNameLower == "contact_email"){
     msg += emailFilter(formField)
  }
  
  //If it's the cc# field...
  if (strName == "CC_Number" && document.frmUserInfo.Payment_Type.selectedIndex > 0 && document.frmUserInfo.Payment_Type.selectedIndex < 4){
    //First run it through the numFilter to make sure we have all numbers
    numFilter(formField, fieldLabel, "################")
    strValue = GetObjValue(formField)
    if (!allDigits(strValue, false)){
      msg += "--- "+fieldLabel+" must be all numbers.\n"
    }
    //Needs to pass the Luhn check and certain other criteria
    var ccTypeDD = document.frmUserInfo.Payment_Type
    if (!LuhnCheck(strValue) || !validateCCNum(ccTypeDD.options[ccTypeDD.selectedIndex].text, strValue)){
      msg += "--- "+fieldLabel+" entered is invalid\n"
    }
  }
  
  return msg
}

function valHowHeard(hhDD, hhTB){
	var rtnMsg = ""
	if (hhDD.selectedIndex <= 0 || hhDD.selectedIndex == 4 || hhDD.selectedIndex == 13){
		rtnMsg +=  "--- 'How you heard of us' selection not valid.\n"
	}
	if (hhDD.value.indexOf("Other") > -1 && isBlank(hhTB.value)){
		rtnMsg +=  "--- Please specify the 'other' way you heard of us.\n"
	}
	return rtnMsg
}

function validateForm(theForm){
  //If the clearForm flag has been set, return true
  //if (clearForm) { return true }
  
  var haveItems = false
  var qtysNumeric = true
  var msg = ""
  var phoneMsg = ""
  var ctls = theForm.elements
  
  with (theForm){
    //CONTACT INFORMATION
    msg += validateField(Contact_FirstName, "Contact First Name", 1, 15, true)
    msg += validateField(Contact_LastName, "Contact Last Name", 2, 30, true)
    msg += validateField(Contact_StreetAddress, "Contact Street Address", 5, 50, true)
    msg += validateField(Contact_City, "Contact City", 2, 50, true)
    msg += validateField(Contact_State, "Contact State", 0, 0, true)
    msg += validateField(Contact_ZipCode,"Contact Zip Code", 0, 0, true)
    msg += validateField(Contact_Country,"Contact Country", 0, 0, true)
    //Check the phone numbers separately.  We need only one.
    phoneMsg += validateField(Contact_Day_Phone, "Contact Day Phone", 12, 12, false)
    phoneMsg += validateField(Contact_Evening_Phone, "Contact Evening Phone", 12, 12, false)
    if (isBlank(Contact_Day_Phone.value) && isBlank(Contact_Evening_Phone.value)){
      msg += "--- Please enter at least one phone number.\n"
    }else if (!isBlank(phoneMsg)){
      msg += phoneMsg //"--- Please enter at least one phone number.\n" 
    }
    msg += validateField(Contact_Email, "Contact Email", 6, 60, true)
    msg += valHowHeard(Contact_How_Heard_About, Contact_How_Heard_About_Other)
    
    //SHIPPING INFORMATION
    msg += validateField(Shipping_FirstName, "Shipping First Name", 1, 15, false)
    msg += validateField(Shipping_LastName, "Shipping Last Name", 2, 30, false)
    msg += validateField(Shipping_StreetAddress, "Shipping Address", 5, 50, false)
    msg += validateField(Shipping_City, "Shipping City", 2, 50, false)
    msg += validateField(Shipping_State, "Shipping State", 0, 0, false)
    msg += validateField(Shipping_ZipCode,"Shipping Zip Code", 0, 0, false)
    msg += validateField(Shipping_Country,"Shipping Country", 0, 0, false)
    
    
    //BILLING INFORMATION
    msg += validateField(Payment_Type,"Payment Type", 0, 0, true)
    
    switch (Payment_Type.selectedIndex) {
      case 1:
      case 2:
      case 3:
        msg += validateField(CC_Number, "Credit Card Number", 0, 0, true)
        msg += validateField(CC_Code, "Card Code", 3, 4, false)
        if (!validateCCExpDate(CC_Exp_Month.options[CC_Exp_Month.selectedIndex].text, CC_Exp_Year.options[CC_Exp_Year.selectedIndex].text)){
           msg += "--- Please select a valid expiration date for your credit card.\n"
        }
        msg += validateField(CC_Name_On_Card,"Name On Card", 2, 50, true)
        break
      case 4:
        msg += validateField(PayPal_Email, "PayPal Acct Email", 6, 60, true)
        break
      case 5:
        msg += validateField(Gift_Cert_Number, "Gift Cert Number", 6, 60, true)
        break
    }
    /*
    if (Payment_Type.selectedIndex < 3 && Payment_Type.selectedIndex > 0) {
      msg += validateField(CC_Number, "Credit Card Number", 0, 0, true)
      msg += validateField(CC_Code, "Card Code", 3, 4, false)
      if (!validateCCExpDate(CC_Exp_Month.options[CC_Exp_Month.selectedIndex].text, CC_Exp_Year.options[CC_Exp_Year.selectedIndex].text)){
         msg += "--- Please select a valid expiration date for your credit card.\n"
      }
      msg += validateField(CC_Name_On_Card,"Name On Card", 2, 50, true)
    }else{
      msg += validateField(PayPal_Email, "PayPal Acct Email", 6, 60, true)
    }
    */
    msg += validateField(CC_Billing_Address,"Billing Address", 5, 50, false)
    msg += validateField(CC_Billing_City, "Billing City", 2, 50, false)
    msg += validateField(CC_Billing_State, "Billing State", 0, 0, false)
    msg += validateField(CC_Billing_Zip,"Billing Zip Code", 0, 0, false)
  } //with

  if (isBlank(msg)){
    return true
  }else{
    msg = "Before continuing, the following items must be corrected:\n\n" + msg
    alert(msg)
    return false
  }
}

function validateContact(theForm){
  var msg = ""
  with (theForm){
    msg += validateField(Name, "Name", 1, 256, true)
    msg += validateField(Email, "Email", 1, 256, true)
    msg += validateField(Comments, "Comments", 0, 0, true)
	}
  if (isBlank(msg)){
    return true
  }else{
    msg = "Before continuing, the following items must be corrected:\n\n" + msg
    alert(msg)
    return false
  }
}
