
/* Credit Card Validator
** Netscape 3.0+ compatible
** IExplore 4.0+ compatible

** Written by Roman Potashinskiy
** Last Modified 8:03 PM 8/9/00
** Copyright 1999-2001, e4orce.com. 
*/ 

// Credit Card Data:
 CCData = new Array();

                   // CARD    STARTS WITH      TTL# VSUM  CARD NAME
CCData[0] = new Array("MC", "51|52|53|54|55", 16, 10, "Master Card");
CCData[1] = new Array("VISA", "4", 16, 10, "Visa");
CCData[2] = new Array("VISA", "4", 13, 10, "Visa");
CCData[3] = new Array("DISC", "6011", 16, 10, "Discover");
CCData[4] = new Array("AMEX", "34|37", 15, 10, "American Express");
CCData[5] = new Array("DCCB", "300|301|302|303|304|305|36|38", 14, 10, "Dinners Club/Carte Blanche");
CCData[6] = new Array("JCB", "3", 16, 10, "JCB");
CCData[7] = new Array("ENR", "2014|2149", 15, 1, "enRoute");
CCData[8] = new Array("JCB", "2131|1800", 15, 10, "JCB");



function CCCheck(frm){
	var CCType = frm['Required-cardtype'].options[frm['Required-cardtype'].selectedIndex].value;
	if (CCType == CCValidator(frm['Required-cardnumber'].value)) return true;
	alert("Check Credit Card Number!");
	frm['Required-cardnumber'].focus();
	return false;
}

function CCValidator(CC){
	var CCN="";
	var CCtext = new String(CC);
	var ValNum=0;
	//clean up, leave numbers only
	for (var i=0; i< CCtext.length; i++){
		if ("0123456789".indexOf(CCtext.charAt(i))>-1) CCN += CCtext.charAt(i);	
	}
	
	// minimum 13 digits in CC number, Max 19:
	if(CCN.length < 13 || CCN.length > 19) return "";

    sum = 0; mul = 1; l = CCN.length;
    for (i = 0; i < l; i++) {
            digit = CCN.substring(l-i-1, l-i);
            tproduct = parseInt(digit, 10)*mul;
            if (tproduct >= 10)
                    sum += (tproduct % 10) + 1;
            else
            sum += tproduct;
       if (mul == 1)
                    mul++;
            else
            mul--;
    }

    ValNum =sum
	
	// Compare to correct data:
	for (var i = 0 ; i < CCData.length; i++){
		if (CCN.length !=  CCData[i][2]) continue;
		if (! (ValNum % CCData[i][3]) == 0) continue;
		if (! StartsWith(CCN, CCData[i][1])) continue;	
		return  CCData[i][0];
	} 
	return "";
}


function StartsWith(CCN, ValidNum){
	VNum = ValidNum.split('|');
	for (var i=0; i< VNum.length; i++){
		if (CCN.substring(0, VNum[i].length) == VNum[i]) return true;
	}
	return false;
}



/*************************************************
This function takes a number and return the possible credit 
card type for that number. If the card does fall in one 
of the categories, it will return a string abbreviation of it, 
possible return values are

 MC, VISA, DISC, AMEX, DCCB, JCB, ENR

If the number is not in any of the above types, it returns empty string.
***************************************************/
