//limit the amount of text that may be entered into a field
function textCounter( field, countfield, maxlimit ) {
  if ( field.value.length > maxlimit )
  {
    field.value = field.value.substring( 0, maxlimit );
    alert( "Please make your text " + maxlimit + " characters or less." );
    return false;
  }
  else
  {
    countfield.value = maxlimit - field.value.length;
  }
}

function checkForm_wishListShare() {
	var emails = document.form1.Emails.value;
	var message = document.form1.Message.value;
	if(emails == "") {
		alert("Please type at least one email address to send your wish list to");
		return false;
	}
	if(message == "") {
		alert("Please type a message to send.");
		return false;
	}
	return true;
}

function checkForm_emailThisPage() {
	var emails = document.form1.Emails.value;
	var message = document.form1.Message.value;
	if(emails == "") {
		alert("Please type at least one email address to send the page to");
		return false;
	}
	if(message == "") {
		alert("Please type a message to send.");
		return false;
	}
	return true;
}


function checkForm_wishList() {
	//ensure at least one item is selected
	for(x=0;x<document.frmWishList.length;x++) {
		var el = document.frmWishList.elements[x];
		if(el.name.indexOf("cb") != -1) {
			if(el.checked) return true;
		}
	}
	alert("Please check the box next to at least one item in your wish list first.");
	return false;
}


function checkForm_review() {
	if(document.form1.Rating.selectedIndex == 0) { alert("Please select a rating between 1 and 5 stars."); return false; }
	if(document.form1.ReviewTitle.value == "") { alert("Please enter a title for your review."); return false; }
	if(document.form1.ReviewText.value == "") { alert("Please type your review."); return false; }
	return true;
}

function checkForm_stockAlert() {
	if(!emailCheck(document.form1.Email.value)) return false;
	return true;
}

function checkForm_subscribe() {
	if(!emailCheck(document.frmSubscribe.Email.value)) return false;
	return true;
}

function checkForm_support() {
	if(!emailCheck(document.form1.Email.value)) return false;
	if(document.form1.Text.value == "") {
		alert("Please enter a description.");
		return false;
	}
	return true;
}

function checkCreateAccount() {
	var req = new Array(7);
	req[0] = "Login";
	req[1] = "Password";
	req[2] = "PasswordConfirm";
	req[3] = "BillFirstName";
	req[4] = "BillLastName";
	req[5] = "BillEmail";
	req[6] = "BillEmailConfirm";
	
	var names = new Array(7);
	names[0] = "Login";
	names[1] = "Password";
	names[2] = "Password again to confirm";
	names[3] = "First Name";
	names[4] = "Last Name";
	names[5] = "Email Address";
	names[6] = "Email address again to confirm";
	
	var bValid = true;
	var message = "You need to complete or change the following fields before submitting this form:\n\n";
	for(x=0;x<req.length;x++) {
		var target = eval("document.form1." + req[x]);
		if(target.value == "") {
			bValid = false;
			message += "-- " + names[x] + "\n";
		}
	}
	
	var login = eval("document.form1.Login.value");
	var password = eval("document.form1.Password.value");
	var passwordConfirm = eval("document.form1.PasswordConfirm.value");
	var email = eval("document.form1.BillEmail.value");
	var emailConfirm = eval("document.form1.BillEmailConfirm.value");
	
	if(login.length < 4 || password.length < 4) {
		bValid = false;
		message += "\nYour Login Name and Password must both be 4 or more characters";
	}
	for(x=0;x<login.length;x++) {
		if(login.charAt(x) == ' ') {
			bValid = false;
			message += "\nYour Login name may not contain spaces.";
		}
	}
	for(x=0;x<password.length;x++) {
		if(password.charAt(x) == ' ') {
			bValid = false;
			message += "\nYour Password may not contain spaces.";
		}
	}
	if (password != passwordConfirm) {
		bValid = false;
		message += "\nThe passwords you entered do not match.";
	}
	if(email != emailConfirm) {
		bValid = false;
		message += "\nThe emails you entered do not match.";
	}
	
	if(!emailCheck(document.form1.BillEmail.value)) {
		return false;
	}
	
	if(!bValid) {
		alert(message);
		return false;
	}
	return true;
}

