/**
 * Handler the login form via ajax.
 *
 * @author psimmons
 *
 * @todo PS - should refactor to a namespace plugin
 */
$(document).ready(function() {
  /////// LOGIN FORM EVENTS //////////
  var cookieName = 'BTLOGININFO';
  var loginInfoCookie = $.cookie(cookieName);
  var destination = false;
  if (loginInfoCookie) {
    var loginInfo = loginInfoCookie.split(':');
      destination = loginInfo[0];
      if(destination == '/mybrighttalk/forgotpassword'){
        $.cookie(cookieName, '', { expires: -1, path: "/" });
      }
  }

  $(document).bind('disableLoginForm', function(event) {
    $('#user-login-form :input').attr('disabled', 'disabled').addClass('disabled');
    $('#user-login-form :submit').css('display', 'none').after('<img id="buttonlogin-loading" class="disabled" src="/css/mybrighttalk/images/buttonlogin-loading-85.gif" />');
  });

  $(document).bind('enableLoginForm', function(event) {
    $("#user-login-form #buttonlogin-loading").remove();
    $('#user-login-form :submit').css('display', 'inline');
    $('#user-login-form :input').removeAttr('disabled').removeClass('disabled');
  });

  $(document).bind('loginSuccess', function(e, data) {
    // clear the loginInfo cookie
    if (!destination || destination == 'undefined' || destination == '/mybrighttalk/forgotpassword') {
      destination = '/mybrighttalk/';
    }
    $.cookie(cookieName, '', { expires: -1, path: "/" });
    window.location = destination;
  });

  ///////// VALIDATION AND SUBMISSION ////////

  $("#user-login-form").validate({
    rules: {
      email: {
        maxlength: 100
      },
      password: {
        nospaces: true,
        minlength: 6,
        maxlength: 32
      }
    },
    submitHandler: function() {
      // @todo COULD wipe the session before submitting

      var email = $.bt.escapeXmlSpecialCharacters($("input#edit-email").val());
      var password = $.bt.escapeXmlSpecialCharacters($("input#edit-pass").val());
      var request = $.bt.brightTALKRequestXmlWrapper('<user><identifier>' + email + '</identifier><password>' + password + '</password></user>');
      var url = "/service/user/xml/login";

      $(document).trigger('disableLoginForm');

      $.ajax({
        type: "POST",
        url: url,
        data: request,
        processData: true,
        success: function(xml) {
          var state = $(xml).find('response').attr('state');
          if (state == 'processed') {
            $('#login-message').html("Logged in now redirecting...");
            $(document).trigger('loginSuccess');
          }
          else {
            $(document).trigger("showError", ["error", "Sorry, unrecognized username or password."]);
            $(document).trigger("enableLoginForm");
          }
        },
        error: function() {
          $(document).trigger("enableLoginForm");
        }
      });
      return false;
    }
  });
});
