var PURCHASE_CLICKED = 0;

function mod10( cardNumber ) { // LUHN Formula for validation of credit card numbers.
	var ar = new Array( cardNumber.length );
	var i = 0,sum = 0;
	for( i = 0; i < cardNumber.length; ++i ) {
		ar[i] = parseInt(cardNumber.charAt(i));
	}
	for( i = ar.length -2; i >= 0; i-=2 ) {  // you have to start from the right, and work back.
		ar[i] *= 2;							 // every second digit starting with the right most (check digit)
		if( ar[i] > 9 ) ar[i]-=9;			 // will be doubled, and summed with the skipped digits.
	}										 // if the double digit is > 9, add those individual digits together 
	for( i = 0; i < ar.length; ++i ) {
		sum += ar[i];						 // if the sum is divisible by 10 mod10 succeeds
	}
	return (((sum%10)==0)?true:false);	  	
}

function expired( month, year ) {
	var now = new Date();							// this function is designed to be Y2K compliant.
	var expiresIn = new Date(year,month,0,0,0);		// create an expired on date object with valid thru expiration date
	expiresIn.setMonth(expiresIn.getMonth()+1);		// adjust the month, to first day, hour, minute & second of expired month
	if( now.getTime() < expiresIn.getTime() ) return false;
	return true;									// then we get the miliseconds, and do a long integer comparison
}

function ContainsOnlyValidChars(sText,ValidChars)
{
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++)  {
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1)  {
         IsNumber = false;
      }
   }
   return IsNumber;
}

function IsNumeric(sText) {
  return ContainsOnlyValidChars(sText,"0123456789.");
}

