/*
This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on 
the web, although the best is probably on Wikepedia ("Credit card number"):

  http://en.wikipedia.org/wiki/Credit_card_number

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request
Updated:    27th Nov. 2006      Additional cards added from Wikipedia
Updated:    18th Jan. 2008      Additional cards added from Wikipedia

*/

/*
   If a credit card number is invalid, an error reason is loaded into the 
   global ccErrorNo variable. This can be be used to index into the global error  
   string array to report the reason to the user if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function checkCreditCard (cardnumber, cardname) {
       
    // Array to hold the permitted card characteristics
    var cards = new Array();
  
    // Define the cards we support. You may add addtional card types.
    
    //  Name:      As in the selection box of the form - must be same as user's
    //  Length:    List of possible valid lengths of the card number for the card
    //  prefixes:  List of possible prefixes for the card
    //  checkdigit Boolean to say whether there is a check digit
    
    cards [0] = {name: "Visa", 
                 length: "13,16", 
                 prefixes: "4",
                 checkdigit: true};
    cards [1] = {name: "MasterCard", 
                 length: "16", 
                 prefixes: "51,52,53,54,55",
                 checkdigit: true};
    cards [2] = {name: "DinersClub", 
                 length: "14,16", 
                 prefixes: "300,301,302,303,304,305,36,38,55",
                 checkdigit: true};
    cards [3] = {name: "CarteBlanche", 
                 length: "14", 
                 prefixes: "300,301,302,303,304,305,36,38",
                 checkdigit: true};
    cards [4] = {name: "AmEx", 
                 length: "15", 
                 prefixes: "34,37",
                 checkdigit: true};
    cards [5] = {name: "Discover", 
                 length: "16", 
                 prefixes: "6011,650",
                 checkdigit: true};
    cards [6] = {name: "JCB", 
                 length: "15,16", 
                 prefixes: "3,1800,2131",
                 checkdigit: true};
    cards [7] = {name: "enRoute", 
                 length: "15", 
                 prefixes: "2014,2149",
                 checkdigit: true};
    cards [8] = {name: "Solo", 
                 length: "16,18,19", 
                 prefixes: "6334, 6767",
                 checkdigit: true};
    cards [9] = {name: "Switch", 
                 length: "16,18,19", 
                 prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
                 checkdigit: true};
    cards [10] = {name: "Maestro", 
                 length: "16,18", 
                 prefixes: "5020,6",
                 checkdigit: true};
    cards [11] = {name: "VisaElectron", 
                 length: "16", 
                 prefixes: "417500,4917,4913",
                 checkdigit: true};
                 
    // Establish card type
    var cardType = -1;
    for (var i=0; i<cards.length; i++) {
  
      // See if it is this card (ignoring the case of the string)
      if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
        cardType = i;
        break;
      }
    }
    
    // If card type not found, report an error
    if (cardType == -1) {
       ccErrorNo = 0;
       return false; 
    }
     
    // Ensure that the user has provided a credit card number
    if (cardnumber.length == 0)  {
       ccErrorNo = 1;
       return false; 
    }
      
    // Now remove any spaces from the credit card number
    cardnumber = cardnumber.replace (/\s/g, "");
    
    // Check that the number is numeric
    var cardNo = cardnumber
    var cardexp = /^[0-9]{13,19}$/;
    if (!cardexp.exec(cardNo))  {
       ccErrorNo = 2;
       return false; 
    }
         
    // Now check the modulus 10 check digit - if required
    if (cards[cardType].checkdigit) {
      var checksum = 0;                                  // running checksum total
      var mychar = "";                                   // next char to process
      var j = 1;                                         // takes value of 1 or 2
    
      // Process each digit one by one starting at the right
      var calc;
      for (i = cardNo.length - 1; i >= 0; i--) {
      
        // Extract the next digit and multiply by 1 or 2 on alternative digits.
        calc = Number(cardNo.charAt(i)) * j;
      
        // If the result is in two digits add 1 to the checksum total
        if (calc > 9) {
          checksum = checksum + 1;
          calc = calc - 10;
        }
      
        // Add the units element to the checksum total
        checksum = checksum + calc;
      
        // Switch the value of j
        if (j ==1) {j = 2} else {j = 1};
      } 
    
      // All done - if checksum is divisible by 10, it is a valid modulus 10.
      // If not, report an error.
      if (checksum % 10 != 0)  {
       ccErrorNo = 3;
       return false; 
      }
    }  
  
    // The following are the card-specific checks we undertake.
    var LengthValid = false;
    var PrefixValid = false; 
    var undefined; 
  
    // We use these for holding the valid lengths and prefixes of a card type
    var prefix = new Array ();
    var lengths = new Array ();
      
    // Load an array with the valid prefixes for this card
    prefix = cards[cardType].prefixes.split(",");
        
    // Now see if any of them match what we have in the card number
    for (i=0; i<prefix.length; i++) {
      var exp = new RegExp ("^" + prefix[i]);
      if (exp.test (cardNo)) PrefixValid = true;
    }
        
    // If it isn't a valid prefix there's no point at looking at the length
    if (!PrefixValid) {
       ccErrorNo = 3;
       return false; 
    }
      
    // See if the length is valid for this card
    lengths = cards[cardType].length.split(",");
    for (j=0; j<lengths.length; j++) {
      if (cardNo.length == lengths[j]) LengthValid = true;
    }
    
    // See if all is OK by seeing if the length was valid. We only check the 
    // length if all else was hunky dory.
    if (!LengthValid) {
       ccErrorNo = 4;
       return false; 
    };   
    
    // The credit card is in the required format.
    return true;
}

function checkForm(form) {
    var error = ""; 
    first = form.elements['first'];
    last = form.elements['last'];
    jobTitle = form.elements['jobTitle'];
    org = form.elements['org'];
    address = form.elements['address'];
    city = form.elements['city'];
    state = form.elements['state'];
    postcode = form.elements['postcode'];
    phone = form.elements['phone'];
    email = form.elements['email'];
    
    price = form.elements['price'];
    method = form.elements['method'];
    var emailChck = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/;	
    var phoneChck = /^\(\d{2}\)\d{7,12}|\d{7,12}$/;
    var textChck = /^[a-zA-Z]+$/;
    var numericChck = /^[0-9]+$/;
    
    
    if(!textChck.test(first.value)) {
        error += "Please enter your first name (text only).\n";
    } 
    if(!textChck.test(last.value)) {
        error += "Please enter your surname (text only).\n";
    }
    if(trim(jobTitle.value) == '' ) {
        error += "Please enter your job title.\n";
    }
    if(trim(org.value) == '' ) {
        error += "Please enter your organisation.\n";
    }
    if(trim(address.value) == '' ) {
        error += "Please enter your address.\n";
    }
    if(!textChck.test(city.value)) {
        error += "Please enter the city where you reside (text only).\n";
    }
    if(!textChck.test(state.value)) {
        error += "Please enter the state where you reside (text only).\n";
    }
    if(!numericChck.test(postcode.value)) {
        error += "Please enter a valid postcode.\n";
    }
    if(!numericChck.test(phone.value)) {
        error += "Please enter a valid mobile or landline number.\n";
    } 
    if(!emailChck.test(email.value)) {
        error += "Please enter a valid email address.\n";
    }
    if(price.value == '') {
        error += "Please select a pricing plan.\n";
    }
    if(method.value == '') {
        error += "Please select a method of payment.\n";
    }
    /*
    if(method.value == 'Visa' || method.value == 'Mastercard') {
        amount = form.elements['amount'];
        cardName = form.elements['cardName'];
        cardNum = form.elements['cardNum'];
        if(trim(amount.value) == '') {
            error += "Please enter an amount.\n";
        }
        checkCreditCard (cardNum.value, method.value);
        if(ccErrorNo < 5) {
            error += ccErrors[ccErrorNo] + ".\n";
        }
        if(trim(cardName.value) == '') {
            error += "Please enter the name printed on this credit card.\n";
        }  
    }
    else if(method.Value == 'Cheque') {*/ 
    if(method.value == 'Cheque') {
        amount = form.elements['amount'];
        if(trim(amount.value) == '') {
            error += "Please enter an amount.\n";
        }
    }
    if(error.length > 0) {
        alert(error);
        return false;
    }
    else {	
        form.submit();
        //return true;
    }
}
    
