
function validate(o) {

  if (validate.arguments.length > 0) {
  	disableForm(o);
    
    fieldNames = o.fieldNames.value.split(",");
    fieldTypes = o.fieldTypes.value.split(",");
    fieldReqs  = o.fieldReqs.value.split(",");
    fieldDesc  = o.fieldDesc.value.split(",");
    var valid  = new Array(fieldNames.length);
    var errMsg = new Array(fieldNames.length);
    var errMsg = new String();
    
    if (fieldNames.length != fieldTypes.length ||
        fieldTypes.length != fieldReqs.length ||
        fieldReqs.length  != fieldDesc.length) {
      alert('Form validation not propertly configured.');
      return false;
    }
    
    for (i=0; i<fieldNames.length; i++) {
      if (fieldTypes[i].substr(0,10) == String("type_list_") || o[fieldNames[i]].value.length > 0) {
        valid[i] = true;
        
        switch (fieldTypes[i].toLowerCase()) {
          case 'type_email':
            if (! isEmail(o[fieldNames[i]].value)) {
              valid[i] = false;
              errMsg += fieldDesc[i] + ': You must enter a valid email address\n';
              flagField(o[fieldNames[i]]);              
            }
            break;
            
          case 'type_int':
          case 'type_integer':
            if (parseInt(o[fieldNames[i]].value) != parseFloat(o[fieldNames[i]].value)) {
              valid[i] = false;
              errMsg += fieldDesc[i] + ': You must enter a number\n';
              flagField(o[fieldNames[i]]);
            }
            break;
          case 'type_float':
            if (isNaN(o[fieldNames[i]].value)) {
              valid[i] = false;
              errMsg += fieldDesc[i] + ': You must enter a number\n';
              flagField(o[fieldNames[i]]);              
            }
            break;
          case 'type_date':
            break;
          case 'type_zip':
            break;
          case 'type_url':
            break;
          case 'type_phone':
          	if (o[fieldNames[i]].value.length < 10) {
          		valid[i] = false;
          		errMsg += fieldDesc[i] + ': You must enter a valid phone number, with area code\n';
          		flagField(o[fieldNames[i]]);
          	}
            break;
          case 'type_cc':
            break;
        }
      } else {
        if (fieldReqs[i] > 0) {
          valid[i] = false;
          errMsg += fieldDesc[i] + ': This is a required field\n';
          flagField(o[fieldNames[i]]);          
        }
      }
      
      if (valid[i]) {
        unFlagField(o[fieldNames[i]]);
      }
    }
  }

  if (errMsg.length > 0) {
    alert(errMsg);
	  enableForm(o);  
    return false;
  } else {
    return true;
  }
}

function disableForm(o) {
	for(var i=0;i<o.elements.length;i++) {
		if (o.elements[i].type == "submit") {
			submitButtonCaption = o.elements[i].value;
			o.elements[i].value = "loading...";
			o.elements[i].disabled = true;
		}
	}
}

function enableForm(o) {
	for(var i=0;i<o.elements.length;i++) {
		if (o.elements[i].type == "submit") {
			o.elements[i].value = submitButtonCaption;
			o.elements[i].disabled = false;
		}	
	}
}	

function flagField(f) {
  f.style.border = '2px solid';
  f.style.background = '#FDFFEA';
}

function unFlagField(f) {
  f.style.border = '';
  f.style.background = '#FFFFFF';  
}

function isEmail(str) {
  var pattern = /\s*\w+@[^\.]+\.[^\.]+(\.[^\.])*\s*/;
  legalChars = "~0123456789.-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_@+";

  if(!pattern.test(str)) {
    return false;
  }
  
  //This enhances the previous EMail check. This checks for legal values and returns illegal values
  for(x=0; x < str; x++) {
    if (legalChars.indexOf(str.substring(x,x+1)) < 0) {
      return false;
    }
  }
  
  return true;
}
  
  
  
