/*  ================================================================    Code by Bill Taylor btaylor@taylormade.com.au     This code may be freely used in full or in part provided this banner is included          Code tested with IE3W95 and IE4.5, NS4.6 Macintosh 	         ================================================================ */  //set these in the caling page after the script is calledvar cards_accepted_list = ''; //eg 'Amex,Visa,Mastercard,DinersClub');var cvv_for = ''; //card types that require cvv eg'Amex,DinersClub';//make cvv_for = cards_accepted_list to always show cvvvar display_pin = false; var pin_chcek_length= 7;var strict_pin_check = false;   function isNumber(num) {   return !isNaN(num);  }      function isposint(num) {    if ( (num == "") || (num <=0) ) {        return false;    }    for (var i=0; i < num.length; i++) {       var ch= num.substring (i, i+1)       if (ch < "0" || ch > "9" ) {       	            return false;       }    }    return true;}//must force n to string in older javascript function twodp(n) {   // (is.js < 1.1) {   n+=.005;     ns = " "+n;    ns = ns.substring(1,ns.length);  // }  //else {   // var ns = n.toString();   //}    var dp = ns.indexOf(".");   if (dp < 0) ns = ns+".00";   else if (dp == ns.length-2) ns = ns+"0";   else if (dp < ns.length-1) ns = ns.substring(0,dp+3);   return ns;       }// replace quotes et al for hidden fields in faxform dq =" Dequote"function dq(x) {   x = xchange(x,"\n",":");   x = xchange(x,"\"","'");   return x;}function xchange(data,oldS,newS) { if ((oldS.length == 0) || (data.length==0)) return data;  for (var i=0; i<data.length; i++) {   if (data.substring(i,i+oldS.length) == oldS) {    data = data.substring(0,i)+newS+data.substring(i+oldS.length,data.length)    }   }  return data}function validate(theform) {if (runtimepass == 1) {runtimepass=0;return false;}    //client, catupdate, reference    	with (theform) {	var CclientFirstname = clientFirstname.value     var CclientLastname  = clientLastname.value;	var CClient = "";	if (salutation.selectedIndex > 0) CClient = salutation.options[salutation.selectedIndex].text + " ";	client.value = CClient + CclientFirstname +" " + CclientLastname;	//CClient = client.value;		var CStreet = Street.value;	var CSuburb = Suburb.value;    var CState = State.value;    var CReference = Reference.value;    if (CReference == "Use for comments or reference") CReference = "";    reference.value = CReference;        var CCountry = Country.value;  //   if ((CCountry=="USA") || (CCountry=="U.S.A.") || (CCountry=="United States") || (CCountry=="United States of America")) {  //  alert("Sorry we cannot ship to the United States, please contact us for further information");  //  return false;  //  }    var CPostCode = PostCode.value;     var CPhone = Phone.value;        var CEmail = ClientEmail.value;    //var sender = "sales@interpet.biz"    if (!CouldBeEmail(CEmail)) {    alert ("Please supply a valid email address");    return false;    } else {    email.value=CEmail;    }           if(PayBy.value=="PayPal")  {CardNumber.value = ""; CardExpires.value=""; NameOnCard.value="";}       var CCardNumber   = CardNumber.value;    var CNameOnCard  = NameOnCard.value;    var CExpires = CardExpires.value;    var CserverMonth = serverMonth.value * 1;    var CserverYear = serverYear.value * 1;    CType = isCardType(CCardNumber);    CardType.value = CType;        /*      var catstr = "Do not notify when there are product updates";    if (catupdate.checked) catstr ="Notify when there are product updates";    catalog.value = catstr;	*/        if((CCardNumber=="") && (CReference=="") && (PayBy.value=="CreditCard")){    alert("Please enter Credit Card Details or a reference as to the method of payment");    return false;    }     if (CCardNumber  != "") {  if ((CType != "Visa") && (CType != "MasterCard"))      {        var m = "";      if (CType == "invalid") m = "Your card number is not valid";      else if (CType == "unknown") m = "I cannot identify the type of card you are using";      else m = "Sorry we do not accept "+CType+" cards";      alert(m);       return false;     }          if ((CNameOnCard == "") || (CExpires == "")) {       alert("Please enter the Name on your Credit card as well as the card expiry date");       return false;  }           CCardNumber = FormatCard(CCardNumber);       CardNumber.value = CCardNumber;    //Check Expiry date   var ExpireOK = isValidExipry(CExpires,CserverYear,CserverMonth);   if(!ExpireOK) {      alert("Invalid Card Expiry date " + CExpires);      return false;    }       CExpires = FormatExpiry(CExpires);    CardExpires.value = CExpires;  }    if ((CclientLastname=="") || (CclientFirstname == "") ||  (CStreet == "") || (CSuburb == "") || (CPostCode == "") ) {    alert("Please supply Name, full address including postcode and your email address");    return false;    }} //with 	return true;}function CouldBeEmail(email) {  //no spaces, an @, a dot somewhere after the @  if (email.indexOf(" ") != -1) return false;  var at = email.indexOf("@");  if (at < 1) return false;  var lastdot = email.lastIndexOf(".");  if (lastdot < at) return false;  return true; }   /*  ================================================================    FUNCTION:  isCreditCard(st)     INPUT:     st - a string representing a credit card number    RETURNS:  true, if the credit card number passes the Luhn Mod-10		    test.	      false, otherwise    ================================================================ */function trim (data) {   var cn = "";   var c="";    var L = data.length   if (L > 0) {     for (var i=0; i< L;i++) {        c = data.substring(i,i+1);     if ((c >="0") && (c <= "9")) cn += data.substring(i,i+1)    }   }   return  cn; }         function FormatCard (cnum) {   cnum = trim(cnum);   var  fcnum ="";  for (var i = 4; i<= 16; i +=4)  fcnum += cnum.substring(i-4,i)+" ";  return fcnum; }  function FormatExpiry (edate) {   edate = trim(edate)   if (edate.substring(0,1) > 1) edate = "0"+edate;   edate = edate.substring(0,2) + "/" + edate.substring(edate.length - 2,edate.length);   return edate;   }function verifyCardType(cn,cards_accepted_list) {//just check first two letters against lis vis,mas,ame, din ct = isCardType(cn); rv = ""; clistA = cards_accepted_list.split(","); for(c=0;c<clistA.length;c++) {   if(ct.substring(0,3).toLowerCase()==clistA[c].substring(0,3).toLowerCase()) {      rv = ct;     break;   } } if (rv=="" && ct !="") { // alert ("Sorry  we accept " + cards_accepted_list " card(s) only"); } return rv;}function isCreditCard(cn) {  var sum = 0;   var mul = 1;   var tproduct = 0;  var l = cn.length;  for (i = l-1; i >= 0; i--) {     var digit = cn.substring(i,i+1);      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)   {    return (true);    }  else {    return (false);   }}function isVisa(cc){  if (((cc.length == 16) || (cc.length == 13)) &&      (cc.substring(0,1) == 4))    return true;  return false;}  // END FUNCTION isVisa()function isMasterCard(cc){  firstdig = cc.substring(0,1);  seconddig = cc.substring(1,2)*1;  if ((cc.length == 16) && (firstdig == 5) &&      ((seconddig >= 1) && (seconddig <= 5))) {      return true;    }  return false;} // END FUNCTION isMasterCard()function isAmericanExpress(cc){  firstdig = cc.substring(0,1);  seconddig = cc.substring(1,2);  if ((cc.length == 15) && (firstdig == 3) &&      ((seconddig == 4) || (seconddig == 7)))    return true;  return false;} // END FUNCTION isAmericanExpress()function isDinersClub(cc){  firstdig = cc.substring(0,1);  seconddig = cc.substring(1,2);  if ((cc.length == 14) && (firstdig == 3) &&      ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))    return true;  return false;}function isBankCard(cc){  firstdig = cc.substring(0,1);  seconddig = cc.substring(1,2);  if ((cc.length == 16) && (firstdig == 5) && (seconddig == 6))    return true;  return false;}function isCardType (CardNumber){   var cc=trim(CardNumber);    if (!isCreditCard(cc)) return "invalid";    if (isVisa(cc)) return "Visa";    if (isMasterCard(cc)) return "MasterCard";    if (isBankCard(cc)) return "BankCard"; //bankcard now defunct    if (isAmericanExpress(cc)) return "Amex";    if (isDinersClub(cc)) return "DinersClub";     return "unknown";}function isValidExipry(data,thisyr,thismth) {// of the form mm(CHAR)yy or mmyy// check using server timevar m=0;if (data.length < 3) return false;var m = data.substring(0,1);if (!isposint(m) && m !=0) return false;if (m > 1)  data = "0"+data;m = data.substring(0,2);if (!isposint(m) || (m < 1) || (m >12)) return false;var y = data.substring(data.length - 2,data.length)if ((y.length != 2) && (y.length != 4) && (!isposint(y))) return false; expy = 2000 + y*1;if ((expy < thisyr) || ((expy == thisyr) && (m*1 <= thismth)) ) return false;return true;}function CheckExpiry(data) {var m=0;td = new Date();thisyr = td.getFullYear();thismth = td.getMonth();if (data.length < 3) return false;var m = data.substring(0,1);if (!isposint(m) && m !=0) return false;if (m > 1)  data = "0"+data;m = data.substring(0,2);//if (!isposint(m) || (m < 1) || (m >12)) alert ("Expiry Date: " + data + " is incorrect. Please check it and confirm it is entered thus: mm/yy");var y = data.substring(data.length - 2,data.length)//if ((y.length != 2) && (y.length != 4) && (!isposint(y))) alert ("Expiry Date: " + data + " is incorrect, Please use the date on your card. Please check it and confirm it is entered thus: mm/yy");expy = 2000 + y*1;//if ((expy < thisyr) || ((expy == thisyr) && (m*1 <= thismth))) alert ("Expiry Date: " + data + " is in the past, Please use the date on your card. Please check it and confirm it is entered thus: mm/yy");if ((expy - thisyr > 10) )  {runtimepass = 1;//alert ("Expiry Date: " + data + " is in excess of 10 years from now, Please check it and confirm it is entered thus: mm/yy");return false;}return true;}runtimepass =0;ct=0;total = 0;function displayOrder() {sep = "\n";fsep = "$";thetext="";cname = "iorder";curorder = unescape(getCookieValue(cname));order =  unescape(getCookieValue(cname)).split(sep);total =0;ct=0;thetext+=('<tr><td><B>Product</B></td><td align="center"><B>Cost</B></td><td align="center"><B>Qty</B></td><td align="center"><B>Total</B></td><td></td></tr>\n');thetext+=('<tr><td colspan=4><Hr size=1></td></tr>\n');for (i=0;i<order.length;i++) {if (order[i].length > 0 && curorder != "undefined") { p = order[i].split(fsep); productPrice = p[0]+fsep+p[1]; thetext +=('<tr><td>'+p[0]+'</td><td align="Right">$ '+twodp(p[1])+'</td><td align="Right">'+p[2]+'</td><td align="Right">$ '+twodp(p[1]*p[2])+'</td>\n'); total +=p[1]*p[2]; ct += parseInt(p[2]);  thetext +=('<td><Input type="hidden" NAME="OrderPart_'+i+' VALUE="VALUE="'+p[2]+' x '+p[0]+' each $'+twodp(p[1])+' = $' + twodp(p[1]*p[2]) +'"</td></tr>\n'); }}  if (ct > 0) {     cs= unescape(getCookieValue("iorderStatus")).split(",");     // cs = "0,50,3.5,250 or 2.5,50,3.5,250  //alert (cs[0] + " " + cs[1] + " " + cs[2] + " " + cs[3]);  (cs[0]==0)?ins=0:ins = cs[0]+1*Math.ceil(total/cs[1]);  (total<cs[3])?freight = cs[2]:freight=0;  fullcost = total+freight;  thetext+=('<tr><td colspan=4><Hr size=1></td></tr>\n');     thetext +=('<tr><td colspan=2>Product Totals</td><td align="Right">'+ct+'</td><td>$'+twodp(total)+'</td>');     thetext +=('<td><input type="hidden" name="Pieces" value="'+ct+'"><input type="hidden" name="subTotal" value="'+twodp(total)+'"></td></tr>\n');    thetext+=('<tr><td colspan=4><Hr size=1></td></tr>\n');    thetext+= ('<tr><td colspan=3>Freight Charge</td><td align="Right">$'+twodp(freight)+'</td>');     thetext+=('<td><input type=hidden name ="Freight" value="'+twodp(freight)+'"></td></tr>\n');   if (ins>0) {     thetext+= ('<tr><td colspan=3>Insurance</td><td align="Right">$'+twodp(ins)+'</td>');     thetext+=('<td><input type=hidden name ="Insurance" value="'+twodp(ins)+'"></td></tr>\n');     fullcost += ins;     }else {        thetext+=('<tr><td><input type=hidden name ="Insurance" value="No"></td></tr>\n');            }      thetext+=('<tr><td colspan=4><Hr size=1></td></tr>\n');      thetext+=('<tr><td colspan=2>Full Cost</td><td></td><td align="Right">$'+twodp(fullcost)+'</td>');   thetext+=('<td><input type="hidden" name ="orderTotal" value="'+twodp(fullcost)+'"></td></tr>\n');     } else     { thetext +=('<tr><td>You have not selected anything to order</td></tr>\n');     }   thetext+=('<tr><td colspan=4><Hr size=1></td></tr>\n');    return thetext;} function getCookieValue(cookie_name) {var cv="";  if(document.cookie)   {        index = document.cookie.indexOf(cookie_name);        if (index != -1)     {            namestart = (document.cookie.indexOf("=", index) + 1);            nameend = document.cookie.indexOf(";", index);            if (nameend == -1) {nameend = document.cookie.length;}            cv = document.cookie.substring(namestart, nameend);                return cv;           }           else return "";        }} //Lodge booking additions cards_accepted_list = "";  function setCardType(cn) {
if(cn=='') {
document.getElementById('cardType').innerHTML = 'Credit';
} else {
ct = isCardType(cn);

//ct = verifyCardType(cn,cards_accepted_list);
gotit =1 ; //accept all cards
errmsg = "";
if (ct=='invalid' || ct=='unknown') {
   errmsg = 'Invalid card number entered. Enter a correct card number or empty the field to move on.';
 } 
else if(cards_accepted_list!='') {
 ca = cards_accepted_list.split(',');
 gotit = 0;
 for (c=0; c<ca.length;c++) {
  if (ct == ca[c]) {
    gotit = 1;
    break;
   }
 }
 
 if (gotit==0) {
 errmsg = "Sorry we do not accept " + ct + " cards. We do accept " + cards_accepted_list;
 
 }
}
 
 if (errmsg=="") {
 cvvd = "none";
  if (cvv_for !='') {
    ca = cvv_for.split(",");
    for(i=0;i<ca.length;i++) {
     if (ct == ca[i]) {
      cvvd = "inline;"
      break;
     }
    }
   }
   //cvvd=(ct=='Amex')?'inline':'none'; //need to display cvvd for all card types for NAB
   document.getElementById('cardNumber').value = FormatCard(cn);
   document.getElementById('cardType').innerHTML = ct;
   document.getElementById('cvvdisplay').style.display=cvvd;
 } else {
   alert(errmsg);
   document.getElementById('cardType').innerHTML = 'Credit';
   document.getElementById('cardNumber').focus();

 }
}
}