function trim(str) {
 		return str.replace(/^\s+|\s+$/g,'');
}
 
function addPaymentDetail(form) {
    var method = form.elements['method'];
    
    if(method.value == 'Cheque') {
        var paymentDiv = document.getElementById('payment');
        paymentDiv.innerHTML = "<li><info>Please make the cheque payable to The Fundraising Summit</info></li><li><label for=\"amount\">Amount:</label><input id=\"amount\" name=\"amount\"/><em>*</em></li>";
    }
    else if(method.value == 'Visa' || method.value == 'Mastercard') {
        var paymentDiv = document.getElementById('payment');
        /*
        paymentDiv.innerHTML = "<li><label for=\"amount\">Amount:</label><input id=\"amount\" name=\"amount\"/><em>*</em></li><li><label for=\"name\">Cardholder Name:</label><input id=\"name\" name=\"cardName\"/><em>*</em></li>";
        paymentDiv.innerHTML += "<li><label for=\"cardNum\">Card Number:</label><input id=\"cardNum\" name=\"cardNum\"/><em>*</em></li><li><label for=\"expiry\">Expiry Date:</label>";
        paymentDiv.innerHTML += "<select name=\"month\" id=\"month\"><option selected=\"selected\">01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option><option>11</option><option>12</option></select>";
        paymentDiv.innerHTML += "<select name=\"year\" id=\"year\"><option selected=\"selected\">2008</option><option>2009</option><option>2010</option><option>2011</option><option>2012</option><option>2013</option><option>2014</option><option>2015</option><em>*</em></li>";
        */
        paymentDiv.innerHTML = "<li><info>Credit card payments are currently being implemented. Sorry for any inconvenience caused.</info></li>";
        
    }
}

function addPricingInfo(form) {
    var price= form.elements['price'];
    
    if(price.value == 'Early Bird Special - $645pp incl. GST') {
        var paymentDiv = document.getElementById('pricing');
        paymentDiv.innerHTML = "<info>The Early Bird Special is applicable for all registrations payed by the 25th of June 2008</info><br />";
    }
    else if(price.value == 'Standard Price - $695pp incl. GST') {
        var paymentDiv = document.getElementById('pricing');
        paymentDiv.innerHTML = "<info>The Standard Price is applicable for all registrations payed after the 25th of June 2008</info><br />";
    }
    else {
        var paymentDiv = document.getElementById('pricing');
        paymentDiv.innerHTML = "";
    }
}


