var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function checkCreditCard (cardnumber, cardname) {
     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "300,301,302,303,304,305,36,38,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,650",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "15,16", 
               prefixes: "3,1800,2131",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334, 6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "12,13,14,15,16,18", 
               prefixes: "5018,5020,5038,6304,6759,6761",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}

function mod10( card_number ) { // LUHN Formula for validation of credit card numbers.
    var ar = new Array( card_number.length );
    var i = 0,sum = 0;


        for( i = 0; i < card_number.length; ++i ) {
            ar[i] = parseInt(card_number.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());     // 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 validateCard(card_number,cardType,cardMonth,cardYear) {
            if( card_number.length == 0 ) {                      //most of these checks are self explanitory
                alert("Please enter a valid card number.");
                return false;               
            }
            for( var i = 0; i < card_number.length; ++i ) {      // make sure the number is all digits.. (by design)
                var c = card_number.charAt(i);


                    if( c < '0' || c > '9' ) {
                        alert("Please enter a valid card number. Use only digits. do not use spaces or hyphens.");
                        return false;
                    }
                }
                var length = card_number.length;         //perform card specific length and prefix tests


                 
                            if( !mod10( card_number ) ) {        // run the check digit algorithm
                                alert("Sorry! this is not a valid credit card number.");
                                return false;
                            }
                            if( expired( cardMonth, cardYear ) ) {                          // check if entered date is already expired.
                                alert("Sorry! The expiration date you have entered would make this card invalid.");
                                return false;
                            }
                            
                            return true; // at this point card has not been proven to be invalid
                            }
function ltrim(string) {
    string=new String(string);
    var string1=new Array();
    var i,j;
    for(i=0,j=0;i<string.length;i++) {
        if(j==0) {
            if(string.charAt(i)!=" ") string1[j++]=string.charAt(i);
        }
        else string1[j++]=string.charAt(i);
    }
    string="";
    for(i=0;i<string1.length;i++) string+=string1[i];
    return string;
}
function rtrim(string) {
    string=new String(string);
    var string1=new Array();
    var i,j;
    for(i=string.length;i>=0;i--) {
        if(string.charAt(i-1)==" ") continue;
        else {
            for(j=0;j<i;j++) string1[j]=string.charAt(j);
            break;
        }
    }
    string="";
    for(i=0;i<string1.length;i++) string+=string1[i];
    return string;
}
function trim(string) {
    string=ltrim(string); //  This function is used to trim the left side of a String
    string=rtrim(string);// This function is used to trim the right side of a String
    return string;
}


function frmcheck() {
    if(trim(document.CHECKOUT.FIRSTNAME.value).length<1) {
        alert("Please enter your First Name. eg. John");
        document.CHECKOUT.FIRSTNAME.focus();
        return false;
    }
    if(trim(document.CHECKOUT.LASTNAME.value).length<1) {
        alert("Please enter your Last Name. eg. Smith");
        document.CHECKOUT.LASTNAME.focus();
        return false;
    }	
    if(trim(document.CHECKOUT.STREET.value).length<1) {
        alert("Please enter Street");
        document.CHECKOUT.STREET.focus();
        return false;
    }
    if(trim(document.CHECKOUT.CITY.value).length<1) {
        alert("Please enter City");
        document.CHECKOUT.CITY.focus();
        return false;
    }
    if(trim(document.CHECKOUT.ZIP.value).length<1) {
        alert("Please enter zip code");
        document.CHECKOUT.ZIP.focus();
        return false;
    }
    if(trim(document.CHECKOUT.STATE.value).length<1) {
        alert("Please choose a State");
        document.CHECKOUT.STATE.focus();
        return false;
    }
	if(document.CHECKOUT.COUNTRY.value == "United States" && (document.CHECKOUT.STATE.value =="" || document.CHECKOUT.STATE.value =="N/A")){
        alert("Please choose a State when United States is selected as country");
        document.CHECKOUT.STATE.focus();
        return false;		
	}
	if(document.CHECKOUT.COUNTRY.value == "Canada" && (document.CHECKOUT.STATE.value =="" || document.CHECKOUT.STATE.value =="N/A" )){
        alert("Please choose a State when Canada is selected as country");
        document.CHECKOUT.STATE.focus();
        return false;		
	}	
    if(trim(document.CHECKOUT.COUNTRY.value).length<1) {
        alert("Please choose a country");
        document.CHECKOUT.COUNTRY.focus();
        return false;
    }	
    if(trim(document.CHECKOUT.PHONE.value).length<1) {
        alert("Please enter Phone");
        document.CHECKOUT.PHONE.focus();
        return false;
    }
    var email=new String(document.CHECKOUT.EMAIL.value);
    if(email!='') {
        if(email.indexOf("@")==-1 ||  email.indexOf(".")==-1 || email.indexOf("@") > email.lastIndexOf(".")) {
            alert("Please enter a valid Email");
            document.CHECKOUT.EMAIL.focus() ;
            return false;
        }
    }
    else {
        alert("Please enter Email");
        document.CHECKOUT.EMAIL.focus() ;
        return false;
    }	
    var cardtypeselected = '';
    for(var i=0 ; i < document.CHECKOUT.CARDTYPE.length ; i++  ) {
        if(document.CHECKOUT.CARDTYPE.options[i].selected == true ) {
            cardtypeselected = document.CHECKOUT.CARDTYPE.options[i].value ;
        }
    }
    if(trim(document.CHECKOUT.CREDITNAME.value).length<1 || trim(document.CHECKOUT.CREDITNAME.value).indexOf(" ")<0) {
        alert("Please enter the Full Name on your credit card. eg. John Smith");
        document.CHECKOUT.CREDITNAME.focus();
        return false;
    }
    if (document.CHECKOUT.CREDITNUMBER.value.length == 0) {
        alert("Please enter a Card Number.");
        document.CHECKOUT.CREDITNUMBER.focus();
        return false;
    }
	if(cardtypeselected=='A'){
		if(checkCreditCard(document.CHECKOUT.CREDITNUMBER.value,'AmEx')==false){
			alert (ccErrors[ccErrorNo]);
			document.CHECKOUT.CREDITNUMBER.focus();
			return false;
		}
	}
	if(cardtypeselected=='M'){
		if(checkCreditCard(document.CHECKOUT.CREDITNUMBER.value,'MasterCard')==false){
			alert (ccErrors[ccErrorNo]);
			document.CHECKOUT.CREDITNUMBER.focus();
			return false;
		}
	}
	if(cardtypeselected=='V'){
		if(checkCreditCard(document.CHECKOUT.CREDITNUMBER.value,'Visa')==false){
			alert (ccErrors[ccErrorNo]);
			document.CHECKOUT.CREDITNUMBER.focus();
			return false;
		}
	}
	if( expired(document.CHECKOUT.EXPMONTH.value,document.CHECKOUT.EXPYEAR.value) ) {                          // check if entered date is already expired.
    	alert("Sorry! The expiration date you have entered would make this card invalid.");
        return false;
	}			
    if( document.CHECKOUT.CVV2.value==""){
        alert("CVV2/CVC2 is mandatory for the card type you have selected. Please enter the CVV2/CVC2 number.");
        document.CHECKOUT.CVV2.focus();
        return false;
    }
	
    var cvv = parseInt(document.CHECKOUT.CVV2.value);
	
	
	
	 if( isNaN(cvv)){
        alert("CVV2/CVC2 is mandatory for the card type you have selected. Please enter the CVV2/CVC2 number.");
        document.CHECKOUT.CVV2.focus();
        return false;
    }
	
	
    if((cardtypeselected=='A' && document.CHECKOUT.CVV2.value.length!=4) || (cardtypeselected!='A' && document.CHECKOUT.CVV2.value.length!=3)){
        if (cardtypeselected=='A') alert("CVV2/CVC2 has to be 4 digits for American Express.");
        else alert("CVV2/CVC2 has to be 3 digits for Visa, Mastercard, and Discover.");
        document.CHECKOUT.CVV2.focus();
        return false;
    }
    if(document.CHECKOUT.CREDITNUMBER.value==""){
        alert("Card Number cannot be empty!");
        document.CHECKOUT.CREDITNUMBER.focus();
        return false;
    }
}
