// Copyright (c) 1998 Sudhakar Chandrasekharan (thaths@netscape.com)
// All rights reserved
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 dated June, 1991.

// Funtion to return the type of credit card
function typeOfCard(number) {
	/* 
	//	Card Prefixes
	//
	//	Mastercard	51-55
	//	Visa		4
	//	AmEx		34,37
	//	Diners		2014,2149,30,36,
	*/

	var firstNumber = number.substring(0,1);
	var firstTwoNumbers = number.substring(0,2);
	var firstThreeNumbers = number.substring(0,3);
	var firstFourNumbers = number.substring(0,4);
	
	var numDigits = number.length

	if (firstNumber == 4 && (numDigits==13 || numDigits==16)) {
		return "VISA";
	} 

	if ((firstTwoNumbers > 50 && firstTwoNumbers < 56) && (numDigits==16)) {
		return "MASTERCARD";
	}

	if ((firstTwoNumbers == 34 || firstTwoNumbers == 37) && (numDigits==15)) {
		return "AMEX";
	}

	if ((firstFourNumbers == 2014 || firstFourNumbers == 2149 || firstTwoNumbers == 30 || firstTwoNumbers == 36) && (numDigits>13 && numDigits<17)) {
		return "DINERS";
	}
	
	return false
}

// Function that determines whether a credit card number is valid
// Please note that a valid credit card number is not essentially a
// credit card in good standing.
function isValidCreditCard(number) {
	var total = 0;
	var flag = 0;
	for (var i=(number.length - 1);i>=0; i--) {
		if (flag == 1) {
			var digits = number.charAt(i) * 2;
			if (digits > 9) digits -= 9;
			total += digits;
//			var reminder = digits % 10;
//			var quotient = (digits - reminder) / 10;
//			total = total + parseInt(reminder);
//			total = total + parseInt(quotient);
			flag = 0;
		} else {
			total = total + parseInt(number.charAt(i));
			flag = 1;
		}
	}
	if ((total%10) == 0 && typeOfCard(number)!=false) {
		return true;
	} else {
		return false;
	}
}

function checkCC(src,targ) {
	var num = ''
	for (var i=1;i<5;i++) {
		num+=document.getElementById(src + '_' + i).value
	}
	if (isValidCreditCard(num)) {
		targ.src = '/images/tick.png'
		targ.alt = 'Credit card number is valid'
	} else {
		targ.src = '/images/cross.png'
		targ.alt = 'Invalid Credit Card Number Entered'
	}
}