function checkCreateAccount2() {
	var req = new Array(7);
	req[0] = "Login";
	req[1] = "Password";
	req[2] = "PasswordConfirm";
	req[3] = "BillFirstName";
	req[4] = "BillLastName";
	req[5] = "BillEmail";
	req[6] = "BillEmailConfirm";
	
	var names = new Array(7);
	names[0] = "Login";
	names[1] = "Password";
	names[2] = "Password again to confirm";
	names[3] = "First Name";
	names[4] = "Last Name";
	names[5] = "Email Address";
	names[6] = "Email address again to confirm";
	
	var bValid = true;
	var message = "You need to complete or change the following fields before submitting this form:\n\n";
	for(x=0;x<req.length;x++) {
		var target = eval("document.form2." + req[x]);
		if(target.value == "") {
			bValid = false;
			message += "-- " + names[x] + "\n";
		}
	}
	
	var login = eval("document.form2.Login.value");
	var password = eval("document.form2.Password.value");
	var passwordConfirm = eval("document.form2.PasswordConfirm.value");
	var email = eval("document.form2.BillEmail.value");
	var emailConfirm = eval("document.form2.BillEmailConfirm.value");
	
	if(login.length < 4 || password.length < 4) {
		bValid = false;
		message += "\nYour Login Name and Password must both be 4 or more characters";
	}
	for(x=0;x<login.length;x++) {
		if(login.charAt(x) == ' ') {
			bValid = false;
			message += "\nYour Login name may not contain spaces.";
		}
	}
	for(x=0;x<password.length;x++) {
		if(password.charAt(x) == ' ') {
			bValid = false;
			message += "\nYour Password may not contain spaces.";
		}
	}
	if (password != passwordConfirm) {
		bValid = false;
		message += "\nThe passwords you entered do not match.";
	}
	if(email != emailConfirm) {
		bValid = false;
		message += "\nThe emails you entered do not match.";
	}
	
	if(!emailCheck(document.form2.BillEmail.value)) {
		return false;
	}
	
	if(!bValid) {
		alert(message);
		return false;
	}
	return true;
}


function checkForm_shippingAndCredit() {
	if(!bValidCreditCardNumber(document.form1.CCName.value,document.form1.CCNumber.value)) {
		return false;
	}
	// make sure expiration date is valid on credit card
	var now = new Date();
	var fullYear = now.getYear().toString();
	var thisYear = parseInt(fullYear.substring(2,4));
	
	var selYear = document.form1.CCExpYear.options[document.form1.CCExpYear.selectedIndex].value;
	var selMonth = document.form1.CCExpMonth.options[document.form1.CCExpMonth.selectedIndex].value;
	
	if(thisYear >= selYear) {
		if(parseInt(now.getMonth() + 1 ) > selMonth) {
				alert("Please select a valid expiration date for your credit card \nor choose a credit card that has not expired.");
				return false;
		}
	}
	if(document.form1.CCCVV2.value == "") {
		alert("Please enter a valid CVV2 Number.");
		return false;
	}
	return true;
}

function checkForm_editAccount() {
	var req = new Array(4);
	req[0] = "Password";
	req[1] = "PasswordConfirm";
	req[2] = "BillEmail";
	req[3] = "BillEmailConfirm";
	
	var names = new Array(7);
	names[0] = "Password";
	names[1] = "Password again to confirm";
	names[2] = "Email Address";
	names[3] = "Email address again to confirm";
	
	var bValid = true;
	var message = "You need to complete or change the following fields before submitting this form:\n\n";
	for(x=0;x<req.length;x++) {
		var target = eval("document.form1." + req[x]);
		if(target.value == "") {
			bValid = false;
			message += "-- " + names[x] + "\n";
		}
	}
	
	var password = eval("document.form1.Password.value");
	var passwordConfirm = eval("document.form1.PasswordConfirm.value");
	var email = eval("document.form1.BillEmail.value");
	var emailConfirm = eval("document.form1.BillEmailConfirm.value");
	
	if(password.length < 4) {
		bValid = false;
		message += "\nYour Password must 4 or more characters";
	}
	for(x=0;x<password.length;x++) {
		if(password.charAt(x) == ' ') {
			bValid = false;
			message += "\nYour Password may not contain spaces.";
		}
	}
	if (password != passwordConfirm) {
		bValid = false;
		message += "\nThe passwords you entered do not match.";
	}
	if(email != emailConfirm) {
		bValid = false;
		message += "\nThe emails you entered do not match.";
	}
	
	if(!emailCheck(document.form1.BillEmail.value)) {
		return false;
	}
	
	if(!bValid) {
		alert(message);
		return false;
	} else {
		return true;
	}
}

