<script type="text/javascript">
	var PaymentValidation_{{ PaymentMethodId|raw }} = {
		cc_name: $(":input[name='paymentField[{{ PaymentMethodId|raw }}][AuthorizeNet_name]']"),
		cc_ccno: $(":input[name='paymentField[{{ PaymentMethodId|raw }}][AuthorizeNet_ccno]']"),
		cc_cccvd: $(":input[name='paymentField[{{ PaymentMethodId|raw }}][AuthorizeNet_cccode]']"),
		cc_ccexpm: $(":input[name='paymentField[{{ PaymentMethodId|raw }}][AuthorizeNet_ccexpm]']"),
		cc_ccexpy: $(":input[name='paymentField[{{ PaymentMethodId|raw }}][AuthorizeNet_ccexpy]']"),

		payment_form: $("#paymentMethodForm_{{ PaymentMethodId|raw }}"),

		checkForm: function() {
			var obj = PaymentValidation_{{ PaymentMethodId|raw }};

			if(obj.cc_name.val() == "") {
				alert("{% lang 'CCManualEnterName' %}");
				obj.cc_name.focus();
				return false;
			}

			if(isNaN(obj.cc_ccno.val()) || obj.cc_ccno.val() == "" || !obj.validateCreditCard()) {
				alert("{% lang 'CCManualEnterCardNumber' %}");
				obj.cc_ccno.focus();
				obj.cc_ccno.select();
				return false;
			}

			if(obj.requiresCVV2() && (obj.cc_cccvd.val() == "" || isNaN(obj.cc_cccvd.val()) || obj.cc_cccvd.val().length > 4)) {
				alert("{% lang 'CCManualEnterCVV2Number' %}");
				obj.cc_cccvd.focus();
				obj.cc_cccvd.select();
				return false;
			}

			if(obj.cc_ccexpm.selectedIndex == 0) {
				alert("{% lang 'CCManualEnterCreditCardMonth' %}");
				obj.cc_ccexpm.focus();
				return false;
			}

			if(obj.cc_ccexpy.selectedIndex == 0) {
				alert("{% lang 'CCManualEnterCreditCardYear' %}");
				obj.cc_ccexpy.focus();
				return false;
			}

			return true;
		},

		validateCreditCard: function() {
			var number = PaymentValidation_{{ PaymentMethodId|raw }}.cc_ccno.val();

			// Strip any non-digits (useful for credit card numbers with spaces and hyphens)
			number=number.replace(/\D/g, '');

			// Set the string length and parity
			var number_length=number.length;
			var parity=number_length % 2;

			// Loop through each digit and do the maths
			var total=0;
			for (i=0; i < number_length; i++) {
				var digit=number.charAt(i);
				// Multiply alternate digits by two
				if (i % 2 == parity) {
					digit=digit * 2;
					// If the sum is two digits, add them together (in effect)
					if (digit > 9) {
						digit=digit - 9;
					}
				}
				// Total up the digits
				total = total + parseInt(digit);
			}

			// If the total mod 10 equals 0, the number is valid
			if (total % 10 == 0) {
				return true;
			} else {
				return false;
			}
		},

		requiresCVV2: function() {
			var cvv = PaymentValidation_{{ PaymentMethodId|raw }}.cc_cccvd;
			if(cvv.length == 1) {
				return true;
			}
			else {
				return false;
			}
		}
	};
</script>