/***********************************************
** File:      @(#)purchase.js	1.3
** Created:   22.2.2005
** Author:    filali
** Modified:  03/14/05
** Copyright: I-Next Ltd
**
** Description:
**   Purchase javascript
** Updates:
**   05.10.05: Add functions (allDigits, inValidCharSet, isValidCreditCardNumber, LuhnCheck) to handle credit card check
***********************************************/
/* ident @(#)purchase.js	1.2 */
function process_form(product_code,sku_code,basket_qty)
{

  // Initilialise variables
  var dummy_image = new Image();

  // check we have a purchase id to work with
  pos = document.cookie.indexOf("dorsey_ecommerce_purchase_id");

  // Check that the user accepts cookies
  if (document.cookie == ''){
    alert('Please Enable Cookies.\n\nIn order to use the Online Purchase System you need to enable cookies in your browser.\n');
  }
  else{
    // we have a purchase_id
    if (pos > -1){
      var randomnumber = Math.floor(Math.random()*10000000000000000000000000000000000000000000000001);
      var image_url = "/cgi/ecommerce/update_basket.cgi?product_code=" + product_code + "&sku_code=" + sku_code +"&quantity=" + basket_qty+'&ms='+randomnumber;
      dummy_image.src = image_url;
      alert('Your enquiry request has been successfully updated');
    }
    else{
      alert('Your cookie has not been set properly, please refresh the page.\n');
    }
  }
}

function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset)
{
	var result = true;

	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}

	return result;
}

function isValidCreditCardNumber(payment_form){

 // Set variables
 var result = true;
 var ccNum = payment_form.card_number.value;

 // Check that the number is not null
 if (payment_form.card_number.value.length > 0){

   // Check it's just numbers
   if (!allDigits(ccNum)){
     alert('Please enter only numbers (no dashes or spaces) for the card number.');
     payment_form.card_number.focus();
     return false;
   }
   else{// Check it's valid
     if (!LuhnCheck(ccNum)){
       answer = confirm ("The card number <" + ccNum + "> appears to be invalid. Please click on 'Cancel' to change it or 'OK' to confirm.");
       if (answer == true){
         return true;
       }
       else{
         payment_form.card_number.focus();
         return false;
       }
     }
     else{
       return true;
     }
   }
 }
 else{// Submit the form
   return true;
 }
}

function LuhnCheck(str)
{
  var result = true;

  var sum = 0;
  var mul = 1;
  var strLen = str.length;

  for (i = 0; i < strLen; i++)
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;

  return result;
}