function IsAlphaOrSpace(sText) {
  return ContainsOnlyValidChars(sText,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ");
}

function IsAlphaNumOrSpace(sText) {
  return ContainsOnlyValidChars(sText,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789- ");
}

function showErrorDiv(txt) {
//alert( txt );
	var el = document.getElementById("important_info");
	if( el ) {
		el.innerHTML = "<table class=\"importantinfo_tbl\"><tr><td class=\"importantinfo_lbl\"><B>Important Information</B></td><td class=\"importantinfo_txt\" name=\"importantinfo_text\"><B>We're sorry, but your form could not be submitted for the following reason(s):</B><br>"+txt+"</td></tr></table>";
		if( el.style ) {
			el.style.visibility = 'visible';
		} else {
			el.visibility = 'visible';
		}
	} else {
		alert(txt);
	}
}

function validateCard(cardNumber,cardType,cardMonth,cardYear, cardCVV, checkvalue) {

	cardNumber = TrimString(cardNumber);	// string trim left and right
	
	if( checkvalue == 0 ) {						
		showErrorDiv("Total amount is 0.00, amount must be more than 0.00");
		return false;				
	}

	if( cardNumber.length == 0 ) {						//most of these checks are self explanitory
		showErrorDiv("You have entered an invalid credit card number.");
		return false;				
	}
	
	if (cardType.length == 0) {
		showErrorDiv("You have not selected a credit card type.");
		return false;				
	}

	var HiddenCardNumber =  cardNumber.substring(0,4);
	if (HiddenCardNumber != 'XXXX')
	{

	for( var i = 0; i < cardNumber.length; ++i ) {		// make sure the number is all digits.. (by design)
		var c = cardNumber.charAt(i);
		if( c < '0' || c > '9' ) {
			showErrorDiv("Please enter a valid card number.  Use only digits.  Do not use spaces or hyphens.");
			return false;
		}
	}
	var length = cardNumber.length;			//perform card specific length and prefix tests

	switch( cardType ) {
		case 'AMEX':
			if( length != 15 ) {
				showErrorDiv("Please enter a valid American Express Card number.");
				return false;
			}
			var prefix = parseInt( cardNumber.substring(0,2));
			if( prefix != 34 && prefix != 37 ) {
				showErrorDiv("Please enter a valid American Express Card number.");
				return false;
			}
			break;
		case 'DIS':
			if( length != 16 ) {
				showErrorDiv("Please enter a valid Discover Card number.");
				return false;
			}
			var prefix = parseInt( cardNumber.substring(0,4));
			if( prefix != 6011 ) {
				showErrorDiv("Please enter a valid Discover Card number.");
				return false;
			}
			break;
		case 'MC':
			if( length != 16 ) {
				showErrorDiv("Please enter a valid MasterCard number.");
				return false;
			}
			var prefix = parseInt( cardNumber.substring(0,2));
			if( prefix < 51 || prefix > 55) {
				showErrorDiv("Please enter a valid MasterCard Card number.");
				return false;
			}
			break;
		case 'VISA':
			if( length != 16 && length != 13 ) {
				showErrorDiv("Please enter a valid Visa Card number.");
				return false;
			}
			var prefix = parseInt( cardNumber.substring(0,1));
			if( prefix != 4 ) {
				showErrorDiv("Please enter a valid Visa Card number.");
				return false;
			}
			break;
	}
	if( !mod10( cardNumber ) ) {                             		// run the check digit algorithm
		showErrorDiv("You have entered an invalid credit card number.");
		return false;
	}

	}

	if( expired( cardMonth, cardYear ) ) {							// check if entered date is already expired.
		showErrorDiv("You have selected an invalid expiration date.");
		return false;
	}

	length = cardCVV.length;			//perform card specific length and prefix tests

	if( !IsNumeric(cardCVV) ) {
		showErrorDiv("You have entered an invalid CVV code.");
		return false;
	}

	switch( cardType ) {
		case 'AMEX':
			if( length != 4 ) {
				showErrorDiv("You have entered an invalid CVV code.");
				//alert("American Express Card has a 4-digit Card Verification Number.");
				return false;
			}
			break;
		case 'DIS':
		case 'MC':
		case 'VISA':
			if( length != 3 ) {
				showErrorDiv("You have entered an invalid CVV code.");
				//alert("Your Card has a 3-digit Card Verification Number.");
				return false;
			}
			break;
	}

    if (PURCHASE_CLICKED != 0) {
		return false;	//don't let clients click purchase twice
    }

    PURCHASE_CLICKED = 1;
	return true; // at this point card has not been proven to be invalid
}

function storeValidateCard(cardNumber,cardType,cardMonth,cardYear, cardCVV, checkvalue, billState, billCountry, billzip, billPhone, billEmail, billTo, billAddress, billCity) {
	PURCHASE_CLICKED = 0;
	if(validateCard(cardNumber,cardType,cardMonth,cardYear, cardCVV, checkvalue)) {

		if(billTo.length < 2 ) { //|| !IsAlphaNumOrSpace(billTo)) {
			showErrorDiv("You have entered an invalid name on your credit card.");
			return false;
		}

		if(billAddress.length < 2) {
			showErrorDiv("You have entered an invalid address.");
			return false;
		}

		if(billCity.length < 2 ) { //|| !IsAlphaOrSpace(billCity)) {
			showErrorDiv("You have entered an invalid city.");
			return false;
		}

		if(billCountry == 'default') {
			showErrorDiv("You have not selected a country.");
			return false;
		}

		if(billCountry == '840' || billCountry == '124') {
			if(billState == 'none') {
				showErrorDiv('Your state/province is required for US and Canadian addresses.');
				return false;
			}
		}
		else {
			if(billState != 'none') {
				showErrorDiv('No state or province needed for countries other than US and Canada.');
				return false;
			}
		}
	
		if( billCountry=='840' && (billzip.length!=5 || !IsNumeric(billzip)) ) {	
			showErrorDiv('You have entered an invalid zip code.');
			return false;
		} else {
			//if( !IsAlphaNumOrSpace(billzip) ) {
			//	showErrorDiv('You have entered an invalid zip code.');
			//	return false;
			//}
			if(billzip == '') {
				showErrorDiv('Your zip/postal code is required.');
				return false;
			}
		}
		
		if(!isPhonenum(billPhone)) {
			showErrorDiv('You have entered an invalid phone number.');
			return false;
		}

		if (!isEmail(billEmail, false)) {
			showErrorDiv('You have entered an invalid email address.');
			return false;
		} 
	}
	else{
		return false;
	}
	
	PURCHASE_CLICKED = 1;
	return true;
}

function TrimString(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}

