//<!-- begin script

/* Adjusted for NCCC.
   This now validates the form, checking that all the details for each member of the party has
   been entered. It then saves away the start and expiry years, to be used in the initialize.
   It also contains the function for setting the cardholder's name and postcode from the
   earlier entries in the form */

/* The saving away of the start and expiry years was later stopped as a better way was to save
   these in hidden fields in the reservation form. */

/* It also now shows an alert giving the details of the charge if a credit card has been chosen
   but only if the page is being shown for the first time or if the details on the page have been
   altered. */

var card_errors;
var today;
var year;
var month;

function validateForm(form){
  if (document.form1.cust_email.value!=""){     //if the email address field is not blank go on to check whether it is valid
    if(!emailCheck(document.form1.cust_email.value))return false; //check that a valid email address has been entered;
  }
  if (!verify(form)) return false;
  
  // Show an alert if necessary if payment is by credit card.
  show_credit_charge();
  return true;
} //validateForm

function verify(form) {
  var themessage = "You have not completed the required fields correctly: ";
  if (form.first_name.value=="") {
    themessage = themessage + "\n -  First Name";
  }
  if (form.last_name.value=="") {
    themessage = themessage + "\n -  Last Name";
  }
  if (form.address1.value=="") {
    themessage = themessage + "\n -  Address1";
  }
  if (form.town.value=="") {
    themessage = themessage + "\n -  Town";
  }
  if (form.postcode.value=="") {
    themessage = themessage + "\n -  Postcode";
  }
  if((form.home_phone.value=="")&&(form.office_phone.value=="")){
    themessage = themessage + "\n -  Home or Office Phone No";
  }
  if (form.cust_email.value=="") {
    themessage = themessage + "\n -  Email Address";
  }
  if (form.prop_code.value=="") {
    themessage = themessage + "\n -  Property Code";
  }
  if (form.arrival.value=="") {
    themessage = themessage + "\n -  Arrival Date";
  }
  if (form.departure.value=="") {
    themessage = themessage + "\n -  Departure Date";
  }
  if (!check_party()) {
    themessage = themessage + "\n -  Full Details of your Party";
  }
  if ((form.linen.checked) && (form.doublebeds.value == "") && (form.single.value == "")) {
    themessage = themessage + "\n -  Make up of Beds if Linen required";
  }
  if ((form.smokers.value != "Yes")&&(form.smokers.value != "No")){
    themessage = themessage + "\n -  Smokers Within Party";
  }
  if (!form.conditions.checked){
    themessage = themessage + "\n -  Terms & Conditions not read?";
  }
  if (!check_card()) {
    themessage = themessage + card_errors;
  }
  if (themessage == "You have not completed the required fields correctly: "){
    return true;
  }
  else{
    alert(themessage);
    return false;
  }
} //verify

function check_party() {
// Checks that no party details are missing and also that there is at least one entry.

  var i;

  for (i=1; i<=12; i++) {
    var p_name = "p_name_" + i;
    var p_sex = "p_sex_" + i;
    var p_age = "p_age_" + i;
    var name = document.getElementsByName(p_name)[0];
    var sex = document.getElementsByName(p_sex)[0];
    var age = document.getElementsByName(p_age)[0];
    if (name.value) {
      if (!sex.value || !age.value) {
        return false
      }
    }
    else {
      if (i == 1) {
        return false
      }
    }
  }
  return true;
} //check_party

