/**
 * RunTrackr - Login Scripts
 */

// TODO: BEFORE submitting the form, MUST MAKE SURE that there are no
// pending Ajax calls waiting to retrieve the challenge:
// Solution:
// 1) When Ajax call starts, disable submit of form (both by actually disabling
// submit AND by disabling submit button)
// - May also want to disable other (password) fields.
// 2) Show a "loading indicator" - circular - while Ajax in operation; this
// will persist until the form is actually submitted using JS.
// 5) To make work without JS, just check if the secondary value has been sent;
// if not, then JS has not been used.
// 6) NEED TO CHECK USING SNIFFER whether the plaintext password is actually
// being submitted! MUST VERIFY OTHERWISE USELESS!

// Set up event handlers and initialize objects.
jQuery(document).ready(function()
{
  // Do not use challenge-response if not supported by the browser.
  if (isChapLoginSupported())
  {
    // Auto-focus the user-name field.
    jQuery('#UserUsername').focus();

    // CHAP Login handler.
    jQuery('form#login').submit(function(event)
    {
      // TODO: Could change to just return true IF readyToSubmit, and otherwise
      // #preventDefault() or return false at the end.
      if (readyToSubmit)
      {
        return true;
      }
      else
      {
        // Prevent traditional form submission.
        event.preventDefault();
      }

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

      jQuery.ajax({
        'url' : url,
        'type' : 'GET',
        'dataType' : 'json',
        'cache' : false,
        'success' : function(challenges, textStatus)
        {
          // Compute the responses to send based on the challenges.
          var password = jQuery('#UserPass').val();
          var response = hex_hmac_sha1(password, challenges.c1);
          var responseNext = hex_sha1(hex_hmac_sha1(password, challenges.c2));

          // Disable and blank out the password field with spaces to prevent
          // the plaintext from being submitted over the network.
          // TODO: Note that the disabled input is not submitted at all, so the
          // 'blanking out' of the password with spaces is somewhat redundant
          // and may not be necessary, and in fact, user-unfriendly.
          var blankPassword = password.replace(/./g, ' ');
          jQuery('#UserPass').val(blankPassword).attr('disabled', 'disabled');

          jQuery('#login').append(
            '<input type="hidden" name="data[User][password]" value="' + response + '" />' +
            '<input type="hidden" name="data[User][response_next]" value="' + responseNext + '" />'
          );

          // Indicate that the form is ready to submit and then submit it!
          readyToSubmit = true;
          jQuery('form#login').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#login').submit()
  }// end if (isChapLoginSupported())
});// end jQuery(document).ready()

