// Browser tests
var IE4 = (document.all && !document.getElementById) ? true : false;
var NS4 = (document.layers) ? true : false;
var IE5 = (document.all && document.getElementById) ? true : false;
var NS6 = (document.getElementById && !document.all) ? true : false;

// Global variables to store session data
var color = '';

// Function to change colour of specified <td>
function tdOver(id, col) {
  if (IE5 || NS6) {
    color = window.document.getElementById(id).style.backgroundColor;
    window.document.getElementById(id).style.backgroundColor = col;
  }
  else if (IE4) {
    color = window.document.all[id].style.background;
    window.document.all[id].style.background = col;
  }
}

// Function to return <td> colour to original state
function tdOut(id) {
  if (IE5 || NS6) window.document.getElementById(id).style.backgroundColor = color;
  else if (IE4) window.document.all[id].style.background = color;
}

// Function to return whether a credit card number is valid or not
function isCreditCard(num) {
  if (num == 0) return (false);
  sum = 0; mul = 1; l = num.length;
  for (i = 0; i < l; i++) {
    digit = num.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--;
  }
  return (((sum % 10) == 0));
}

// Confirm a delete action
function del_confirm(itm, qs, tbl) {
  if (confirm("Are you sure you want to delete "+tbl+" id:\n\n"+itm)) window.location.href = window.location.pathname+"?action=delete&"+qs;
}

// Modified macromedia validate function to encompass credit cards
function MM_validateCCForm() { //v6.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateCCForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  }
  if (! isCreditCard(document.forms['fmOrder'].cc_number.value)) errors += '- a valid credit card number is required.\n';
  if (errors) alert('The following error(s) occurred:\n'+errors);
  return (errors == '');
}
