//Does initial card number validation before Luhn Check
function validateCCNum(cardType, cardNum){
	//alert("Incoming cardType is: "+cardType+"\nIncoming cardNum is: "+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
  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
  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.frmOrder.CC_Type.selectedIndex >= 1){
    //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.frmOrder.CC_Type
    if (!LuhnCheck(strValue) || !validateCCNum(ccTypeDD.options[ccTypeDD.selectedIndex].text, strValue)){
      msg += "--- "+fieldLabel+" entered is invalid\n"
    }
  }
  
  return msg
}

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
  //Go thru the first 13 fields to make sure user is really ordering something
  for (var i = 0; i < 17; i++){
    //If it's a textbox
    if (ctls[i].type.toLowerCase() == "text"){
      //If something is entered
      if (!isBlank(ctls[i].value)){
        haveItems = true
        //Make sure it's all numeric
        if (isNaN(ctls[i].value)) { qtysNumeric = false }
        //If it's the RAM2 24VDC, check the housing
        if (ctls[i].name.indexOf("RAM_2_24VDC") > -1 && theForm.RAM_2_24VDC_HOUSING.selectedIndex < 1){
          msg += "--- Please select a housing type for your RAM II 24 VDC.\n"
        }
      }
    }
  } //for (var i = 0; i < 13; i++)
  //If there are no items ordered, show an error and get out.
  if (!haveItems) {
    msg += "--- No items ordered.  Please enter a quantity for an item or items to order.\n"
  }else if (!qtysNumeric){
    msg += "--- Please enter only numeric values in Qty fields.\n"
  }
  
  with (theForm){
    //CONTACT INFORMATION
    msg += validateField(Contact_Name, "Contact Name", 1, 50, true)
    msg += validateField(Contact_Address1, "Contact Address 1", 5, 50, true)
    msg += validateField(Contact_Address2, "Contact Address 2", 5, 50, true)
    msg += validateField(Contact_City, "Contact City", 5, 30, true)
    msg += validateField(Contact_State, "Contact State", 0, 0, true)
    msg += validateField(Contact_ZipCode,"Contact Zip Code", 5, 5, 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)
    
    //SHIPPING INFORMATION
    msg += validateField(Shipping_Name, "Shipping Name", 1, 50, false)
    msg += validateField(Shipping_Address1, "Shipping Address 1", 5, 50, false)
    msg += validateField(Shipping_Address2, "Shipping Address 2", 5, 50, false)
    msg += validateField(Shipping_City, "Shipping City", 5, 30, false)
    msg += validateField(Shipping_State, "Shipping State", 0, 0, false)
    msg += validateField(Shipping_ZipCode,"Shipping Zip Code", 5, 5, false)
    
    
    //BILLING INFORMATION
    msg += validateField(CC_Type,"Credit Card Type", 0, 0, true)
    msg += validateField(CC_Number, "Credit Card Number", 0, 0, true)
    msg += validateField(CC_Expire, "Credit Card Exp Date", 4, 4, true)
    msg += validateField(CC_Code, "Card Code", 3, 4, false)
    msg += validateField(CC_Name_On_Card,"Name On Card", 5, 50, true)
    msg += validateField(CC_Billing_Address1,"Billing Address 1", 5, 50, false)
    msg += validateField(CC_Billing_Address2,"Billing Address 2", 5, 50, false)
    msg += validateField(CC_Billing_City, "Billing City", 5, 30, false)
    msg += validateField(CC_Billing_State, "Billing State", 2, 20, false)
    msg += validateField(CC_Billing_ZipCode,"Billing Zip Code", 5, 5, 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 validateRegForm(theForm){
  var msg = ""
  
  with (theForm){
    msg += validateField(Purchase_Date, "Purchase_Date", 0, 0, true)
    msg += validateField(Model_Number, "Model_Number", 0, 0, true)
    msg += validateField(Serial_Number, "Serial_Number", 0, 0, true)
    msg += validateField(Customer_Name, "Customer_Name", 0, 0, true)
    msg += validateField(Customer_Address1, "Customer_Address1", 0, 0, true)
    msg += validateField(Customer_City, "Customer_City", 0, 0, true)
    msg += validateField(Customer_State, "Customer_State", 0, 0, true)
    msg += validateField(Customer_ZipCode, "Customer_ZipCode", 0, 0, true)
    msg += validateField(Customer_Phone, "Customer_Phone", 0, 0, true)
    msg += validateField(Installer_Name, "Installer_Name", 0, 0, true)
    msg += validateField(Installer_Address1, "Installer_Address1", 0, 0, true)
    msg += validateField(Installer_City, "Installer_City", 0, 0, true)
    msg += validateField(Installer_State, "Installer_State", 0, 0, true)
    msg += validateField(Installer_ZipCode, "Installer_ZipCode", 0, 0, true)
    msg += validateField(Installer_Phone, "Installer_Phone", 0, 0, true)
    msg += validateField(From, "Email", 0, 0, true)
  }
  
  if (isBlank(msg)){
    return true
    //alert("All OK, would be submitting form.")
    //return false
  }else{
    msg = "The following items need attention before the form can be submitted:\n\n"+msg
    alert(msg)
    return false
  }
  
}
