﻿function  validateAbroadCC( CardType,CardNumber,expireMonth,expireYear,CardValidityMsg,NumOfDigitsMsg,WrongNumberMsg,WrongCompany)
{
	
	// card Type:	1: visa 
	//		2: isracard 
	//		3: mastercard 
	//		4: American Express 
	//		5: Diners 
	//		6: Ashmoret
	//		7: Prepaid Debit
	//		8: UK Maestro
	//		9: Maestro International (includes Solo and Switch)
	//		10: Safe Charge Dev
	//		11: Visa Electron

	var errDesc,lsNumber;
	var lsChar;		//an individual character
	var lnTotal;	//Sum of all calculations
	var lnDigit;	//A digit found within a credit card number
	var lnPosition; //identifies a character position in a string
	var lnSum ;		//Sum of calculations for a specific set
	var lnMultiplier;
	var isValid=true;
	
	var arrErr=new Array();
	arrErr[0]="";
	arrErr[1]=CardValidityMsg;
	arrErr[2]=NumOfDigitsMsg;
	arrErr[3]=WrongNumberMsg;
	arrErr[4]=WrongCompany;
	var toDay=new Date();
	errDesc="";
	
	// check expiry date
	if (expireYear < toDay.getYear() || (expireYear ==toDay.getYear() && expireMonth < (toDay.getMonth()+1))) 
	{
		 isValid=false;
	     errDesc=arrErr[1];	     
	     alert(errDesc);
	     return isValid;
	}
    
    // check if Mestro (Solo or Switch as well), Safe Charge Dev, Visa Electron
    if(!(CardType>=8 && CardType<=11) )
    {
		
			// Strip all characters that are not numbers.
			// Loop through each character in the card number submited
		 var pos=0;	
			var lsNumber="";
			lnTotal=0;
			while(pos<=CardNumber.length)
			{
				lsChar=CardNumber.substr(pos,1 ); //Grab the current character
				if (!lsChar.isNaN)
				{
					lsNumber = lsNumber +lsChar;
				}
				pos=pos+1;		
			}
			//The credit card number must be between 13 and 16 digits.
			if (lsNumber.length<13  && lsNumber.length != 8 && lsNumber.length != 9)
			{ 	   
				isValid=false;
				errDesc=arrErr[2];   
				alert(errDesc);
				return isValid;		
			}
			if (lsNumber.length > 16)
			{
				isValid=false;
				errDesc=arrErr[2]; 
			      	alert(errDesc);
				return isValid;
			}
		 //********************************************
		 //**   -- The credit card number must start with:
		 //**   -- 4 for Visa Cards
		 //**   -- 34,37 for American Express Cards
		 //**   -- 51 to 55 for MasterCards
		 //**   -- 30,36,38 for Diners
		 //********************************************   
		 
		 //Choose action based on type of card
			// visa:
			if (CardType=="1"){
				if  (lsNumber.substr(0,1) != "4"){
					isValid=false;
					errDesc=arrErr[4]; 
					alert(errDesc);
					return isValid;
				}          	
			}
		 //American Express
		 if (CardType=="4" ){
			    if (lsNumber.substr(0,2) !="37" && lsNumber.substr(0,2) !="34"){ 
					isValid=false;
					errDesc=arrErr[4]; 
			        alert(errDesc);
					return isValid;
			    }
			}
 
		 //Mastercard
		 if (CardType=="3" ){  
				if (lsNumber.substr(0,2) !="51" && lsNumber.substr(0,2) !="52" && lsNumber.substr(0,2) !="53" && lsNumber.substr(0,2) !="54" && lsNumber.substr(0,2) !="55"){
					isValid=false;
					errDesc=arrErr[4]; 
					alert(errDesc);
					return isValid;            
		     }
			}
		  //Diners
		 if (CardType=="5"){
		     if (lsNumber.substr(0,2) !="30" && lsNumber.substr(0,2) !="36" && lsNumber.substr(0,2) !="38"){ 
					isValid=false;
					errDesc=arrErr[4];
					alert(errDesc);
					return isValid;             
		     }
			}
		     
		// If the credit card number is less then 16 digits add zeros
		// to the beginning to make it 16 digits.
		if (lsNumber.length > 9 && CardType != "6")
		{	
  			while  (lsNumber.length < 16)
			{    
			    //Insert 0 to the beginning of the number
			    lsNumber = "0" + lsNumber;    
			}
		 
		 //Multiply each digit of the credit card number by the corresponding digit of
		 //the mask, and sum the results together.
		 
		 //Loop through each digit
  			lnPosition = 0; 
			while (lnPosition<16)
			{
			  	//Parse a digit from a specified position in the number
		     lnDigit = lsNumber.substr(lnPosition,1);
		          
			    //Determine if we multiply by:
		     // 1 (Even)
			    // 2 (Odd)
			    // based on the position that we are reading the digit from
		     lnMultiplier = 1 + ((lnPosition+1) % 2);
		     
		     // Calculate the sum by multiplying the digit and the Multiplier
			    lnSum = lnDigit * lnMultiplier;
		     
		     // (Single digits roll over to remain single. We manually have to do this.)
		     // If the Sum is 10 or more, subtract 9
			    if (lnSum > 9 )
				{
					lnSum =lnSum - 9;
		     }
		 	// Add the sum to the total of all sums
		    	lnTotal = lnTotal + lnSum;
		 	lnPosition++;
		 }

			//Once all the results are summed divide
			// by 10, if there is no remainder then the credit card number is valid.
   
			if ((lnTotal % 10) == 0)
			{ 
				errDesc=arrErr[0]; 
			}
			else
			{        
				isValid=false;
				errDesc=arrErr[3];
				alert(errDesc);
			   	return isValid;             
		 }
		} 
		else
		{
				while  (lsNumber.length < 9)
				{    
				    	//Insert 0 to the beginning of the number
				    	lsNumber = "0" + lsNumber;    
				}
				// 	multiply number by increasing numbers e.g.
				//	0 1 0 8 3 0 5 2 9	-- the number
				//	9 8 7 6 5 4 3 2 1	-- the multiply
				lnMultiplier = 9
				lnPosition = 0 
				lnTotal=0;
				while (lnPosition<9)
				{
					lnDigit = parseInt(lsNumber.substr(lnPosition,1));     
					lnTotal = lnTotal + (lnDigit * lnMultiplier);
					lnPosition=lnPosition+1;
					lnMultiplier = lnMultiplier-1;
				}
				if ((lnTotal % 11) == 0)
				{ 
				        IerrDesc=arrErr[0]; 
				}
				else
				{
				      	isValid=false;
					errDesc=arrErr[3];
					alert(errDesc);
				   		return isValid;  
				}
		} 
		 if (errDesc!="")
		{
			alert(errDesc);
		}
		errDesc="";
		return isValid;	
	}
	else
	{
		
		//credit cards Maestro (inculdes Solo and Switch), Visa Electoron, Safe Charge Dev
		
		var CardName;
		
		switch (CardType)
		{
			case "8":
				// UK Maestro
			case "9":
				// Maestro International
				CardName = "Maestro";
				break;
			case "10":
				CardName = "Safe Charge Dev";
				break;
			case "11":
				CardName = "VisaElectron";
				break;
		}
		
		if(!ValidateSafeChargeCC(CardNumber,CardName))
		{	
			alert(ccErrors[ccErrorNo]);
			return false;
		}
		else 
			return true;
			
		//return true;	
	}
		
}