function checkForm_details() {
	//ensure at least one item is selected
	var command = document.frmDetails.command.value;
	for(x=0;x<document.frmDetails.length;x++) {
		var el = document.frmDetails.elements[x];
		if(el.name.indexOf("add") != -1) {
			if(el.checked) return true;
		}
	}
	alert("Please check the box next to at least one item\nbefore adding to your " + command);
	return false;
}






// for every upsell product checked by user
// if there is an attribute for the item
// make sure a selection has been made

function checkForm_upsell() {
	
	var cbPrefix = "PID";
	for(x=0;x<document.form1.length;x++) {
		var cur = document.form1.elements[x];
		//if we land on a checkbox and it's checked
		//check to see if there is a matching attribute
		if(cur.name.substr(0,cbPrefix.length) == cbPrefix && cur.checked) {
			var productID = cur.name.substr(cbPrefix.length);
			var target = eval("document.form1.Attr" + productID);
			if(target && target.selectedIndex == 0) {
				alert("Please make a selection from the drop down box before adding your selection.");
				return false;
			}
		}
	}
	
	return true;
}



//validate all required billing information is present
function checkForm_billing() {
	
	var bValid = true;
	var error = "You need to complete or correct the following required fields before proceeding:\n";
	
	var req = new Array();
	req[0] = "BillFirstName";
	req[1] = "BillLastName";
	req[2] = "BillEmail";
	req[3] = "BillAddress1";
	req[4] = "BillCity";
	req[5] = "BillZip";
	
	var names = new Array();
	names[0] = "First Name";
	names[1] = "Last Name";
	names[2] = "Email Address";
	names[3] = "Address 1";
	names[4] = "City";
	names[5] = "Zip";

	for(x=0;x<req.length;x++) {
		var target = eval("document.form1." + req[x]);
		if(target.value == "") {
			bValid = false;
			error += "-- " + names[x] + "\n";
		}
	}
	
	var billState = document.form1.BillState.options[document.form1.BillState.selectedIndex].value;
	var billCountry = document.form1.BillCountry.options[document.form1.BillCountry.selectedIndex].value;

	
	if(billState == "none") {
		bValid = false;
		error += "-- State" + "\n";
	}
	
	if(billCountry == "none") {
		bValid = false;
		error += "-- Country (if non-U.S., please select Other (outside the U.S.))" + "\n";
	}
	
	//if indicating billing and shipping address are the same
	//validate shipping address
	
	if(document.form1.bBillShip.checked) {
		if(billCountry != "US" && billCountry != "PR") {
			alert("We cannot ship to the country you selected.\nOn the next step, please create a shipping adress in the United States or Puerto Rico.\nIf you need additional help, please contact support@bigdiscount.com.");
			document.form1.bBillShip.checked = false;
		}
		var a1 = document.form1.BillAddress1.value;
		var regex = /p\.?o\.?\s*box/gi;
		if(a1.search(regex) != -1) {
			alert("We cannot ship to P.O. Boxes.\nPlease enter a physical address on the next step.\nIf you need additional help, please contact support@bigdiscount.com");
			document.form1.bBillShip.checked = false;
		}
	}
	
	if(!bValid) {
		alert(error);
		return false;
	} else {
		if(emailCheck(document.form1.BillEmail.value)) {
			document.form1.submit();
		}
	}
}

function checkForm_shipping() {
	var bValid = true;
	var error = "You need to complete or correct the following required fields before proceeding:\n";
	
	var req = new Array();
	req[0] = "ShipFirstName";
	req[1] = "ShipLastName";
	req[2] = "ShipEmail";
	req[3] = "ShipAddress1";
	req[4] = "ShipCity";
	req[5] = "ShipZip";
	
	var names = new Array();
	names[0] = "First Name";
	names[1] = "Last Name";
	names[2] = "Email Address";
	names[3] = "Address 1";
	names[4] = "City";
	names[5] = "Zip";

	for(x=0;x<req.length;x++) {
		var target = eval("document.form1." + req[x]);
		if(target.value == "") {
			bValid = false;
			error += "-- " + names[x] + "\n";
		}
	}
	
	var shipState = document.form1.ShipState.options[document.form1.ShipState.selectedIndex].value;
	
	if(shipState == "none") {
		bValid = false;
		error += "-- State\n";
	}
	if(shipState == "01") {
		bValid = false;
		error += "-- Ship state must be a U.S. State\n";
	}
	
	var a1 = document.form1.ShipAddress1.value;
	var regex = /p\.?o\.?\s*box/gi;
	if(a1.search(regex) != -1) {
		alert("We cannot ship to P.O. Boxes.\nPlease enter a street address or contact support@bigdiscount.com for assistance.");
		return false;
	}
	
	if(!bValid) {
		alert(error);
		return false;
	} else {
		if(emailCheck(document.form1.ShipEmail.value)) {
			return true;
		}
	}
}