function setExpiry(ed) {
if (ed.toLowerCase()=='mm/yy'||ed=='') {
  document.getElementById('cardExpires').value = 'mm/yy';
  return true;
  } else {
 if(CheckExpiry(ed)) {
    document.getElementById('cardExpires').value = FormatExpiry(ed);
    return true;
 } else {
 alert ('Please enter card expiry as mm/yy or empty the field to move on');
     document.getElementById('cardExpires').focus();
     return false;
 }
}
}


function validateCreditCardPayment() {

err = '';
 ccname = document.getElementById('nameOnCard').value;
 ccnum = document.getElementById('cardNumber').value;
 cvv =document.getElementById('cvv').value;
 ccexp = document.getElementById('cardExpires').value;
 ccamt = document.getElementById('creditCardPayment').value;
 if (display_pin) {
 pin = document.getElementById('pin').value;

 if(pin==''  || !luhns_check(pin)) {
 err += 'A Valid Payment Notice Number must be entered\n';
 }
 }
 
 if (ccamt =='' || parseFloat(ccamt) == 0) {
   err += 'A positive amount must be entered\n';
 }
 tfee = (document.getElementById('totalfee'))?document.getElementById('totalfee').value:"";
 narrative = (document.getElementById('creditCardNarrative'))?xchange(document.getElementById('creditCardNarrative').value,';',','):"Card Payment";
 if (ccname == '') {
  err += 'No Name on Credit Card was entered\n';
 }
 if (ccnum==''){
  err += 'No credit card number was entered\n';
 } else {
 cctype = verifyCardType(ccnum,cards_accepted_list);
 if (cctype == '') {
	err += 'Only '+cards_accepted_list+' credit cards are accepted\n';
 }
 if (cctype=='Amex' && cvv=='') {
  	err += 'the 4 digit cvv number is required for ' + cvv_for + '.\n';

 }
 }
if (ccexp.toLowerCase()=='mm/yy'||ccexp=='') {
   err +='No expiry date was entered';
  } else {
 if(!CheckExpiry(ccexp)) {
  err +='an invalid expiry date was entered, it must be of the form mm/yy\n';
  }
  }
 if (ccamt==''&& tfee!='' ) {
  if (confirm('No amount has been entered but a booking fee of '+tfee+' has been calculated.\nWould you like to pay this amount?')) {
   document.getElementById('creditCardPayment').value = tfee;
   ccamt = tfee;
  } 
  }
 if(ccamt==''||ccamt==0) {
   err +='No payment amount specified\n';
 }
  if(ccamt<0) {
   err +='Negative credit card payments cannot be processed\n';
 }

 if (err!='') {
   alert ('Payment could not proceed\n'+err);
   document.getElementById('cardPaymentValid').value='';
   return false;
 } else {
   document.getElementById('cardPaymentValid').value=ccamt+';'+ccnum+';'+cctype+';'+ccexp+';'+cvv+';'+ccname+';'+narrative;
   //return true;
   alert("Form validated: NOTE this is a mock up no action will occur");
   return false;
 }
}
function getCardInterface() {ci = '<TABLE>';
cvvd = (cvv_for == cards_accepted_list)?"inline":"none";if (display_pin) {ci += '<tr><td nowrap>Payment Notice Number</td><td><input  type="text" name="pin" id="pin" value="" style="width:50px;" maxlength=8 onblur="verify_pin(this.value);" /></td></tr>';
}
ci += '<tr><td nowrap>Payment Amount</td><td><input  type="text" name="creditCardPayment" id="creditCardPayment" value="67.65" style="width:50px;" maxlength=8 onblur="" /></td></tr>';
ci += '<tr><td nowrap>Card Holder Name</td><td nowrap> <input $readonly type=text id=nameOnCard name=nameOnCard value="" style="width:160px;"></td></tr>';
ci += '<tr><td nowrap><span id="cardType">Credit</span> Card Number</td><td nowrap> <input $readonly type=text id=cardNumber name=cardNumber style="width:160px;" value="" onBlur="setCardType(this.value);"></td></tr>';
ci += '<tr><td>Expires</td><td><input type=text id=cardExpires name=cardExpires $readonly style="width:60px;"  value="mm/yy" onBlur="setExpiry(this.value);" >';
ci += '<span id="cvvdisplay" style="display:'+ cvvd +';"> Card Pin <input $readonly type=text style="width:60px;" id="cvv" name="cvv" value=""></span>&nbsp;</td></tr>';
ci += '<script language="javascript">setCardType(document.getElementById("cardNumber").value);</script>';
ci += '<input type=hidden id=cardPaymentValid name=cardPaymentValid>';
ci += '<input type=hidden id=cardPaymentUpdate name=cardPaymentUpdate value=0>';
ci += '<input type=hidden id=cardPaymentTable name=cardPaymentTable >';
ci += '</table>';return ci;}function fillCardDetails(bid,table,ccdate,ccamt,ccnum,cctype,ccexp,cvv,ccname,escnarrative) {//fills card details document.getElementById('cardPaymentUpdate').value = bid;document.getElementById('cardPaymentTable').value = table;document.getElementById('cardNumber').value =ccnum;
document.getElementById('creditcard_transaction_date').value =fixDate(ccdate);document.getElementById('nameOnCard').value =ccname;document.getElementById('cardNumber').value =ccnum;
document.getElementById('cvv').value =cvv;
document.getElementById('cardExpires').value =ccexp;
document.getElementById('creditCardPayment').value = twodecplaces(ccamt);
document.getElementById('creditCardNarrative').value = unescape(escnarrative);
}function verify_pin(v) { if(!luhns_check(v)) {  alert("The Notice Number is not correct please reenter it"); } else {  showifnot8(v);  } }function showifnot8(v) { if(v.length>0 && v.length!=8) {  document.getElementById('extradetail').style.display = 'block'; }}function notempty(vx,l) {v =  vx.value.replace(' ','');vx.value = v.toUpperCase(); if(v=='') {   alert("Please enter a "+vx.name);  } else if (l>0 && v.length!=l) {   alert ("The "+ vx.name+" must be "+ l + " characters long without spaces");   }}function luhns_check(CRNC) {
CRNC = ''+CRNC;
CRNC = CRNC.replace(' ','');
if (!isNumber(CRNC) || CRNC.length<5 || CRNC.length > 8) {
 return false;
}
if (CRNC.length != 8) {
 return true;
}
s = CRNC.replace(' ','');
CRN = s.substr(0, s.length - 1);
CDx = parseInt(s.substr(s.length - 1, 1));

cdcalc = parseInt(luhns_modulus(CRN));
if (cdcalc == -1) {
 return true; //not a relevant number so let it pass
} else if(cdcalc == CDx) {
  return true;
} else {
  return false;
 }
} //End Function