function check_card() {
 /* Checks that if a card number has been given a card type has been set (a card type could be
    set in error and not cleared so the reverse is not checked) and if so the card checksum is
    checked. Also checks that if there is a card number any start date shown is not in the
    future, there is a valid expiry date and a security number has been given */

  var card_type_buttons = document.getElementsByName("card_type");
  var card_no = document.getElementsByName("card_no")[0];
  var security_no = document.getElementsByName("security_no")[0];
  var card_name = document.getElementsByName("card_name")[0];
  var card_pc = document.getElementsByName("card_pc")[0];
  var sm = document.getElementsByName("start_month")[0];
  var sy = document.getElementsByName("start_year")[0];
  var em = document.getElementsByName("expiry_month")[0];
  var ey = document.getElementsByName("expiry_year")[0];

  today = new Date();
  cYear = today.getFullYear();
  cMonth = today.getMonth() + 1;
  card_errors = "\n -  Credit/Debit Card Errors:";

  // First check if there is a card number then a card type is set. Exit if no card number.
  if (!card_no.value) {
    return true
  }

  // Need to loop round the radio buttons to find which one, if any, is checked.
  var i;
  var card_type;
  for (i=0; i<card_type_buttons.length; i++) {
    if (card_type_buttons[i].checked) {
      card_type = card_type_buttons[i].value;
    }
  }
  if (!card_type) {
    card_errors += "\n        The card type is not shown";
  }

  // We've got a card number. Check the number is valid
  if (!FSfncCheckCCnum(card_no.value)) {
    card_errors += "\n        The card number is incorrect - please check";
    return false
  }

  // Check that we've been given a three-digit security number.
  if (!security_no.value) {
    card_errors += "\n        Please enter the card's security number";
  }
  else {
    if (isNaN(security_no.value) ||  security_no.value.length!=3) {
      card_errors += "\n        The security number is incorrect - please check";
    }
  }

  // Now check the start date (if given)
  if (sm.value) {
    var index = sm.selectedIndex;
    var start_month = sm.options[index].value;
    index = sy.selectedIndex;
    var start_year = sy.options[index].value;
    if ((start_year>cYear) || (start_year==cYear && start_month>cMonth)) {
      card_errors += "\n        The start date is in the future";
    }
  }

  // and then the expiry date.
  if (em.value) {
    index = em.selectedIndex;
    var expiry_month = em.options[index].value;
    index = ey.selectedIndex;
    var expiry_year = ey.options[index].value;
    if ((expiry_year<cYear) || (expiry_year==cYear && expiry_month<cMonth)) {
      card_errors += "\n        The expiry date is in the past";
    }
  }
  else {
    card_errors += "\n        No expiry date has been given";       
  }

  // Check there's a cardholders name and postcode.
  if (!card_name) {
    card_errors += "\n        The cardholder's name is not shown";
  }
  if (!card_pc) {
    card_errors += "\n        The cardholder's postcode is not shown";
  }

  // Now finish up.
  if (card_errors == "\n -  Credit/Debit Card Errors:") {
    return true;
  }
  else {
    return false;
  }
} //check_card

function show_credit_charge() {
  
  // Show a message if there has been a change in the credit card charge but if the deposit has been cleared because
  // the property is not available then just exit.
  var deposit = document.getElementsByName('deposit')[0].value;
  if(deposit == null || !deposit) {
    return
  }
  var regexp = /([^\d\.])/g;
  var cc_charge = document.getElementsByName("cc_charge")[0].value;
  var charge = parseFloat(cc_charge.replace(regexp, ""));
  if (isNaN(charge)) {
    charge = 0;
  }
  var payment_obj = document.getElementsByName("payment")[0];
  var payment = parseFloat(payment_obj.value.replace(regexp, ""));

  // Show the appropriate message.
  var message = '';
  var last_charge_obj = document.getElementsByName("last_cc_charge")[0];
  if (charge && charge != last_charge_obj.value) {
    
    // There is a charge and it has altered so show the new details.
    var basic_payment = payment - charge;
//    var displ_basic_payment = '£' + formatNumber(basic_payment,2);
    var displ_basic_payment = formatNumber(basic_payment,2);
    message = "Deposit without credit card charge - " + displ_basic_payment + "\n\n";
    message += "Deposit with the credit card charge - " + payment_obj.value + "\n";
    alert(message);

    // Set the charge that's just been displayed so that we know next time whether we have
    // to display another message.
    last_charge_obj.value = charge;
  }
  else if (charge == 0 && last_charge_obj.value != 0) {
    // The credit card charge is zero and there was one before.
    message = "The credit card charge has been removed.\n\n";
    message += "The deposit is now " + payment_obj.value + "\n\n";
    alert(message);

    // Set the charge that's just been displayed so that we know next time whether we have
    // to display another message.
    last_charge_obj.value = 0;
  }
  return

}//show_credit_charge


