/*************************************************************************\
  Author: Simon Tneoh Chee-Boon
  Email Add.: tneohcb@pc.jaring.my
  Last Modified: 30th.Sep.2001
  Copyright (c) 1997-2001 Simon Tneoh  All Rights Reserved
    Permission to use, copy, modify, and distribute this software and its
    documentation for commercial or non-commercial purposes is hereby granted
    provided that this copyright notice appears in all copies.
  This is a demonstration of using credit card javascript object. The
  credit cards used here are the international standard card. Luhncheck is
  used to validate the card number.
\*************************************************************************/


/*************************************************************************\
  boolean luhnCheck([String CardNumber])
  return true if CardNumber pass the luhn check else return false.
  Reference: http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl
\*************************************************************************/
function luhnCheck(cardno) {
  if (! isNum(cardno)) {
    return false;
  }

  var no_digit = cardno.length;
  var oddoeven = no_digit & 1;
  var sum = 0;

  for (var count = 0; count < no_digit; count++) {
    var digit = parseInt(cardno.charAt(count));
    if (!((count & 1) ^ oddoeven)) {
      digit *= 2;
      if (digit > 9)
	digit -= 9;
    }
    sum += digit;
  }
  if (sum % 10 == 0)
    return true;
  else
    return false;
}

/*************************************************************************\
  boolean isNum(String argvalue)
  return true if argvalue contains only numeric characters,
  else return false.
\*************************************************************************/
function isNum(argvalue) {
  argvalue = argvalue.toString();

  if (argvalue.length == 0)
    return false;

  for (var n = 0; n < argvalue.length; n++)
    if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9")
      return false;

  return true;
}


/*************************************************************************\
  JustDigits(cardnumber)
  strip out everything except characters '0' to '9' from card number.
  written I.Buxton 2/10/2003
\*************************************************************************/

function JustDigits(value) {
  
  if (value.length == 0 || value == null)
     return "";

  var tmp = "";
  for (var count = 0; count < value.length; count++) {
    var ch = value.charAt(count);
    if ((ch >= "0") && (ch <= "9"))
       tmp += ch;
  }
  // alert("card = " + tmp);
  return tmp;
}

function verify()
{
	var theForm = document.forms[0];
	var prefix = "_ctl0:_ctl0:";
	var CardNum = theForm.elements[prefix + "cardnum"].value;
	CardNum = JustDigits(CardNum);
	theForm.elements[prefix + "cardnum"].value = CardNum;

	var cardType = ddLabel(theForm.elements[prefix + "cardtype"]);
	var expMonth = ddValue(theForm.elements[prefix + "cardexpmonth"]);
	var expYear  = ddValue(theForm.elements[prefix + "cardexpyear"]);
	var startMonth  = ddValue(theForm.elements["cardstartmonth"]);
	var startYear   = ddValue(theForm.elements["cardstartyear"]);
	var issueNo = theForm.elements["cardissuenumber"].value;
	var cvv2 = theForm.elements[prefix + "cardcode"].value;
	
//alert("data checks disabled for testing...");
//return true;


	if (typeof(checkCountry) == 'function') {
		if (!checkCountry()) return false;
	}


	if (typeof(CheckZip) == 'function')
	{
		if (!CheckZip())
		{
			alert("You have not included a postal code - this is required for\ncard validation. Please edit your details in the 'My account' section");
			return false;
		}
	}

	if (theForm.elements[prefix + "cardtype"].selectedIndex == 0)
	{
		alert("You have not chosen a card type");
		return false;
	}


	if (CardNum == "")
	{
		alert("Card number is invalid");
		return false;
	}

	
	if (hasExpired(expMonth, expYear))
	{
		alert("The expiry date has already passed");
		return false;
	}
	

	if (cardType == "Switch" || cardType == "Solo")
	{
		if (!hasStarted(startMonth, startYear) && (issueNo == ""))
		{
			alert("Switch/Solo valid start date or issue number required");
			return false;
		}
		
		// don't allow start date AND issue number to BOTH be entered.

		if ((issueNo != "") && (isNum(startMonth +"") || isNum(startYear+"")))
		{
			alert("Please enter EITHER a valid start date \nOR the issue number as printed \non the card (not both).");
			theForm.elements["cardissuenumber"].focus();
			return false;
		}

		if ((issueNo != "") && (!isNum(issueNo+"")) )
		{
			alert("Please enter a valid issue number");
			return false;
		}

		if ((issueNo == "0") || (issueNo == "00"))
		{
			alert("Please enter a valid issue number");
			return false;
		}

		//
		// set values for the 'hidden' fields so the XSE postback thing doesn't complain...
		if (isNum(startMonth +"") || isNum(startYear+"")) {
			theForm.elements[prefix + "cardstartmonth"].value = startMonth;
			theForm.elements[prefix + "cardstartyear"].value  = startYear;
		} else {
			theForm.elements[prefix + "cardstartmonth"].value = "01";
			theForm.elements[prefix + "cardstartyear"].value  = "01";
		}
		if (issueNo != "") {
			theForm.elements[prefix + "cardissuenum"].value   = issueNo;
		} else {
			theForm.elements[prefix + "cardissuenum"].value   = "0";
		}


	} else {
		//
		// visa / mastercard not allowed to use issue or start date

		if ((issueNo != "") || (isNum(startMonth+"") || isNum(startYear+"")))
		{
			alert("Start date/issue number are only allowed for Switch/Solo cards.");
			theForm.elements["cardissuenumber"].focus();
			return false;
		}
		
	}


	if (theForm.elements[prefix + "nameoncard"].value == "")
	{
		alert("Please enter the card holder name");
		theForm.elements[prefix + "nameoncard"].focus();
		return false;
	}

	
	if (cvv2 == "")
	{
		alert("Please enter the card CVV2 code");
		theForm.elements[prefix + "cardcode"].focus();
		return false;
	}


	if (cvv2.length > 4 || cvv2.length < 3 || (!isNum(cvv2+"")))
	{
		alert("Please enter a valid CVV2 code");
		theForm.elements[prefix + "cardcode"].focus();
		return false;
	}

	if (luhnCheck(CardNum))
	{
		// alert("card is OK!");
		// Now do the validation we were originally going to do...
		if (typeof(ValidatorOnSubmit) == 'function') ValidatorOnSubmit();
		return true;
	} else {
		alert("Card number appears to be invalid");
		return false;
	}

	// no verification needed for postal orders
	return true;
}

function ddValue(objdropdown) { return(objdropdown.options[objdropdown.selectedIndex].value); }
function ddLabel(objdropdown) { return(objdropdown.options[objdropdown.selectedIndex].text);  }

function hasExpired(month, year) {

  if (!isNum(year+""))
    return true;
  if (!isNum(month+""))
    return true;
  
  year = year * 1
  if (year < 90) year += 2000;
  if (year < 100) year += 1900;
  
  today = new Date();
  expiry = new Date(year, month);
  if (today.getTime() > expiry.getTime())
    return true;
  else
    return false;
}

function hasStarted(month, year) {

  if (!isNum(year+""))
    return false;
  if (!isNum(month+""))
    return false;
  
  year = year * 1
  if (year < 90) year += 2000;
  if (year < 100) year += 1900;
  month = month * 1
  month = month - 1
  if (month < 1){
	month += 12;
	year -= 1;
  }
  today = new Date();
  startdate = new Date(year, month);
  if (today.getTime() > startdate.getTime())
    return true;
  else
    return false;
}

// Here is the bit that resets the form details to do the verifying...
//document.forms[0].onsubmit = function MyonSubmit(event) { return verify(); };
