var preError = "The following errors have been found:\n------------------------------------\n";
var shipError = "Did you want to SHIP TO your billing address? If YES please\ncheck the \"SHIPPING SAME AS BILLING\" box!\n\nOtherwise, ";
var errorString = "";
var postError = "------------------------------------\nPlease correct these errors and re-submit.";
var errorNumber = 0;
var errorNumDot = ". ";
var chkShip = false;

function addGiftBox(value) {
	if (value == "yes") {
		var qty = document.notecardForm.ncGiftBoxQty.value;
		if (qty == "" || isNaN(qty)) {
			alert('Please enter an appropriate value.');
		} else {
			document.notecardForm.addGiftBox.value = "yes";
			document.notecardForm.submit();
		}
	} else if (value == "no") {
		document.notecardForm.addGiftBox.value = "no";
		document.notecardForm.submit();
	}
}
function returnCustomer() {
	errorString = "";
	errorNumber = 0;
	var emailAddress = document.returnCustomerForm.returnEmailAddress.value;
	if (checkEmail(emailAddress)) {
		document.returnCustomerForm.isReturn.value = "yes";
		document.returnCustomerForm.submit();
	} else {
		alert(preError + errorString + postError);
	}
}
function checkCustomer() {
	errorString = "";
	errorNumber = 0;
	var preError = "Please fill out:\n\n";
	var firstName = document.customerInfoForm.billing_first_name.value;
	var lastName = document.customerInfoForm.billing_last_name.value;
	var address = document.customerInfoForm.billing_address_1.value;
	var zipCode = document.customerInfoForm.billing_postal_code.value;
	var city = document.customerInfoForm.billing_city.value;
	var stateIndex = document.customerInfoForm.billing_state_id.selectedIndex;
	var state = document.customerInfoForm.billing_state_id.options[stateIndex].value;
	var countryIndex = document.customerInfoForm.billing_country.selectedIndex;
	var country = document.customerInfoForm.billing_country.options[countryIndex].value;
	var phone = document.customerInfoForm.billing_phone.value;
	var emailAddress = document.customerInfoForm.billing_email.value;
	var emailAddress2 = document.customerInfoForm.check_email.value;
	var chkpo = false;
	chkShip = false;
	if (document.customerInfoForm.shipping_checkbox.checked) {
		chkpo = true;
	}
	if (checkNames(firstName,lastName) && checkAddress(address,city,zipCode,state,countryIndex,chkpo) && checkNumbers(phone) && checkEmail(emailAddress) && compareEmail(emailAddress, emailAddress2)) {
		var firstName = document.customerInfoForm.shipping_first_name.value;
		var lastName = document.customerInfoForm.shipping_last_name.value;
		var address = document.customerInfoForm.shipping_address_1.value;
		var zipCode = document.customerInfoForm.shipping_postal_code.value;
		var city = document.customerInfoForm.shipping_city.value;
		var stateIndex = document.customerInfoForm.shipping_state_id.selectedIndex;
		var state = document.customerInfoForm.shipping_state_id.options[stateIndex].value;
		var countryIndex = document.customerInfoForm.shipping_country.selectedIndex;
		var country = document.customerInfoForm.shipping_country.options[countryIndex].value;
		var chkpo = true;
		if (document.customerInfoForm.shipping_checkbox.checked) {
			chkpo = false;
		}
		chkShip = true;
		if (checkNames(firstName,lastName) && checkAddress(address,city,zipCode,state,countryIndex,chkpo)) {
			document.customerInfoForm.submit();
		} else {
			alert(shipError + preError + errorString + postError);
		}
	} else {
		alert(preError + errorString + postError);
	}
}
function purchase() {
	var monthIndex = document.orderForm.event_month.selectedIndex;
		var month = document.orderForm.event_month.options[monthIndex].value;
	var dayIndex = document.orderForm.event_day.selectedIndex;
		var day = document.orderForm.event_day.options[dayIndex].value;
	var yearIndex = document.orderForm.event_year.selectedIndex;
		var year = document.orderForm.event_year.options[yearIndex].value;

	if (checkDateNeeded(month,day,year)) {
		if (month == "noneChosen" || day == "noneChosen" || year == "noneChosen") {
			document.orderForm.date_needed.value = "";
		} else {
			document.orderForm.date_needed.value = year + "-" + month + "-" + day;
		}
		document.orderForm.purchase.value = "yes";
		document.orderForm.submit();
	} else {
		alert(preError + errorString + postError);
	}
}
function checkCardInfo(value) {
	if (confirm("Are you sure you want to make a purchase? If yes click OK, if not then simply click Cancel to stop the purchase.")) {

		errorString = "";
		errorNumber = 0;
		var ocheckout = (document.PaymentInfo.submit_paypal.value == "yes" || document.PaymentInfo.submit_google.value == "yes") ? true:false;
		var gcNumber1 = document.PaymentInfo.gc_number1.value;
		var gcNumber2 = document.PaymentInfo.gc_number2.value;
		var acc_name = document.PaymentInfo.acc_name.value;
		var acc_routing = document.PaymentInfo.acc_routing.value;
		var acc_number = document.PaymentInfo.acc_number.value;
		var terms = document.PaymentInfo.terms.checked ? true:false;
/*	var ccName = document.PaymentInfo.cc_name.value; */
		var ccNumber = document.PaymentInfo.cc_number.value;
		var ccVerifyNum = document.PaymentInfo.cc_verify_number.value;
		var ccMonth = document.PaymentInfo.cc_expire_month.value;
		var ccYear = document.PaymentInfo.cc_expire_year.value;

		if (!((gcNumber1.length == 0 && gcNumber2.length == 0) || (gcNumber1.length == 4 && gcNumber2.length == 4))) {
			var errors = true;
			errorNumber++;
			errorString += errorNumber + errorNumDot + "Please fill out gift certficate code completely or leave each one blank.\n";
			alert(preError + errorString + postError);
			return;
		}

//	if (document.PaymentInfo.shipping_checkbox.checked) {
/*		if (checkCreditCard(ccNumber,ccName)) { */ 
		var gcempty = (gcNumber1.length == 0 && gcNumber2.length == 0) ? true:false;
		var chempty = (acc_name.length == 0 && acc_routing.length == 0 && acc_number.length == 0) ? true:false;
		var ccempty = (ccNumber.length == 0 && ccVerifyNum.length == 0) ? true:false;
		if (gcempty && chempty && ccempty && !ocheckout) {
			var errors = true;
			errorNumber++;
			errorString += errorNumber + errorNumDot + "Please fill out checking account info, credit card info and/or gift certificate info or select an alternate payment method.\n";
			alert(preError + errorString + postError);
			return;
		}
		if (!chempty && !ccempty) {
			var errors = true;
			errorNumber++;
			errorString += errorNumber + errorNumDot + "Please only fill out checking account info or credit card info, but not both.\n";
			alert(preError + errorString + postError);
			return;
		}
		if (ocheckout && (!chempty || !ccempty)) {
			var errors = true;
			errorNumber++;
			errorString += errorNumber + errorNumDot + "Do not fill out checking account info or credit card info if using Paypal or Google Checkout.\n";
			alert(preError + errorString + postError);
			return;
		}
		var gcok = (gcNumber1.length == 4 && gcNumber2.length == 4) ? true:false;
		if (value == "no" || ocheckout || (gcok && chempty && ccempty) || (!chempty && checkCheck(acc_name,acc_routing,acc_number,terms)) || (!ccempty && checkCreditCard(ccNumber))) {
			document.getElementById('ccLink').disabled = true;
			document.getElementById('ccLink').onclick = new Function("return false;");
			document.getElementById('processButton').style.display = 'none';
			document.getElementById('processing').style.display = 'block';
			document.PaymentInfo.submit();
		} else {
			alert(preError + errorString + postError);
		}

	}
}
/* #################### check form fields #################### */
function checkDateNeeded(month,day,year) {
	errorString = "";
	errorNumber = 0;
	var errors = false;
	if (
		(month == "noneChosen" && (day != "noneChosen" || year != "noneChosen")) ||
		(day == "noneChosen" && (month != "noneChosen" || year != "noneChosen")) ||
		(year == "noneChosen" && (month != "noneChosen" || day != "noneChosen"))
		) {
		var errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "Please fill out date completely or leave each one blank.\n";
	}

	if (errors) {
		return false;
	} else {
		return true;
	}

}
function checkNames(first,last) {
	if (chkShip) {
		shipto = "SHIP TO ";
	} else {
		shipto = "BILLING ";
	}
	var errors = false;
	if (first == "") {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + shipto + "First name\n";
	}
	if (last == "") {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + shipto + "Last name\n";
	}
	if (errors) {
		return false;
	} else {
		return true;
	}
}

