/* ******************************************************************************
 * Javascript checks for checkout pages
 *
 * Updated April 2002 - smistry@jrcigars.com
 *  
 ******************************************************************************* */
 
// --- Numbers only
function smNumbersOnly(field) {
	var valid = "0123456789"
	var ok = "yes";
	var temp;
	for (var i = 0; i < field.value.length; i++) {
		temp = "" + field.value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") ok = "no";
	}
	if (ok == "no") {
		alert("Invalid entry!  Only numbers are accepted");
		field.focus();
		field.select();
	}
}

// --- Letters only
function smLettersOnly(field) {
	var valid = "abcdefghijklmnopqrstuvwxyz"
	var ok = "yes";
	var temp;
	for (var i=0; i<field.value.length; i++) {
		temp = "" + field.value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") ok = "no";
	}
	if (ok == "no") {
		alert("Invalid entry!  Only are accepted!");
		field.focus();
		field.select();
	}
}

// --- Auto Tab
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode)) {
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
	}
	function containsElement(arr, ele) {
		var found = false, index = 0;
		while(!found && index < arr.length)
		if(arr[index] == ele)
		found = true;
		else
		index++;
		return found;
	}
	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
		if (input.form[i] == input)index = i;
		else i++;
		return index;
	}
	return true;
}

// --- Disable submit after submission
function disableForm(theform) {
	if (document.all || document.getElementById) {
		for (i = 0; i < theform.length; i++) {
			var tempobj = theform.elements[i];
			if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "button" || tempobj.type.toLowerCase() == "reset")
			tempobj.disabled = true;
		}
		// setTimeout('alert("Your form has been submitted.  Notice how the submit and reset buttons were disabled upon submission.")', 2000);
		return true;
	}
	else {
		// alert("The form has been submitted.  But, since you're not using IE 4+ or NS 6, the submit button was not disabled on form submission.");
		return false;
	}
}

// --- Change button when submitted
function changeButton(s)  {
	s.value = "SENDING Form Data...";
	return true;
}

// --- Test that the field is not blank
function testField(form, Ctrl) {
	if (Ctrl.value == "") {
		validatePrompt (Ctrl, "Please enter a value");
		return (false);
	} 
	else {
		return (true);
	}
}





// --- Test for Address Number
function testAddress(form, Ctrl) {
	if (Ctrl.value == "") {
		validatePrompt (Ctrl, "Please enter your address");
		return (false);
	} 
	else {
		return (true);
	}
}


// --- Test for City
function testCity(form, Ctrl) {
	if (Ctrl.value == "") {
		validatePrompt (Ctrl, "Please enter your city");
		return (false);
	} 
	else {
		return (true);
	}
}

// --- Test for State
function testState(form, Ctrl) {
	// document.writeln("type is " + Ctrl.type);
	if (Ctrl.type == "hidden") {
		// check the value is not null
		if (Ctrl.value == "") {
			validatePrompt (Ctrl, "State Shipping not found");
			return (false);
		} 
		else {
			return (true);
		}
	}
	else {
		// === Fix for older versions of Netscape
		var Ctrl_value = Ctrl.options[Ctrl.selectedIndex].value;
		if (Ctrl_value == "") {
			validatePrompt (Ctrl, "Please enter your state");
			return (false);
		} 
		else {
			return (true);
		}
	}
}

// --- Test for Zip
function testZip(form, Ctrl) {
	if (Ctrl.value == "") {
		validatePrompt (Ctrl, "Please enter your zip");
		return (false);
	} 
	else {
		return (true);
	}
}

// --- Check Credit Card
function checkCreditCard(ccnum) {
	if (ccnum.value.indexOf("x") > -1) {
		return true;
	} 
	else {	
		return validateCard (ccnum.value);
	}
}

// --- Test for Gift Message Length
function testMessageLen(form, Ctrl) {
	if (Ctrl.value.length > 50) {
		validatePrompt (Ctrl, "Please make your 'Gift Message(s)' shorter.\n(50 Characters Max Each)");
		return (false);
	} 
	else {
		return (true);
	}
}


// --- Test for CC Expiration
function testExp(mon, yr) {
	today = new Date();
	exp_date = new Date(yr.options[yr.selectedIndex].text,mon.options[mon.selectedIndex].text);
	if (today > exp_date) {
		validatePrompt (mon, "Your credit card no longer valid, please correct your expiration date or enter a different card.");
		return false;
	} 
	else {
		return true;
	}
}