function oldfunction() {
  // DATA VALIDATION

   var pattern = /\s*\w+@[^\.]+\.[^\.]+(\.[^\.])*\s*/;
   var letters = /[a-zA-Z]/;
   var numbers = /[0-9]/;
   legalChars = "~0123456789.-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_@+";
   alphaNums = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  ERR_MSG = "";

  with(document.main) {
  
  formatCC(account_number);
  
    /***************** ERROR CHECKING *******************************/
  if (billing_full_name.value.length < 2)   ERR_MSG += "\nPlease fill in your Billing Name";
  if (billing_company.value.length < 2)   ERR_MSG += "\nPlease fill in your Billing Company";
  if (billing_address.value.length < 2)   ERR_MSG += "\nPlease fill in your Billing Address";
  if (billing_city.value.length < 2)    ERR_MSG += "\nPlease fill in your Billing City";
  if (BILLING_STATE.value.length < 2)     ERR_MSG += "\nPlease select your Billing State";
  if (billing_phone.value.length < 10)    ERR_MSG += "\nBilling Phone must be at least 10 numbers";
  if (billing_postal_code.value.length < 5)   ERR_MSG += "\nBilling Zip Code must be at least 5 numbers";
  if (billing_country.value.length < 2)     ERR_MSG += "\nPlease fill in your Billing Country";
  /******* EMAIL VALIDATION *********/
  if (billing_email.value.length < 7)
    ERR_MSG += "\nBilling E-Mail address must be at least 7 characters";
  if (billing_email.value != "") {
      if(!pattern.test(billing_email.value))  ERR_MSG += "\nInvalid Billing E-Mail Address."
  }
  //This enhances the previous EMail check. This checks for legal values and returns illegal values
  if (billing_email.value != "" && billing_email.value.length > 1) {
      for(x=0; x < billing_email.value.length; x++) {
    if (legalChars.indexOf(billing_email.value.substring(x,x+1)) < 0)
        ERR_MSG += "\n" + "Illegal character '"+billing_email.value.substring(x,x+1)+"' at position " +(x+1)+ " in Billing E-Mail Address.";
      }
  }
  /******* END EMAIL VALIDATION ***********/

  if (!same_as_billing.checked) {
      if (shipping_full_name.value.length < 2)  ERR_MSG += "\nPlease fill in your Shipping Attention";
      if (shipping_company.value.length < 2)  ERR_MSG += "\nPlease fill in your Shipping Company";
      if (shipping_address.value.length < 2)  ERR_MSG += "\nPlease fill in your Shipping Address";
      if (shipping_city.value.length < 2)   ERR_MSG += "\nPlease fill in your Shipping City";
      if (SHIPPING_STATE.value.length < 2)  ERR_MSG += "\nPlease select your Shipping State";
      if (shipping_phone.value.length < 10) ERR_MSG += "\nShipping Phone must be at least 10 numbers";
      if (shipping_postal_code.value.length < 5)  ERR_MSG += "\nShipping Zip Code must be at least 5 numbers";
      if (shipping_country.value.length < 2)  ERR_MSG += "\nPlease fill in your Shipping Country";
      /******* EMAIL VALIDATION *********/
      if (shipping_email.value.length < 7)
        ERR_MSG += "\nShipping E-Mail address must be at least 7 characters";
      if (shipping_email.value != "") {
          if(!pattern.test(shipping_email.value)) ERR_MSG += "\nInvalid Shipping E-Mail Address."
      }
      //This enhances the previous EMail check. This checks for legal values and returns illegal values
      if (shipping_email.value != "" && shipping_email.value.length > 1) {
          for(x=0; x < shipping_email.value.length; x++) {
        if (legalChars.indexOf(shipping_email.value.substring(x,x+1)) < 0)
            ERR_MSG += "\n" + "Illegal character '"+shipping_email.value.substring(x,x+1)+"' at position " +(x+1)+ " in Shipping E-Mail Address.";
          }
      }
      /******* END EMAIL VALIDATION ***********/
  }

  if (payment_method.selectedIndex==0)  ERR_MSG += "\nPlease enter your payment method";
  else
  if (payment_method.selectedIndex==1 | payment_method.selectedIndex==2 | payment_method.selectedIndex==3)
  {
    validate(document.main);
    if (account_number.value.length < 14)   ERR_MSG += "\nPlease enter your account number";
    if (validation_code.value.length < 3)   ERR_MSG += "\nPlease enter your validation code";
    if (name_on_card.value.length < 2)  ERR_MSG += "\nPlease enter your name on card";
  }
/*********************/

  if (!confirm_order.checked)   ERR_MSG += "\nPlease mark the checkbox at the bottom of the page to accept \n Freund's Terms and Conditions and to submit your order";

    if(ERR_MSG.length > 0) {
  alert(ERR_MSG);
  return false;
    }
    /********************* PASSED ERROR CHECK *********************************/
} //END WITH

//return false;
return true;
}


function GetInt(innum) {
  if (isNaN(parseInt(innum)))
  return 0;
  return parseInt(innum);
}
function GetFloat(innum) {
  if (isNaN(parseFloat(innum)))
  return 0;
  return parseFloat(innum);
}
function FormatNumber(innum) {
  tempNum = "00" + Math.round(innum*100);
  tempNum2 = tempNum.substring(tempNum.length-2,tempNum.length)
  tempNum = "$ " + parseInt(innum) + "." + tempNum2
  return tempNum;
}