function luhnstest() {
for (i=1234567; i<= 1234667; i++) {
document.write(i+' '+ luhns_modulus(i)+'<BR>');

}

}


function luhns_modulus(CRN) {
//from ANZ bank definition but set for CBA
//for this implementtaion the CRN is 7 digits long
crnstr = ""+CRN;
if (crnstr.length != pin_chcek_length  && !strict_pin_check) {
 return -1; //dummy check digit inappropriate number
} else {
wtstr = "2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1";
weights = wtstr.split( ","); // an array of integers >= length of CRN
start_left = "Y";//'[Y,N] for N use rightmost digits of weights * rightmost digit of CRN and work left
add_digits = "Y"; //[Y,N,T] if multiple digits in sum add them recursively till you get 1 or N don't or T just use the units
modulus = 10; //integer > 0
keep_zero = "Y"; //[Y,N] if N then use the subtract_from value rather than 0 as the check digit
subtract_from = 10; //0 for no subtraction otherwise subtract check digit from this to give final check digit
cdlength = 1; //assume check digit length to be 1 no information for this paraeter

CD = 0;
 for(d=0;d<crnstr.length;d++){

  if (start_left == "N") {
    wt = weights[weights.length - d -1];
  } else {
     wt = weights[d];
  }
  v = parseInt(wt) * parseInt(crnstr.substr( d, 1));
  if (add_digits == "N") {
   //do nothing
  } else if(add_digits == "T") {
    v = v.substr(v.length-1, 1);
  } else { //Y if weights are large this might be more than two digits long
   
   while(v > 9) {
    vstr = v+'';
    v = 0;
    for(l = 0;l<vstr.length;l++){
     v = v + parseInt(vstr.substr(l, 1));
     } //Next
   }
  }//Next
  
  //increment the  check digit
   CD += v;
   } //Next d
    CD = CD % modulus;
  
  if (subtract_from > CD) {
    if ((keep_zero == "N" && CD == 0) || CD > 0) {
      CD = subtract_from - CD;
     }
    }
  return CD;
 } //has 7 digits
}