/*============================================================================*/

/*

This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on 
the web, although the best is probably on Wikepedia ("Credit card number"):

  http://en.wikipedia.org/wiki/Credit_card_number

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request
Updated:    27th Nov. 2006      Additional cards added from Wikipedia
Updated:    18th Jan. 2008      Additional cards added from Wikipedia
Updated:    26th Nov. 2008      Maestro cards extended

*/

/*
   If a credit card number is invalid, an error reason is loaded into the 
   global ccErrorNo variable. This can be be used to index into the global error  
   string array to report the reason to the user if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

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 ValidateSafeChargeCC(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: "36,54,55",
               checkdigit: true};
  cards[3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305",
               checkdigit: true};
  cards[4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards[5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,622,64,65",
               checkdigit: true};
  cards[6] = {name: "JCB", 
               length: "16", 
               prefixes: "35",
               checkdigit: true};
  cards[7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  // Maestro inculdes Solo and Switch cards (added their unique prefixes to Maestro prefixes)!!!
  cards[8] = {name: "Maestro", 
               length: "12,13,14,15,16,18,19", 
               prefixes: "6334,6767,4903,4905,4911,4936,564182,633110,6333,6759,5018,5020,5038,6304,6759,6761,560054,589261,601382,670695,6709,6725",
               checkdigit: true};
  cards[9] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913,4508,4844,405670,4312,440753,4599,4935,402360,416039,416451,416896,440622,446157,446158,479056,4920",
               checkdigit: true};
  cards[10] = {name: "Safe Charge Dev",
				length: "16",
				prefixes: "4,5020,6",
				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;
}

/*============================================================================*/



/**********************************   OLD SAFE CHARGE FUNCTION (25-Feb-09) ****************************

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";
	
//credit cards Maestro & Visa Electoron 
function OLD________ValidateSafeChargeCC(CreditCardTypeId,CardNumber)
{
	
	
	
	var cards = new Array();

	

	 cards [0] = {name: "Maestro",
			   creditCardTypeId: "8,9",
               length: "16,18", 
               prefixes: "5020,6",
               checkdigit: true};
	 cards [1] = {name: "VisaElectron", 
			   creditCardTypeId: "11",
               length: "16", 
               prefixes: "417500,4917,4913",
               checkdigit: true};
               
      cards [1] = {name: "Safe Charge Dev", 
			   creditCardTypeId: "10",
               length: "16", 
               prefixes: "4,5020,6",
               checkdigit: true};
               
    // Establish card type
  var cardType = -1;
  var foundCardType = false;
  for (var i=0; i<cards.length; i++) {
	
	var creditCardTypes = cards[i].creditCardTypeId.split(",");
	
	for (var j=0;j<creditCardTypes.length;j++)
	{
		if (CreditCardTypeId == creditCardTypes[j]) 
			{
				cardType = i;
				foundCardType= true;
				break;
			}//if
			
	}//for
	
		if(foundCardType)
				break;	
	
    
  }//for
  
  
  // 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;
 
  
  
}

*************************************************************************************************/