
  var register = new function() {

    var xml = null;

    /* Initialise the form */
    this.init = function() {

      /* Add event handlers */
      Event.observe('submitButton', 'click', handleSubmitClick);
      Event.observe('trialName', 'blur', handleTrialNameBlur);
   }

    /* Handles the callback response from the submit
    button's onclick event */
    function handleSubmitClick() {
      if(validate()) {
        $('trialForm').submit();
      }
    }

    /*
    Performs validation checkes all required fields.
    */
    var firstFocus = false;
    function validate() {

      var hasErrors = false;
      firstFocus = false;

      /* First name */
      if($('firstName').getValue() == '') {
        flagFieldError($('firstName'), 'First Name is required.');
        hasErrors = true;
      }
      else {
        unFlagFieldError($('firstName'));
      }

      /* Last name */
      if($('lastName').getValue() == '') {
        flagFieldError($('lastName'), 'Last Name is required.');
        hasErrors = true;
      }
      else {
        unFlagFieldError($('lastName'));
      }

      /* Telephone */
      if($('telNumber').getValue() == '') {
        flagFieldError($('telNumber'), 'Telephone is required.');
        hasErrors = true;
      }
      else {
        unFlagFieldError($('telNumber'));
      }

      /* Email */
      if($('emailAddress').getValue() == '') {
        flagFieldError($('emailAddress'), 'Email Address is required.');
        hasErrors = true;
      }
      else {

        /* Valid email */
        var re = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", 'i');
        if(!re.test($('emailAddress').getValue())) {
          flagFieldError($('emailAddress'), 'Email Address must be valid.');
          hasErrors = true;
        }
        else {

          /* Match confirmation? */
          if($('emailAddress').getValue() != $('confirmEmailAddress').getValue()) {
            flagFieldError($('emailAddress'), '');
            flagFieldError($('confirmEmailAddress'), 'Does not match Email Address.');
            hasErrors = true;
          }
          else {
            unFlagFieldError($('emailAddress'));
            unFlagFieldError($('confirmEmailAddress'));
          }
        }
      }

      /* Church or Organisation Name */
      if($('churchName').getValue() == '') {
        flagFieldError($('churchName'), 'Church or Organisation is required.');
        hasErrors = true;
      }
      else {
        unFlagFieldError($('churchName'));
      }

      /* Trial Account Name */
      if($('trialName').getValue() == '') {
        flagFieldError($('trialName'), 'Trial Account Name is required.');
        hasErrors = true;
      }
      else {

        var re = new RegExp("^[a-zA-Z0-9-]{6,}$", 'i');
        if(!re.test($('trialName').getValue())) {
          flagFieldError($('trialName'), 'Letters, numbers and hyphens only. Min of 6 chrs.');
          hasErrors = true;
        }
        else {
          unFlagFieldError($('trialName'));
        }
      }

      if(hasErrors == false && !$('confirmTC').checked) {
        alert('You must agree with our Terms & Conditions to proceed.');
        hasErrors = true;
      }

      return (hasErrors? false : true);
    }

    /*
    Takes one parameter of a form element object
    and will apply an error css class.
    */
    function flagFieldError(field, msg) {

      switch(field.tagName.toLowerCase()) {

        case 'input':

          if(field.type.toLowerCase() == 'text') {
            new Effect.Highlight(field, {duration: 3, endcolor: '#ffd9d9'});
            field.style.backgroundColor = '#ffd9d9';
            field.nextSiblings()[0].innerHTML = msg;

            if(!firstFocus) {
              field.focus();
              firstFocus = true;
            }
          }
          break;
      }
    }

    /*
    Same as above but removes any error classes.
    */
    function unFlagFieldError(field) {

      switch(field.tagName.toLowerCase()) {

        case 'input':

          if(field.type.toLowerCase() == 'text') {
            field.style.backgroundColor = 'white';
            field.nextSiblings()[0].innerHTML = '';
          }
          break;
      }
    }

    /*
    Handles the callback resonse from the trial
    name blur event.
    */
    function handleTrialNameBlur() {
      $('submitButton').disabled = true;
      $('trialCheckAni').show();

      var ajaxSess = new Ajax.Request('apps/trial/trialCheck.php', {
        method:'GET',
        parameters: "trialName=" + encodeURIComponent($('trialName').getValue()) + "&isTrial=-1",
        onSuccess: function(transport) {
          var jsonResult = eval("(" + transport.responseText + ")");

          if(jsonResult.available) {
            $('submitButton').disabled = false;
            unFlagFieldError($('trialName'));
          }
          else {
            flagFieldError($('trialName'), 'Trial name unavailable, please try another.');
          }

          $('trialCheckAni').hide();
        }
      });
    }
  }

  Event.observe(window, 'load', register.init);