function CalculateTotals() {
  with(document.main) {
  Q1 = GetInt(quantity_1.value);
  Q2 = GetInt(quantity_2.value);
  Q3 = GetInt(quantity_3.value);
  Q4 = GetInt(quantity_4.value);
  Q5 = GetInt(quantity_5.value);
  Q6 = GetInt(quantity_6.value);

  P1 = GetFloat(price_1.value);
  P2 = GetFloat(price_2.value);
  P3 = GetFloat(price_3.value);
  P4 = GetFloat(price_4.value);
  P5 = GetFloat(price_5.value);
  P6 = GetFloat(price_6.value);

  subtotal_1.value = FormatNumber(Q1 * P1);
  subtotal_2.value = FormatNumber(Q2 * P2);
  subtotal_3.value = FormatNumber(Q3 * P3);
  subtotal_4.value = FormatNumber(Q4 * P4);
  subtotal_5.value = FormatNumber(Q5 * P5);
  subtotal_6.value = FormatNumber(Q6 * P6);

  TempSubtotal     = (Q1 * P1) + (Q2 * P2) + (Q3 * P3) + (Q4 * P4) + (Q5 * P5) + (Q6 * P6);
  subtotal.value   = FormatNumber(TempSubtotal);

  //' CALCULATE DISCOUNT AND TOTALS
  if (TempSubtotal >= 5000) {
    discount.value = "Call for Pricing";
    total.value = "Call for Pricing";
  } else {
    discount.value = "";
    TempDiscount = 0;

    if (TempSubtotal >= 1250)   { TempDiscount = 12.5; discount.value = "12.5%"}
    else if (TempSubtotal >= 1000)  { TempDiscount = 10;  discount.value = "10%"}
    else if (TempSubtotal >= 500) { TempDiscount = 5;  discount.value = "5%"}

    total.value = FormatNumber(TempSubtotal * (1 - TempDiscount/100));
  }
  } //END WITH
}

//MAIN FUNCTION: validate()

/********************************
Currently expects the following (feel free to change)

form name=signupForm
Fields:
  CardType (selectable)
  CardNumber
  ExpireYear (selectable)
  ExpireMonth (selectable)
***********************************/

function validateOld  (o) {
  today = new Date();
  curMonth = today.getMonth()+1;
  curYear  = today.getYear();

  var ccardNum = o.account_number.value;
  var ccardName = o.payment_method.options[o.payment_method.selectedIndex].value;
  if (ccardNum.search(/\S/) < 0) {
    ERR_MSG += "\nPlease enter your credit card number.";
    return false;
  } else if (ccardNum.search(/\D/) >= 0) {
    ERR_MSG += "\nPlease enter a valid credit card number.";
    return false;
  } else if (!validateCCard(ccardName, ccardNum)) {
    ERR_MSG += "\nPlease enter a valid credit card number.";
    return false;
  }
    
  if (o.expire_month.selectedIndex == 0 || o.expire_year.selectedIndex == 0) {
    ERR_MSG += "\nPlease enter you credit card expiration date.";
    return false;
  } else {
    var month = parseInt(o.expire_year.options[o.expire_month.selectedIndex].value, 10);
    var year = parseInt(o.expire_year.options[o.expire_year.selectedIndex].text, 10);
    if (year < curYear || (year == curYear && month < curMonth)) {
      ERR_MSG += "\nThis credit card has expired.";
      return false;
    }
  }

  return true;
}

function formatCC(o) {
  ccnum = o.value;
  
  ccnum = ccnum.replace(/\D+/g, "");
  o.value = ccnum;
}

function validateCCard(card, ccnumber) {
  var type = card;
  var number = ccnumber;
  var valid = true;
    
  if (type == "Amex") {
    if (number.length != 15)
      valid = false;
    else if (number.search(/^3[47]/) < 0)
      valid = false;
  } else if (type == "Discover") {
    if (number.length != 16)
      valid = false;
    else if (number.search(/^6011/) < 0)
      valid = false;
  } else if (type == "MC") {
    if (number.length != 16)
      valid = false;
    else if (number.search(/^5[1-5]/) < 0)
      valid = false;
  } else if (type == "Visa") {
    if (number.length != 13 && number.length != 16)
      valid = false;
    else if (number.search(/^4/) < 0)
      valid = false;
  } else {
      valid = false;
  }

  if (valid)
    valid = mod10check(number);

  return valid;
}

function mod10check(number) {
  var evenSum=0;
  var oddSum=0;
  for (i = (number.length-1); i >= 0; i--) {
    oddSum += parseInt(number.substr(i,1));
    i--;
    if (i>=0) {
      var even=parseInt(number.substr(i,1));
      even = even * 2;
      if (even >= 10) {
        even = "" + even;
        even = parseInt(even.substr(0,1)) + parseInt(even.substr(1,1));
      }
      evenSum += even;
    }
  }
  var sum = oddSum + evenSum;
    
  if (sum % 10 == 0)
    return true;
  else
    return false;
}

