//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 description " + maxlimit + " characters or less." );
    return false;
  }
  else
  {
    countfield.value = maxlimit - field.value.length;
  }
}


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_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 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;
		}
	}
	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_viewDetails(productID,bGroupBuy,bHasCart,bNbr) {
	var warn_gbCart = "You have regular shopping items in your cart\nJoining this Group Buy will NOT purchase those items.\nYou will have to checkout separately after joining the group\nin order to purchase the product(s) in your cart.\nOK to proceed?";
	var warn_gb = "Please make a selection from the drop down box\nbefore joining this group buy.";
	var warn_cart = "Please make a selection from the drop down box\nbefore adding this item to your cart.";	
	if(bGroupBuy && bHasCart) {
		if(confirm(warn_gbCart)) return true;
		return false;
	}
	var attr = eval("document.form1.Attr" + productID);
	var esd = eval("document.form1.ESD" + productID);
	var multi = eval("document.form2.multic");
	alert(bNbr);
	return false;


	if(attr && attr.selectedIndex == 0) {
		alert(bGroupBuy ? warn_gb : warn_cart);
		return false;
	}
	if(esd && esd.selectedIndex == 0) {
		alert(bGroupBuy ? warn_gb : warn_cart);
		return false;
	}
	if (multi==1 && bNbr>0)	{
		boxes = document.form2.multic.length;
		txt = 0;
		for (i = 0; i < boxes; i++) 
		{
			if (document.form2.multic[i].checked) 
			{
				txt = txt + 1;
			}
		}
		if (txt == 0) 
		{
			alert("Wrong number of Boxes ticked" + "\nYou checked "+txt+" boxes but you need to check "+bNbr);
			return false;
		}
		
	}
	return true;
}


// 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" + "\n";
	}
	
	if(!bValid) {
		alert(error);
		return;
	} 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;
	var shipCountry = document.form1.ShipCountry.options[document.form1.ShipCountry.selectedIndex].value;
	
	if(shipState == "none") {
		bValid = false;
		error += "-- State" + "\n";
	}
	
	if(shipCountry == "none") {
		bValid = false;
		error += "-- Country" + "\n";
	}
	
	if(!bValid) {
		alert(error);
		return;
	} else {
		if(emailCheck(document.form1.ShipEmail.value)) {
			document.form1.submit();
		}
	}
}




//----------------------------------------- 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();
	}
}

//----------------------------------------- checkOut.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;
	}
}