// **********************************************************************
// CreditCardValidation.js | Created On: 15th February 2008 | Sujay V Sarma
// File contains all functions to validate 
// the CreditCard Number, CreditCard Type.
// **********************************************************************


// This function returns the object for the given Id
    // id: the id of the object to retrieve
    // returns: object or null
    function ccgetDocumentObject(id) 
    {
	    var d = null;
	
	    if (document.getElementById) {
		    d = document.getElementById(id);
	    } else if (document.all) {
		    d = document.all(id);
	    }
	
	    return d;
    }
    
    // This function validates the given credit card number against the given card type
    // cardNumberFieldId - id of the field containing the credit card number
    // ctDDId - id of the field containing the card type
    function ValidateCardNumber(cardNumberFieldId, ctDDId)
    {
        var n = ccgetDocumentObject(cardNumberFieldId);
        var s, i, twice, twicesum, d1, d2, chk1, chk2, chk3, verify;
        if(ccgetDocumentObject(ctDDId))
        {
            var cardType = ccgetDocumentObject(ctDDId).value;
        }
        verify = false;
        s = n.value;
        if (s = "")
        {
            return false;
        }
        // first check if card type, card number prefix and length rules match
        switch (cardType)
        {
            case 'Mastercard':
                var dig2 = parseInt(s.substring(0,2));
                if( ((dig2 >= 51) && (dig2 <= 55)) && (s.length == 16))
                {
                    verify = true;
                }
                break;
                
//            case 'VISA':
//                if(s.startsWith('4') && ((s.length == 13) || (s.length == 16)) )
//                {
//                    verify = true;
//                }
//                break;

             case 'Visa':
                if((s.substring(0,1).toLowerCase() == "4") && ((s.length == 13) || (s.length == 16)) )
                {
                    alert("Vis");
                    verify = true;
                }
                break;
                
//            case 'American Express':
//                if (s.startsWith('34') || s.startsWith('37') && (s.length == 15))
//                {
//                    verify = true;
//                }
//                break;

             case 'American Express':
                if ((s.substring(0,2).toLowerCase() == "34") || (s.substring(0,2).toLowerCase() == "37") && (s.length == 15))
                {
                    verify = true;
                }
                break;
            
//            case 'Diners Club':
//                var pref = parseInt(s.subString(0,3));
//                if (
//                        ( 
//                            ((pref >= 300) && (pref <= 305)) || 
//                            ((pref >= 360) && (pref <= 369)) || 
//                            ((pref >= 380) && (pref <= 389))
//                         ) && 
//                         (s.length == 14)
//                    )
//                {
//                    verify = true;
//                }
//                break;
//            
//            case 'enRoute':
//                if (s.startsWith('2014') || s.startsWith('2149') && (s.length == 15))
//                {
//                    verify = true;
//                }
//                break;
//            
//            case 'Discover':
//                if (s.startsWith('6011') && (s.length == 16))
//                {
//                    verify = true;
//                }
//                break;    
                
        }
        
        // Check the numeric validity of the number only if type/number/length succeeded
        if (verify)
        {
            // remove all the dashes
            s = s.replace(/-/g,'');
        
            // pickup every alternate digit, double it and add the digits you get
            twicesum = 0;
            for (i=0; i<s.length; i=i+2)
            {
                twice = parseInt(s[i]) * 2;
                d1 = twice % 10;
                d2 = parseInt( (twice / 10).toString() );
                twicesum += (d1 + d2);            
            }
            chk1 = twicesum;
            chk2 = 0;
            
            // pickup digits not covered in above loop and add them with each other
            for (i=1; i<=s.length; i=i+2)
            {
                twice = parseInt(s[i]);
                chk2 += twice;            
            }
            
            // add both checksums
            chk3 = chk1 + chk2;
        
            // if checksum / 10 leaves no reminder, its a wellformed number
            if ((chk % 10) == 0) {
                verify = true;
            } else {
                verify = false;
            }
        }
        
        if (! verify) {
            alert('Credit card number is not valid');
        }
        
        return verify;
    }
    
  ////////////////**********************Added by Kalpesh *******************/////////////////////
  //////////////// The below function check for valid Credit card information ///////////////////
  function chkCrediCardValid(ccardnumber,ccardtype,regx)
{
  
  myCardNo = ccgetDocumentObject(ccardnumber).value;
  myRegx = ccgetDocumentObject(regx);
   
  if(ccgetDocumentObject(ccardtype))
        {
           myCardType = ccgetDocumentObject(ccardtype).value;
  }
  //myCardType = ccardtype.value;
    //alert(myCardNo.value);
  //  alert(myCardType);
   if (checkCreditCard (myCardNo,myCardType)) 
   {
    myRegx = ccgetDocumentObject(regx);
    //alert ("Credit card has a valid format")
    //alert(myRegx);
    if(myRegx != null)
      {
         ValidatorEnable(myRegx,false);
         //alert("Card");
      }
      return true;
      
  } 
  else {
   myRegx = ccgetDocumentObject(regx);
  if(myRegx != null)
  {
    
     ValidatorEnable(myRegx,true);
  }
  alert (ccErrors[ccErrorNo])};
  return false;
}


 function chkCrediCardValid2(ccardnumber,ccardtype)
{
  
  myCardNo = ccgetDocumentObject(ccardnumber).value;
 
  
  if(ccgetDocumentObject(ccardtype))
        {
           myCardType = ccgetDocumentObject(ccardtype).value;
  }
  //myCardType = ccardtype.value;
    //alert(myCardNo.value);
  //  alert(myCardType);
   if (checkCreditCard (myCardNo,myCardType)) {
    //alert ("Credit card has a valid format")
  } 
  else {
  
  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 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: "American Express", 
               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: "16,18", 
               prefixes: "5020,6",
               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;
}