/* Log the user in. */
function login_ajax(form) {
  var form_data = {
    url: "/login_ajax/",
    handleAs: "json",
    load: function(data) {
      if (data.user_id == 0) {document.getElementById("login_status").innerHTML = "Invalid username or password.";}
      else {window.history.back(-1);}
    },
    error: function(data) {
      alert(data);
    },
    timeout: 60000,
    form: form
  };
  dojo.xhrPost(form_data);
}

/* Check if the user is logged in. Not needed anymore. */
function check_auth() {
  dojo.xhrGet({
    url: "/check_auth/",
    handleAs: "json",
    timeout: 60000,
    load: function(data, ioArgs) {
      var div_wel = document.getElementById("welcome");
      var div_auth = document.getElementById("auth");
      if (data.user_id != 0) {
        div_wel.innerHTML = "Welcome,&nbsp;&nbsp;" + data.user_first + "!&nbsp;&nbsp;&nbsp;&nbsp;";
        div_auth.className = "logout";
        div_auth.innerHTML = "<a href='#' onclick=\"document.getElementById('url').value=location.pathname; document.forms['dir'].submit();\">logout</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;";
      }
    },
    error: function(response, ioArgs) {
      console.error("HTTP status code: ", ioArgs.xhr.status);
      return response;
    }
  });
}

/* Send email reminders to users for forgotten username/password.
   [CODES] 0: username sent to email. 1: email not found. 2: new password sent to email. 3: username/email not found/match. */
function remind(form, remind_this) {
  var form_data = {
    url: "/remind/",
    handleAs: "json",
    load: function(data) {
      var div = document.getElementById('result');
      switch(data.code) {
        case 0:
          div.innerHTML = "Your username has been sent to your email."; div.style.display = "block";
          break;
        case 1:
          div.innerHTML = "The email you entered was not found."; div.style.display = "block";
          break;
        case 2:
          div.innerHTML = "A new password has been sent to your email."; div.style.display = "block";
          break;
        case 3:
          div.innerHTML = "The email/username combination is invalid."; div.style.display = "block";
          break;
      }
    },
    error: function(data) {
      alert(data);
    },
    timeout: 60000,
    form: form
  };
  dojo.xhrPost(form_data);
}
