Merge pull request #2916 from NileemaJadhav/HR-13-fix
[civicrm-core.git] / templates / CRM / Core / BillingBlock.js
1 // http://civicrm.org/licensing
2 (function($) {
3
4 /**
5 * Adds the icons of enabled credit cards
6 * Handles clicking on a icon.
7 * Changes the icon depending on the credit card number.
8 * Removes spaces and dashes from credit card numbers.
9 */
10 function civicrm_billingblock_creditcard_helper() {
11 $.each(CRM.config.creditCardTypes, function(key, val) {
12 var html = '<a href="#" title="' + val + '" class="crm-credit_card_type-icon-' + key + '"><span>' + val + '</span></a>';
13 $('.crm-credit_card_type-icons').append(html);
14
15 $('.crm-credit_card_type-icon-' + key).click(function() {
16 $('#credit_card_type').val(val);
17 $('.crm-container .credit_card_type-section a').css('opacity', 0.25);
18 $('.crm-container .credit_card_type-section .crm-credit_card_type-icon-' + key).css('opacity', 1);
19 return false;
20 });
21 });
22
23 // Hide the CC type field (redundant)
24 $('#credit_card_type, .label', '.crm-container .credit_card_type-section').hide();
25
26 // Select according to the number entered
27 $('.crm-container input#credit_card_number').change(function() {
28 var ccnumber = cj(this).val();
29
30 // Remove spaces and dashes
31 ccnumber = ccnumber.replace(/[- ]/g, '');
32 cj(this).val(ccnumber);
33
34 // Semi-hide all images, we will un-hide the right one afterwards
35 $('.crm-container .credit_card_type-section a').css('opacity', 0.25);
36 $('#credit_card_type').val('');
37
38 civicrm_billingblock_set_card_type(ccnumber);
39 });
40 }
41
42 function civicrm_billingblock_set_card_type(ccnumber) {
43 // Based on http://davidwalsh.name/validate-credit-cards
44 // See also https://en.wikipedia.org/wiki/Credit_card_numbers
45 var card_types = {
46 'mastercard': '5[1-5][0-9]{14}',
47 'visa': '4(?:[0-9]{12}|[0-9]{15})',
48 'amex': '3[47][0-9]{13}',
49 'dinersclub': '3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
50 'carteblanche': '3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
51 'discover': '6011[0-9]{12}',
52 'jcb': '(?:3[0-9]{15}|(2131|1800)[0-9]{11})',
53 'unionpay': '62(?:[0-9]{14}|[0-9]{17})'
54 }
55
56 var card_values = {
57 'mastercard': 'MasterCard',
58 'visa': 'Visa',
59 'amex': 'Amex',
60 'dinersclub': 'Diners Club',
61 'carteblanche': 'Carte Blanche',
62 'discover': 'Discover',
63 'jcb': 'JCB',
64 'unionpay': 'UnionPay'
65 }
66
67 $.each(card_types, function(key, pattern) {
68 if (ccnumber.match('^' + pattern + '$')) {
69 var value = card_values[key];
70 $('.crm-container .credit_card_type-section .crm-credit_card_type-icon-' + key).css('opacity', 1);
71 $('select#credit_card_type').val(value);
72 return false;
73 }
74 });
75 }
76
77 civicrm_billingblock_creditcard_helper();
78
79 $(function() {
80 $('#billing-payment-block').on('crmFormLoad', civicrm_billingblock_creditcard_helper);
81 });
82 })(CRM.$);