function protectAccount() {
  consoleLog("Protect account");
  if (hasLocalStorage()) {

    ajaxCall("/api/v1/setCredentials.php", {
      uuid: localStorage["uniqueId"],
      email: $("#protectEmail").val(),
      password: $("#protectPassword").val(),
      password2: $("#protectPassword2").val()
    }).fail(function (data) {
      consoleLog("protectAccount error: " + JSON.stringify(data));
    }).done(function (data) {
      if (data.response != undefined) {
        switch (data.response.responseCode) {
          case 200:
            revealMessageDialog($("#i18ProtectionEnabledLabel").html(), $("#i18ProtectionEnabledDescription").html());
            for (var i = 0; i < data.response.value.rows.length; ++i) {
              consoleLog("loadSettings localStorage SET " + data.response.value.rows[i]["name"] + ": " + data.response.value.rows[i]["value"]);
              localStorage[data.response.value.rows[i]["name"]] = data.response.value.rows[i]["value"];
            }
            $(GLOBAL).trigger("isLoggedIn");
            break;
          case 403:
          case 404:
          case 412:
            revealMessageDialog($("#i18ProtectionFailedLabel").html(), data.response.responseCode + ": " + data.response.message);
            break;
          default:
            consoleLog("protectAccount error: " + data.response.responseCode + ": " + data.response.message);
            break;
        }
      } else {
        consoleLog("protectAccount error unexpected response: " + data);
      }
    }).always(function () {
      consoleLog("protectAccountDone fired");
      $(GLOBAL).trigger("protectAccountDone");
    });
  }
}

function unprotectAccount() {
  consoleLog("Disable protection");
  if (hasLocalStorage()) {
    ajaxCall("/api/v1/removeCredentials.php", {
      uuid: localStorage["uniqueId"], password: $("#unprotectPassword").val()
    }).fail(function (data) {
      consoleLog("unprotectAccount error: " + data.toString());
    }).done(function (data) {
      if (data.response != undefined) {
        switch (data.response.responseCode) {
          case 200:
            revealMessageDialog($("#i18ProtectionDisabledLabel").html(), $("#i18ProtectionDisabledDescription").html());
            consoleLog("unprotectAccount succeeded: " + data.response.responseCode + ": " + data.response.message);
            localStorage.removeItem("loginToken");
            $(GLOBAL).trigger("isLoggedOut");
            break;
          case 401:
            revealMessageDialog($("#i18ProtectionRemovalFailedLabel").html(), $("#i18ProtectionRemovalFailedDescription").html());
            break;
          case 404:
          case 412:
            revealMessageDialog($("#i18NoAccountLabel").html(), $("#i18NoAccountDescription").html());
            break;
          default:
            consoleLog("unprotectAccount error: " + data.response.responseCode + ": " + data.response.message);
            break;
        }
      } else {
        consoleLog("unprotectAccount error unexpected response: " + data);
      }
    }).always(function () {
      consoleLog("unprotectAccountDone fired");
      $(GLOBAL).trigger("unprotectAccountDone");
    });
  }
}

function removeAccount(redirect, forced) {
  var r = forced;
  if (forced !== true) {
    r = window.confirm($("#i18RemoveAccountPromptDescription").html());
  }
  if (r) {
    if (hasLocalStorage()) {
      consoleLog("Remove account");

      ajaxCall("/api/v1/removeAccount.php", {
        uuid: localStorage["uniqueId"], password: $("#removeAccountPassword").val()
      }).fail(function (data) {
        consoleLog("removeAccount error: " + data.toString());
      }).done(function (data) {
        if (data.response != undefined) {
          switch (data.response.responseCode) {
            case 200:
              consoleLog("removeAccount succeeded: " + data.response.responseCode + ": " + data.response.message);
              localStorage.clear();
              if (redirect) {
                window.location = serverBaseUrl + "/";
              }
              break;
            case 401:
              revealMessageDialog($("#i18AccountRemovalFailedLabel").html(), $("#i18AccountRemovalFailedDescription").html());
              break;
            case 404:
            case 412:
              revealMessageDialog($("#i18NoAccountLabel").html(), $("#i18NoAccountDescription").html());
              break;
            default:
              consoleLog("removeAccount error: " + data.response.responseCode + ": " + data.response.message);
              break;
          }
        } else {
          consoleLog("removeAccount error unexpected response: " + data);
        }
      }).always(function () {
        consoleLog("removeAccountDone fired");
        $(GLOBAL).trigger("removeAccountDone");
      });
    }
  }
}

