tessguefen
9/24/2015 - 11:21 PM

Miva: Single Input Credit Card Checker

Miva: Single Input Credit Card Checker

// ---- Credit Card Checker (No OPAY) ---- //
var CreditCardChecker = {
	init: function (cc_input) {

		this.cc = $(cc_input);

		this.cc.keyup(function() {
			$('.credit-card.highlighted-card').removeClass('highlighted-card');
			this.check( $(this.cc).val() );
		}.bind(this));

		if (this.cc.length > 0) {
			$('.credit-card.highlighted-card').removeClass('highlighted-card');
			this.check( $(this.cc).val() );
		}

	},

	check: function(cc_value) {

		// Card Prefex Structure
		var cardTypes = [
			{
				code: 'AMEX',
				prefixes: [
					34,
					37
				]
			},
			{
				code: 'VISA',
				prefixes: [
					4
				]
			},
			{
				code: 'MASTERCARD',
				prefixes: [
					[50, 55]
				]
			},
			{
				code: 'DISCOVER',
				prefixes: [
					6011,
					[622126, 622925],
					[644, 649],
					65
				]
			}
		];

		// Validate Which Card was Chosen
		var cc_code;
		cardTypes.forEach(function(type, index) {
			for (var i = 0; i < type.prefixes.length; i++) {
				if (typeof type.prefixes[i] === 'number') {
					if (cc_value.indexOf(type.prefixes[i]) === 0) {
						cc_code = type.code;
					}
				}
				else if (typeof type.prefixes[i] === 'object' || typeof type.prefixes[i] === 'array') {
					for (var j = type.prefixes[i][0]; j <= type.prefixes[i][1]; j++) {
						if (cc_value.indexOf(j) === 0) {
							cc_code = type.code;
						}
					}
				}
			}
		});

		// Populate Hidden Inputs
		switch(cc_code) {
			case 'AMEX':
				$('input[name="PaymentDescription"]').val('American Express');
				$('input[name="PaymentMethod"]').val('authnet:AMEX');
				$('.credit-card[data-cc-type="American Express"]').addClass('highlighted-card');
				break;
			case 'VISA':
				$('input[name="PaymentDescription"]').val('Visa');
				$('input[name="PaymentMethod"]').val('authnet:VISA');
				$('.credit-card[data-cc-type="Visa"]').addClass('highlighted-card');
				break;
			case 'MASTERCARD':
				$('input[name="PaymentDescription"]').val('MasterCard');
				$('input[name="PaymentMethod"]').val('authnet:MASTERCARD');
				$('.credit-card[data-cc-type="MasterCard"]').addClass('highlighted-card');
				break;
			case 'DISCOVER':
				$('input[name="PaymentDescription"]').val('Discover');
				$('input[name="PaymentMethod"]').val('authnet:DISCOVER');
				$('.credit-card[data-cc-type="Discover"]').addClass('highlighted-card');
				break;
			default:
				$('input[name="PaymentDescription"]').val('');
				$('input[name="PaymentMethod"]').val('');
		}
	}
}
CreditCardChecker.init('input[name="AuthorizeNet_Card_Num"]');