/**
 * RunTrackr - Register Scripts
 */
var readyToSubmit = false;

jQuery(document).ready(function()
{
  // Check password field.
  jQuery('#UserPass').blur(function(event)
  {
    if (this.value != '')
    {
      checkPassword();
      if (jQuery('#UserPassConfirm').val() != '')
      {
        checkConfirmPassword();
      }
    }
  });

  // Check password-confirm field.
  jQuery('#UserPassConfirm').blur(function(event)
  {
    if(this.value != '')
    {
      checkConfirmPassword();
    }
  });

  // Do not use challenge-response if not supported by the browser.
  if (isChapLoginSupported())
  {
    // CHAP Registration handler.
    jQuery('form#register').submit(function(event)
    {
      if (readyToSubmit)
      {
        return true;
      }
      else
      {
        // Prevent traditional form submission.
        event.preventDefault();
      }

      /*---
       * Validate passwords to see if they match the criteria.  This cannot
       * be done server-side since we don't pass the passwords in plaintext.
       * ---*/

      // TODO: Make this more elegant.
      var password = jQuery('#UserPass').val();

      // Hide previous error messages.
      jQuery('.error-message').hide();
      var isValidationError = false;

      // TODO: Should bind all of these checks into an array of callbacks.
      // Check password 'quality', length.
      if (!checkPassword())
      {
        isValidationError = true;
      }

      // Confirm passwords match.
      if (!checkConfirmPassword())
      {
        isValidationError = true;
      }

      // Check that the terms were agreed to.
      if (jQuery('#Agree:checked').val() === undefined)
      {
        window.alert("Please accept the Terms of Use and Privacy Policy to register.");
        isValidationError = true;
      }

      // Validation error; don't submit for server-side checks.
      if (isValidationError == true)
      {
        return;
      }

      var url = jQuery('#challenges-url').val();

      jQuery.ajax({
        'url' : url,
        'type' : 'GET',
        'dataType' : 'json',
        'cache' : false,
        'success' : function(challenges, textStatus)
        {
          // Compute the challenge-hashed-password and ready it for submission.
          var hashedPasswordResponse = hex_sha1(hex_hmac_sha1(password, challenges.c1));

          // Disable the plaintext password fields to prevent submission.
          // No need to blank out since disabled elements' values should not be
          // submited as per the HTML spec.
          jQuery('#UserPass').attr('disabled', 'disabled');
          jQuery('#UserPassConfirm').attr('disabled', 'disabled');

          // TODO: Is this safe to allow the client to send the challenge?
          // ALSO: See if we can modify/set the `created` or `modified` fields
          // from this form!  SHOULD ALWAYS MAKE SURE TO EXPLICITLY SET ANY
          // fields that aren't meant to take user-input!
          jQuery('#register').append(
            '<input type="hidden" name="data[User][password]" value="' + hashedPasswordResponse + '" />' +
            '<input type="hidden" name="data[User][challenge1]" value="' + challenges.c1 + '" />'
          );

          // Indicate that the form is ready to submit and then submit it!
          readyToSubmit = true;
          jQuery('form#register').submit();

        },
        // TODO: What to do in case of an error?
        'error': function(XMLHttpRequest, textStatus, errorThrown)
        {
          alert('There was an error!');
        }
      });// end jQuery.ajax()
    });// end jQuery('form#register').submit()
  }// end if (isChapLoginSupported())
});// end jQuery(document).ready()

function checkPassword()
{
  var password = jQuery('#UserPass').val();

  // Confirm password 'quality'.
  if (password.replace(/^\s+|\s+$/g,"").length < 6)
  {
    // Passwords only alphanumeric? Won't be able to check if using CHAP; can only check using JS.
    // TODO: Check for spaces!
    jQuery('.password.error-message').show();

    return false;
  }

  jQuery('.password.error-message').hide();
  return true;
}

function checkConfirmPassword()
{
  var password = jQuery('#UserPass').val();
  var passwordConfirm = jQuery('#UserPassConfirm').val();

  // Confirm passwords match.
  if (password != passwordConfirm)
  {
    // Confirmation of matching passwords will be done PURELY via JavaScript.  Consider checking matching onBlur()
    jQuery('.password-confirm.error-message').show();

    return false;
  }

  jQuery('.password-confirm.error-message').hide();
  return true;
}