function loadAccountSettings() {
  /**
   * Clear remove account password.
   * We only want to remove account with no credentials set.
   */
  if (localStorage["loginToken"] == null) {
    $("#removeAccountPassword").val("");
    removeAccount(false, true);
  }
  consoleLog("Load account");
  loadSettingsFromServer($("#loadSettingsEmail").val(), $("#loadSettingsPassword").val());
}

function sendPasswordResetMail() {
  consoleLog("sendPasswordResetMail");
  ajaxCall("/api/v1/sendPasswordResetMail.php", {
    email: $("#resetPasswordEmail").val()
  }).fail(function (data) {
    consoleLog("Send password reset e-mail error: " + data.toString());
    revealMessageDialog($("#i18PasswordResetFailedLabel").html(), $("#i18PasswordResetFailedDescription").html());
  }).done(function (data) {
    if (data.response != undefined) {
      if (data.response.responseCode == 200) {
        consoleLog("Send password reset e-mail succeeded: " + data.response.responseCode + ": " + data.response.message);
        revealMessageDialog($("#i18PasswordResetLabel").html(), $("#i18PasswordResetDescription").html());
      } else {
        revealMessageDialog($("#i18PasswordResetFailedLabel").html(), $("#i18PasswordResetFailedDescription").html());
      }
    } else {
      consoleLog("Send password reset e-mail error unexpected response: " + data);
      revealMessageDialog($("#i18PasswordResetFailedLabel").html(), $("#i18PasswordResetFailedDescription").html());
    }
  }).always(function () {
    consoleLog("sendPasswordResetMailDone fired");
    $(GLOBAL).trigger("sendPasswordResetMailDone");
  });
}

function resetPassword() {
  consoleLog("resetPassword");
  ajaxCall("/api/v1/resetPassword.php", {
    token: $("#token").val(),
    password: $("#protectPassword").val(),
    password2: $("#protectPassword2").val()
  }).fail(function (data) {
    consoleLog("Password reset error: " + data.toString());
    revealMessageDialog("Password reset error", "Password could not be reset.");
  }).done(function (data) {
    if (data.response != undefined) {
      if (data.response.responseCode == 200) {
        consoleLog("Password reset succeeded: " + data.response.responseCode + ": " + data.response.message);
        revealMessageDialog("Password reset", "Password has been reset.");
      } else {
        revealMessageDialog("Password reset error", "Password could not be reset.");
      }
    } else {
      consoleLog("Send password reset error unexpected response: " + data);
      revealMessageDialog("Password reset error", "Password could not be reset.");
    }
  }).always(function () {
    consoleLog("resetPasswordDone fired");
    $(GLOBAL).trigger("resetPasswordDone");
  });
}

/**
 * Logout and remove all unnecessary localSettings.
 * The minimal is needed to trigger a login with the next visit.
 * Redirect to home page.
 */
function logout() {
  var id = localStorage["id"];
  var uniqueId = localStorage["uniqueId"];
  localStorage.clear();
  localStorage["id"] = id;
  localStorage["uniqueId"] = uniqueId;
  window.location = "/";
}

function login() {
  if (hasLocalStorage()) {
    if (localStorage["uniqueId"] != null) {
      loadSettingsFromServer($('#email').val(), $('#password').val(), $('#tokenTimeToLive').val());
    } else if (localStorage["uniqueId"] == null) {
      /**
       * New profile.
       */
      loadSettingsFromServer();
    }
  }
}