// --- Test for Shipping
function testShipping(form, Ctrl) {
	// === Fix for older versions of Netscape
	// var Ctrl_value = Ctrl.options[Ctrl.selectedIndex].value;
	var Ctrl_value = Ctrl.options[Ctrl.selectedIndex].value;
	if (Ctrl_value == "") {
		validatePrompt (Ctrl, "Please choose a shipping option");
		return (false);
	} 
	else {
		return (true);
	}
}


// --- Support routine used during tests
function validatePrompt (Ctrl, PromptStr) {
	alert (PromptStr)
	Ctrl.focus();
	return;
}



function check_exp() {
	//mon=document.form1.ccexpmo.value
	//yr=document.form1.ccexpyr.value
	mon=document.form1.ccexpmo.options[document.form1.ccexpmo.selectedIndex].text
	yr=document.form1.ccexpyr.options[document.form1.ccexpyr.selectedIndex].text
	today=new Date()
	exp_date=new Date(yr,mon)
	if (today > exp_date) {
		alert("Your credit card has expired - Month = " + mon + " Year = " + yr );
		return false;
	} 
	else {
		return true;
	}
}


// --- Test that a shipping option has been chosen
function checkShipOption(SHService) {
	// 	if (document.form1.SHService.selectedIndex.value!=0) {
	//  error - if (document.form1.SHService.value!="") {
	if (SHService.options[SHService.selectedIndex].value != "") {
		return true;
	} 
	else {
		alert("Please select a shipping option");
		return false;
	}
}	


// --- Returning customers
function checkState(){
	if (document.form1.ShAddress1.value="") {
		alert("Please enter the shipping address");
		return false;
	}
	else {
		if (document.form1.ShState.selectedIndex==0) {
			alert("Please select a State");
			return false;
		}
	}
	return true;
}


// --- New customers
function checkState2(){
	if (document.form1.Address1.value!="") {
		if (document.form1.State.selectedIndex==0) {
			alert("Please select a State.");
			return false;
		}
	}
	return true;
}


// --- Returning customers
function checkShip() {
	ship=checkShipOption();
	if (ship && checkState()) {
		if (document.form1.ccnumber.value.indexOf("x") > -1) {
			return check_exp();
		} 
		else {	
			valid_car=validateCard (document.form1.ccnumber.value);
			if (valid_car==true) {
				return check_exp();
			} 
			else {
				return false;
			}
		}
	} 
	else {
		return false;
	}
}


// --- New customers
function checkShip2(form) {
	ship=checkShipOption(form.SHService);
	if (ship==true) {
		if (checkPassword() && check_exp() && checkState2()) {
			return validateCard (document.form1.ccnumber.value);
		} 
		else {
			return false;
		}
	} 
	else {
		return false;
	}
}


function checkPassword(){

	//--email check
	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 +")*$");
		if (document.form1.Email.value==null || document.form1.Email.value == "enter email here") {
		alert("Please enter your email address");
		return false;
	}
	var matchArray=document.form1.Email.value.match(emailPat);
	if (matchArray==null) {
		alert("Email address is invalid.  Please fix.");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	
	if (user.match(userPat)==null) {
	    alert("Please enter a valid email address.");
	    return false;
	}
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
	    for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
					alert("Please enter a valid email address.");
					return false;
		    }
	    }
	    return true;
	}
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("Please enter a valid email address.");
	  return false;
	}
	var atomPat=new RegExp(atom,"g");
	var domArr=domain.match(atomPat);
	var len=domArr.length;
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>4) {
	   
	   alert("Please enter a valid email address.");
	   return false;
	}
	
	
	if (len<2) {
	   var errStr="Please enter a valid email address.";
	   alert(errStr);
	   return false;
	}
	//--end of email check


	 if (document.form1.Password.value=="" || document.form1.re_Password.value=="") {
		alert("Please enter your password.")
		document.form1.Password.focus();
		return false;
	} 
	else if (document.form1.Password.value!=document.form1.re_Password.value) {
		alert("The password you entered does not match. Please correct.")
		document.form1.Password.focus();
		return false;
	} 
	else if (document.form1.Email.value!=document.form1.re_Email.value) {
		alert("The email address you entered does not match. Please correct.")
		document.form1.Email.focus();
		return false;
	} 
	else {
		return true;
	}
}