//validate all required information in wholesale registration page
function checkForm_wholesale() {
	
	var req = new Array();
	req[0] = "BillFirstName";
	req[1] = "BillLastName";
	req[2] = "BillEmail";
	req[3] = "BillEmailConfirm";
	req[4] = "Login";
	req[5] = "Password";
	req[6] = "PasswordConfirm";
	req[7] = "BillCompany";
	req[8] = "BillAddress1";
	req[9] = "BillCity";
	req[10] = "BillZip";
	req[11] = "BillPhone";
	req[12] = "ResellerID";
	
	var names = new Array();
	names[0] = "First Name";
	names[1] = "Last Name";
	names[2] = "Email Address";
	names[3] = "Email address again to confirm";
	names[4] = "Login";
	names[5] = "Password";
	names[6] = "Password again to confirm";
	names[7] = "Company Name";
	names[8] = "Address 1";
	names[9] = "City";
	names[10] = "Zip";
	names[11] = "Phone";
	names[12] = "ResellerID";

	var bValid = true;
	var message = "You need to complete or correct the following required fields before proceeding:\n";
	for(x=0;x<req.length;x++) {
		var target = eval("document.form1." + req[x]);
		if(target.value == "") {
			bValid = false;
			message += "-- " + names[x] + "\n";
		}
	}
	
	var login = eval("document.form1.Login.value");
	var password = eval("document.form1.Password.value");
	var passwordConfirm = eval("document.form1.PasswordConfirm.value");
	var email = eval("document.form1.BillEmail.value");
	var emailConfirm = eval("document.form1.BillEmailConfirm.value");
	var billState = document.form1.BillState.options[document.form1.BillState.selectedIndex].value;
	var billCountry = document.form1.BillCountry.options[document.form1.BillCountry.selectedIndex].value;

	
	if(login.length < 4 || password.length < 4) {
		bValid = false;
		message += "\nYour Login Name and Password must both be 4 or more characters";
	}
	for(x=0;x<login.length;x++) {
		if(login.charAt(x) == ' ') {
			bValid = false;
			message += "\nYour Login name may not contain spaces.";
		}
	}
	for(x=0;x<password.length;x++) {
		if(password.charAt(x) == ' ') {
			bValid = false;
			message += "\nYour Password may not contain spaces.";
		}
	}
	if (password != passwordConfirm) {
		bValid = false;
		message += "\nThe passwords you entered do not match.";
	}
	if(email != emailConfirm) {
		bValid = false;
		message += "\nThe emails you entered do not match.";
	}
	if(billState == "none") {
		bValid = false;
		message += "-- State (if non-U.S., please select Other (outside the U.S.))" + "\n";
	}
	
	if(billCountry == "none") {
		bValid = false;
		message += "-- Country" + "\n";
	}
	if(!bValid) {
		alert(message);
		return false;
	}
	return true;
}



//----------------------------------------- passwordRecovery.php -----------------------------------------------
function checkForm_passwordRecovery() {
	if(emailCheck(document.form1.BillEmail.value)) {
		return true;
	} 
	return false;
}

function checkEmailSalesReport() {
	if(emailCheck(document.form1.Email.value)) {
		document.form1.submit();
	}
}

//----------------------------------------- checkout1.php ----------------------------------------------------
function checkLoginAndPassword() {
	var bValid = true;
	if(document.form1.Login.value.length < 4 ) {
		bValid = false;
	}
	if(document.form1.Password.value.length < 4 ) {
		bValid = false;
	}
	if(!bValid) {
		alert("The Login and Password must each be between 4 and 20 characters long.\nPlease re-enter your Login and Password.");
		return false;
	}
	return true;
}