var regexObj = {
	canada 		: /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]( )?\d[ABCEGHJKLMNPRSTVWXYZ]\d$/i , //i for case-insensitive
	usa    		: /^\d{5}(-\d{4})?$/ 
}
function checkAddress(address,city,zip,state,countryIndex,chkpo) {
	if (chkShip) {
		shipto = "SHIP TO ";
	} else {
		shipto = "";
	}
	var errors = false;
	if (address == "") {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + shipto + "Street Address line 1.\n";
	} else {
		if (chkpo) {
			if (address.substring(0,3).toUpperCase() == "PO " || 
			address.substring(0,2).toUpperCase() == "P."  || 
			address.substring(0,2).toUpperCase() == "P "  || 
			address.substring(0,4).toUpperCase() == "BOX " ||
			address.substring(0,4).toUpperCase() == "POB " ||
			address.substring(0,5).toUpperCase() == "POBOX" ||
			address.substring(0,5).toUpperCase() == "POST " ||
			address.substring(0,4).toUpperCase() == "APO " ||
			address.substring(0,4).toUpperCase() == "ASU ") {
				errors = true;
				errorNumber++;
				errorString += errorNumber + errorNumDot + "Street Address line 1.\nNOTE: PO Boxes are NOT ALLOWED.\n";
	    }
	  }
  }
	if (city == "") {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot +shipto +  "City\n";
	}
	if (zip == "") {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + shipto + "Zip or Postal code\n";
	} else {
		if (countryIndex < 2) {
			if (countryIndex == 1) {
				var regexp = new RegExp(regexObj.canada);
			} else {
				var regexp = new RegExp(regexObj.usa);
			}
			if (!regexp.test(zip)) {
				errors = true;
				errorNumber++;
				errorString += errorNumber + errorNumDot + shipto + "Zip or Postal code is invalid\n";
			}
		}
	}
	if (countryIndex < 2 && state == "") {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + shipto + "State or Province\n";
	}
	if (errors) {
		return false;
	} else {
		return true;
	}
}
function checkNumbers(phone,fax) {
	var errors = false;
	if (phone == "") {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "Billing Phone number\n";
	}
//	if (fax != null) {
//		if (fax == "") {
//		errors = true;
//		errorNumber++;
//		errorString += errorNumber + errorNumDot + "Fax number was not entered.\n";
//		}
//	}
	if (errors) {
		return false;
	} else {
		return true;
	}
}
function compareEmail(emailAddress, emailAddress2) {
	if (emailAddress != emailAddress2) {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "The Email addresses you entered do not match!\n";
		return false;
	}
	return true;
}
function checkEmail(emailAddress) {
	var errors = false;
	var theAt = emailAddress.indexOf("@");
	var theDot = emailAddress.lastIndexOf(".");
	var aSpace = emailAddress.indexOf(" ");
	var illegalChar = false;
	var theChar = "";
	var illegalChars = "!#$%^&*()/:;,+";
	/* check if address exists */
	if (emailAddress == "") {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "Please enter your Email address\n";
	} else
	/* check the formatting */
	if ((theAt == -1) || (theAt == 0) || (theDot == -1) || (theDot < theAt + 1) || (theDot > emailAddress.length - 1) || (aSpace != -1)) {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "The Email address you entered is formatted wrong!\n";
	} else {
	/* check for illegal characters */
		for (x = 0; x < illegalChars.length; x++) {
			theChar = illegalChars.charAt(x);
			if (emailAddress.indexOf(theChar) != -1) {
				illegalChar = true;
			}
		}
		if (illegalChar == true) {
			errors = true;
			errorNumber++;
			errorString += errorNumber + errorNumDot + "The Email address you entered contains illegal characters!\n";
		}
	}
	if (errors) {
		return false;
	} else {
		return true;
	}
}
/*function checkCreditCard(ccNumber,ccName) { */
function checkCreditCard(ccNumber) {
	var errors = false;
//	if (ccName == "") {
//		errors = true;
//		errorNumber++;
//		errorString += errorNumber + errorNumDot + "Please enter the name on the credit card.\n";
//	}

	if (ccNumber == "") {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "Please enter a credit card number.\n";
	} else if (ccNumber.length < 15 || isNaN(ccNumber)) {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "Credit card number is not in the right format.\n";
	}

//	if (document.PaymentInfo.cc_cvv_indicator[0].checked) {
		if (document.PaymentInfo.cc_verify_number.value == "" || isNaN(document.PaymentInfo.cc_verify_number.value)) {
			errors = true;
			errorNumber++;
			errorString += errorNumber + errorNumDot + "Please enter a valid credit card verification number.\n";
		}
//	}

	var cardType = ccNumber.charAt(0);
	if (cardType > 6 || cardType < 3) {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "Sorry, but we can only accept Visa, MasterCard, Discover or American Express credit cards.\n";
	}

	if (errors) {
		return false;
	} else {
		return true;
	}
}
function chgyr() {
	var ccMonth = document.PaymentInfo.cc_expire_month.value;
	var ccYear = document.PaymentInfo.cc_expire_year.value;
	var now = new Date();
	var month = now.getMonth() + 1;
	var year = now.getFullYear();
	if (ccMonth < month && ccYear == year) {
		document.PaymentInfo.cc_expire_year.selectedIndex += 1;
	}
}
function checkABA(s) {

  var i, n, t;
  // First, remove any non-numeric characters.
  t = "";
  for (i = 0; i < s.length; i++) {
    c = parseInt(s.charAt(i), 10);
    if (c >= 0 && c <= 9)
      t = t + c;
  }

  // Check the length, it should be nine digits.
  if (t.length != 9)
    return false;

  // Now run through each digit and calculate the total.
  n = 0;
  for (i = 0; i < t.length; i += 3) {
    n += parseInt(t.charAt(i),     10) * 3
      +  parseInt(t.charAt(i + 1), 10) * 7
      +  parseInt(t.charAt(i + 2), 10);
  }

  // If the resulting sum is an even multiple of ten (but not zero),
  // the aba routing number is good.
  if (n != 0 && n % 10 == 0)
    return true;
  else
    return false;
}

function validateABA(s) {
  if (checkABA(s))
     return true;
  else
    alert("Please ensure your 9 digit bank routing number has been entered correctly.");
  return false;
}
function checkCheck(acc_name,acc_routing,acc_number,terms) {
	var errors = false;
	if (!terms) {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "You must check the AUTHORIZE THIS CHECK box in order to proceed.\n";
	}
	if (!(acc_name.length > 0)) {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "Bank name was not entered.\n";
	}
	if (!(acc_number.length > 0)) {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "Bank Account number was not entered.\n";
	}
  if (!checkABA(acc_routing)) {
		errors = true;
		errorNumber++;
		errorString += errorNumber + errorNumDot + "Please ensure your 9 digit bank routing number has been entered correctly.\n";
  }
	if (errors) {
		return false;
	} else {
		return true;
	}
}
function showcc() {
	document.getElementById('mecinfo').style.display = 'none';
	document.getElementById('ccinfo').style.display = 'block';
	document.PaymentInfo.cc_number.focus();
}
function showmec() {
	document.getElementById('ccinfo').style.display = 'none';
	document.getElementById('mecinfo').style.display = 'block';
	document.PaymentInfo.acc_name.focus();
}
	