function validateCard (cc_num) {
	result = validatecardfunc(cc_num);
	if (result == true) {
		Num = stripNonNumbers (cc_num);
		ret = cardcheck (Num)
		if (ret == "VALID") {
			return true;
		}
		else {
			alert ("Credit card not valid!");
			document.form1.ccnumber.focus();
			return false;
		}
	} 
	else {
		alert ("Credit card not valid!")
		document.form1.ccnumber.focus();
		return false;
	}
}


function validatecardfunc (cc_num) {
	validcard = false;
	cc_num = stripNonNumbers (cc_num);
	ret = stripNonNumbers (cc_num);
	if (ret.substring (0, 1) ==5) {
		result = "Mastercard"
	} 
	else if (ret.substring (0, 1) ==4) {
		result = "Visa"
	} 
	else if (ret.substring (0, 1) ==3) {
		result = "American Express"
	} 
	else if (ret.substring (0, 1) ==6) {
		result = "Discover"
	} 
	else {
		result = "";
		validcard = false;
	}	
        
	if (result == "Mastercard") {
	  if (ret.length == 16) 
	          validcard = true;
	  if ((ret.substring (0, 2) >= "51") && (ret.substring (0, 2) <= "55"))
	          validcard = true;
	  else
	          validcard = false;
	}
	if (result == "Visa") {
	  if ((ret.length == 16)  || (ret.length ==13))
	          validcard = true;
	  if (ret.substring (0, 1) != "4")
	          validcard = false;
	}
	if (result == "American Express") {
	  if (ret.length == 15) 
					  validcard = true;
	  if ((ret.substring (0, 2) != "34") && (ret.substring (0, 2) != "37"))
	          validcard = false;
	}
	if (result == "Discover") {
	  if (ret.length == 16) 
	          validcard = true;
	  if (ret.substring (0, 4) != "6011")
	          validcard = false;
	}
	return (validcard);
}


function cardcheck (Num) {
	CardType=""
	mask = "2121212121212121"
	if (Num=="") {
		CardType="BLANK";
		return (CardType);
	}        
	if ( Num.length == 13 ) {
		Num = "000" + Num;
	}
	else if ( Num.length == 14 ) {
		Num = "00" + Num;
	}
	else if (Num.length == 15 ) {
		Num = "0" + Num;
	}

	if (Num.length == 16) {
		Num = Num;
	}
	else {
		CardType="INVALID";
	}
	
	CheckSum = 0;
	for (count = 1; count<= 16; count++) {
		ProdVal = Num.charAt(count-1) * mask.charAt(count-1);
		if (ProdVal > 9) {
			ProdVal = ProdVal - 9;
		}
		CheckSum = CheckSum + ProdVal;
	}
	CheckSum = CheckSum % 10;
	if (CheckSum != 0) {
		CardType="INVALID";
	}
	else {
		CardType="VALID";
	}
	return (CardType)
}


function stripNonNumbers (InString) {
	OutString="";
	for (Count=0; Count < InString.length; Count++) {
		TempChar=InString.substring (Count, Count+1);
		Strip = false;
		CharString="0123456789";
		for (Countx = 0; Countx < CharString.length; Countx++) {
			StripThis = CharString.substring(Countx, Countx+1)
			if (TempChar == StripThis) {
				Strip = true;
				break;
			}
		}
		if (Strip) {
			OutString=OutString+TempChar;
		}
	}
	return (OutString);
}



// Test all fields
// --- Abort submit on error
// --- Submit only if all fields pass tests
function runSubmit (form)  {
	
	if (!testAddress(form, form.ShAddress1)) return;
	if (!testCity(form, form.ShCity)) return;
	if (!testState(form, form.ShState)) return;
	if (!testZip(form, form.ShZip)) return;
	if (!testShipping(form, form.SHService)) return;


	if (!testAddress(form, form.Address1)) return;
	if (!testCity(form, form.City)) return;
	if (!testState(form, form.State)) return;
	if (!testZip(form, form.Zip)) return;

	if (!testExp(form.ccexpmo, form.ccexpyr)) return;
	if (!checkCreditCard(form.ccnumber)) return;
	if (!testMessageLen(form, form.gift_message1)) return;
	if (!testMessageLen(form, form.gift_message2)) return;
	form.submit();

	changeButton(form.submitbutton);
	disableForm(form);
	
}


// Test all fields
// --- Abort submit on error
// --- Submit only if all fields pass tests
function runSubmitVerification (form)  {
	
	form.submit();

	changeButton(form.submitbutton);
	disableForm(form);
	
}