function checkForm_creditCard() {
	if(!bValidCreditCardNumber(document.form1.CCName.value,document.form1.CCNumber.value)) {
		return false;
	}
	// make sure expiration date is valid on credit card
	var now = new Date();
	var fullYear = now.getYear().toString();
	var thisYear = parseInt(fullYear.substring(2,4));
	
	var selYear = document.form1.CCExpYear.options[document.form1.CCExpYear.selectedIndex].value;
	var selMonth = document.form1.CCExpMonth.options[document.form1.CCExpMonth.selectedIndex].value;
	
	if(thisYear >= selYear) {
		if(parseInt(now.getMonth() + 1 ) > selMonth) {
				alert("Please select a valid expiration date for your credit card \nor choose a credit card that has not expired.");
				return false;
		}
	}
	return true;
}



//------------------------------------------ credit card validation ----------------------------------

function bValidCreditCardNumber(type,num) {
	if (!isOnlyDigits(num)){
 		alert('Please enter only digits (no dashes or spaces) for the credit card number');
		return false;
	}
 	if (!LuhnCheck(num) || !validateNum(type,num)){
 		alert("The credit card number you entered appears to be invalid.  Please try again");
		return false;
	}
	return true;
}

//verify that all numbers entered for card are digits

function isOnlyDigits(str)
{
	var numbers = "0123456789";
	for (var i=0;i<str.length;i++)
		if (numbers.indexOf(str.substr(i,1))<0){
			return false;
		}
	return true;
}


function LuhnCheck(str) 
{
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++) 
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var 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 validateNum(type,num)
{
	var result = false;
	
	var cardLen = num.length;
	var firstdig = num.substring(0,1);
	var seconddig = num.substring(1,2);
	var first4digs = num.substring(0,4);
	var validNums = 0;

	switch (type)
	{
		case "VISA":
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case "AMEX":
			validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "MASTERCARD":
			validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case "DISCOVER":
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case "DINERS":
			validNums = "068";
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
	}
	return result;
}


//--------------------------------------- validate email address --------------------------------------------------------

function emailCheck (emailStr) { 
	var checkTLD=0; 
	var knownDomsPat=/ ^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/; 
	var emailPat=/^(.+)@(.+)$/; 
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]"; 
	var validChars="\[^\\s" + specialChars + "\]"; 
	var quotedUser="(\"[^\"]*\")"; 
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/; 
	var atom=validChars + '+'; 
	var word="(" + atom + "|" + quotedUser + ")"; 
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); 
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$"); 
	var matchArray=emailStr.match(emailPat); 
	
	if (matchArray==null) { 
		alert("The Email Address appears to be invalid.\nPlease check your typing and try again."); 
		return false; 
	}
	 
	var user=matchArray[1]; 
	var domain=matchArray[2]; 
	
	for (i=0; i<user.length; i++) { 
		if (user.charCodeAt(i)>127) { 
			alert("The username portion of the email address you entered \nappears to contain invalid characters."); 
			return false; 
		} 
	} 
	
	for (i=0; i<domain.length; i++) { 
		if (domain.charCodeAt(i)>127) { 
			alert("The domain name portion of the email address you entered \nappears to contain invalid characters."); 
			return false; 
		} 
	} 
	
	if (user.match(userPat)==null) { 
		alert("The Username Is Invalid."); 
		return false; 
	} 
	
	var IPArray=domain.match(ipDomainPat); 
	if (IPArray!=null) { 
		for (var i=1;i<=4;i++) { 
			if (IPArray>255) { 
				alert("The destination IP Address of the email address you entered\n appears invalid."); 
				return false; 
			} 
		} 
	return true; 
	} 
	
	var atomPat=new RegExp("^" + atom + "$"); 
	var domArr=domain.split("."); 
	var len=domArr.length; 
	
	for (i=0;i<len;i++) { 
		if (domArr[i].search(atomPat)==-1) { 
			alert("The Domain Name Is Invalid."); 
			return false; 
		} 
	}
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) { 
		alert("The domain name extension of the email address you entered\nappears invalid."); 
		return false; 
	}
	 
	if (len<2) { 
		alert("The email address you entered is missing a hostname."); 
		return false; 
	}
	return true;
} 

var counter=0; 

function isReady() {
	var ret = false;
	if (validate_form()) ret = true;
	ret = emailCheck(document.info.email.value) ? true : false;
	if(ret) {
  	if(counter++){
    	ret=false;
    	alert('The Form Is Already Being Submitted'); 
  	}
	} else {
    ret=true;
		alert(ret);
		return ret;
	}
}