function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
  var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address.
   These characters include ( ) < > @ , ; : \ " . [ ]    */
  var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a
   username or domainname.  It really states which chars aren't allowed. */
  var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
  var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
  var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
  var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
  var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
  var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
  var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
  var matchArray=emailStr.match(emailPat)
  if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
    alert("Email address seems incorrect (check @ and .'s)")
    return (false);
  }
  var user=matchArray[1]
  var domain=matchArray[2]

// See if "user" is valid
  if (user.match(userPat)==null) {
    // user is not valid
    alert("The username doesn't seem to be valid.")
    return (false);
  }

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
  var IPArray=domain.match(ipDomainPat)
  if (IPArray!=null) {
    // this is an IP address
    var i;
    for (i=1;i<=4;i++) {
      if (IPArray[i]>255) {
          alert("Email Destination IP address is invalid!")
       return (false);
      }
    }
    return true
  }

// Domain is symbolic name
  var domainArray=domain.match(domainPat)
  if (domainArray==null) {
    alert("The domain name doesn't seem to be valid.")
      return (false);
  }

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
  var atomPat=new RegExp(atom,"g")
  var domArr=domain.match(atomPat)
  var len=domArr.length
  if (domArr[domArr.length-1].length<2 ||
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
    alert("The email address must end in a three-letter domain, or two letter country.")
    return (false);
  }

// Make sure there's a host name preceding the domain.
  if (len<2) {
    var errStr="The email address is missing a hostname!"
    alert(errStr)
    return (false);
  }

// If we've gotten this far, everything's valid!
  return true;
} //emailCheck

/*
PRODUCT:  JavaScript Utilities for Credit Card Validation
VERSION:  1.01, April 2004
AMENDED:  1.02, August 2005, by ESR
CONTACT:  Future Shock Ltd, www.Future-Shock.net, post@future-shock.net

This file may be used freely as long as none of the comments are removed.
*/

function FSfncCheckCCnum(number) {
  // Check credit/debit card number is in valid format
  var ccRE=/\W/gi;
  var CCnumber=number.replace(ccRE, "");
  if (isNaN(CCnumber)) {
//    alert("Credit card number is not numeric.");
//    FormField.focus();
    return false
  }
  if ((CCnumber.length!=16) && (CCnumber.length!=18)) {
//    alert("Incorrect number of digits in credit card number.");
//    FormField.focus();
    return false
  }
  var cardMath=0;
  for (i=CCnumber.length; i>0; i--) {
    if (i % 2 == 1) {
      var doubled = "" + (parseInt(CCnumber.substring(i - 1, i)) * 2);
      if (doubled.length==2) {
        doubled = parseInt(doubled.substring(0,1)) + parseInt(doubled.substring(1,2))
      }
      cardMath += parseInt(doubled);
    }
    else {
      cardMath += parseInt(CCnumber.substring(i - 1, i))
    }
  }
  if (cardMath % 10 != 0) {
//    alert("Credit card number is invalid.");
//    FormField.focus();
    return false
  }
  return true;
} //FSfncCheckCCnum

function set_card_values() {

  // This sets the name and postcode in the card details from what has been entered,
  // in case it is required.
  var fName = document.getElementsByName("first_name")[0];
  var lName = document.getElementsByName("last_name")[0];
  var card_name = document.getElementsByName("card_name")[0];
  var name = fName.value + " " + lName.value;
  card_name.value = name;
  var pCode = document.getElementsByName("postcode")[0];
  var card_pcode = document.getElementsByName("card_pc")[0];
  card_pcode.value = pCode.value;
}

//function save_expiry()  {
//
///* This saves the expiry month and year in hidden fields just before the 'submit'. This is used
//  in initialize to ensure that these fields are set after it sets up the expiry year one. */
//  var em = document.getElementsByName("expiry_month")[0];
//  var index = em.selectedIndex;
//  var expiry_month = em.options[index].value;
//  var hem = document.getElementsByName("exp_month")[0];
//  hem.value = expiry_month;
//  var ey = document.getElementsByName("expiry_year")[0];
//  index = ey.selectedIndex;
//  var expiry_year = ey.options[index].value;
//  var hey = document.getElementsByName("exp_year")[0];
//  hey.value = expiry_year;
//  alert("The expiry date as saved: " + hem.value + " " + hey.value);
//
//} //save_expiry

//--> end script
