$(GLOBAL).bind("appStart", function () {
  /**
   * Clear localStorage and only keep the id and uniqueId.
   */
  if (hasLocalStorage()) {
    $(GLOBAL).trigger("isLoggedOut");
    if (localStorage["uniqueId"] != null) {
      var id = localStorage["id"];
      var uniqueId = localStorage["uniqueId"];
      var loginToken;
      var tipsShown;
      var defaultZoom = null;
      if (localStorage["loginToken"] != null) {
        loginToken = localStorage["loginToken"];
      }
      if (localStorage["tipsShown"] != null) {
        tipsShown = localStorage["tipsShown"];
      }
      if (localStorage["locale"] != null) {
        locale = localStorage["locale"];
      }
      if (localStorage["gmapZoom"] != null) {
        defaultZoom = localStorage["gmapZoom"];
      }
      localStorage.clear();
      localStorage["id"] = id;
      localStorage["uniqueId"] = uniqueId;
      localStorage["tipsShown"] = tipsShown;
      localStorage["locale"] = locale;
      if (loginToken != null) {
        localStorage["loginToken"] = loginToken;
      }
      if (defaultZoom != null) {
        localStorage["gmapZoom"] = defaultZoom;
      }
      refreshNotifications();

    } else {
      localStorage.clear();
    }
  }
  /**
   * Load the settings from the webserver.
   * When a user does not have an uniqueId then we'll also retrieve one from the server.
   */
  loadSettingsFromServer("", "", 7);
});

$(GLOBAL).bind("timeEvent", function () {
  consoleLog("timeEvent event captured");
  refreshNotifications();
});

$(GLOBAL).bind("checkinStart", function () {
  consoleLog("checkinStart event captured");
  $(".conquerButton").html("<img src='img/smallLoader.gif'/>");
});

$(GLOBAL).bind("checkinDone", function () {
  consoleLog("checkinDone event captured");
  $(".conquerButton").html($("#i18ConquerLabel").html());
});

$(GLOBAL).bind("isLoggedIn", function () {
  consoleLog("isLoggedIn event captured");
  $("#protectSetting").hide();
  $(".menuLoginButton").hide();
  $(".menuLogoutButton").show();
  $("#unprotectSetting").show();
});
$(GLOBAL).bind("isLoggedOut", function () {
  consoleLog("isLoggedOut event captured");
  $("#protectSetting").show();
  $(".menuLoginButton").show();
  $(".menuLogoutButton").hide();
  $("#unprotectSetting").hide();
});

$(GLOBAL).bind("getUniqueIdSuccess", function () {
  consoleLog("getUniqueIdSuccess event captured");
  getNearbyConqueredPlaces();
});

$(GLOBAL).bind("loadSettingsFromServerDone", function () {
  consoleLog("loadSettingsFromServerDone event captured");
  checkGenderMenuItems();
});

$(GLOBAL).bind("saveSettingsToServerDone", function () {
  consoleLog("saveSettingsToServerDone event captured");
  $("#toast").html($("#i18SavedLabel").html());
  $("#toast").finish().show().fadeOut(3000);
  checkGenderMenuItems();
});

$(window).scroll(function () {
  if ($(window).scrollTop() > 60) {
    $("#magellanPlaceholder").show();
  }
  else {
    $("#magellanPlaceholder").hide();
  }
})

/**
 * Set listeners for auto-save purpose.
 */
$("input[type=text].autosave").blur(function() {
  saveSettings();
});
$('input[type=text].autosave').keypress(function (e) {
  if (e.which == 13) {
    saveSettings();
  }
});

var nicknameSaveDelay;
$('#nickname').keyup(function (e) {
  if (nicknameSaveDelay != null) {
    clearTimeout(nicknameSaveDelay);
  }
  nicknameSaveDelay = setTimeout("saveSettings()", 2000);
});

$('#venue').keypress(function (e) {
  if (e.which == 13) {
    $(this).trigger("placeChanged");
  }
});

$('#venue').on("placeChanged", function (e) {
  consoleLog("searchPlaces: " + $(this).val());
  searchPlaces();
  location.hash = '';
  location.hash = 'map';
});

$("input[type=radio].autosave, input[type=date].autosave").change(function () {
  saveSettings();
});

$("select.autosave").change(function() {
  saveSettings();
});

$("#photo").change(function () {
  consoleLog("Upload photo");
  uploadPhoto();
});

$(document).on('closed', '#loginModal[data-reveal]', function () {
  if (localStorage["uniqueId"] != null) {
    login();
  }
});

function refreshNotifications() {
  if (typeof (showChallengesCount) != 'undefined') {
    showChallengesCount();
  }
  if (typeof (showNotificationsCount) != 'undefined') {
    showNotificationsCount();
  }
}

function newProfile() {
  $('#removeAccountPassword').val('');
  localStorage.clear();
  location.reload();
}

var loadingSettings = false;
/**
 * Load settings from server.
 */
function loadSettingsFromServer(email, password, tokenTimeToLive) {
  /**
   * Load settings from remote API if uniqueId is set.
   */
  if (hasLocalStorage() && loadingSettings === false) {
    if (localStorage["uniqueId"] != null) {
      var loginToken = (localStorage["loginToken"] != null) ? localStorage["loginToken"] : "";
      consoleLog("getSettings called: [" + email + "] [" + password + "] [" + loginToken + "] [" + tokenTimeToLive + "]");
      loadingSettings = true;

      $(GLOBAL).trigger("loadSettingsFromServer");

      ajaxCall("/api/v1/getSettings.php", {
        uuid: localStorage["uniqueId"],
        email: email,
        password: password,
        loginToken: loginToken,
        tokenTimeToLive: tokenTimeToLive
      }).fail(function (data) {
        consoleLog("getSettings error: " + data);
        loadingSettings = false;
      }).done(function (data) {
        loadingSettings = false;
        if (data.response != undefined) {
          switch (data.response.responseCode) {
            case 200:
              if (data.response.value != undefined) {
                if (data.response.value.rows != undefined) {
                  consoleLog(data.response.responseCode + ": " + data.response.message);
                  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"];
                  }
                  loadSettings();
                  if (email != null && email.length > 0 && password != null && password.length > 0) {
                    revealMessageDialog($("#i18SettingsLoadedLabel").html(), "");
                    $(GLOBAL).trigger("loadSettingsFromServerSuccess");
                  }
                }
                checkCooldown();
                if (typeof (getPointsTotal) != 'undefined') {
                  getPointsTotal();
                }

              } else {
                consoleLog("getSettings no settings on server: " + data.response.responseCode + ":" + data.response.message);
                saveSettings();
                checkGenderMenuItems();
              }
              break;
            case 401:
              /**
               * If unauthorized then we reset our loginToken as well.
               * It might be expired.
               */
              localStorage.removeItem("loginToken");
              setTimeout("revealDialog('#loginModal')", 1000);
              consoleLog(JSON.stringify(data));
              break;
            case 404:
              revealMessageDialog($("#i18SettingsLoadErrorLabel").html(), data.response.responseCode + ": " + $("#i18SettingsLoadErrorDescription").html());
              localStorage.clear();
              loadSettingsFromServer();
              break;
            default:
              revealMessageDialog($("#i18SettingsLoadErrorLabel").html(), data.response.responseCode + ": " + $("#i18SettingsLoadErrorDescription").html());
              localStorage.clear();
              loadSettingsFromServer();
              break;
          }
        } else {
          revealMessageDialog($("#i18SettingsLoadErrorLabel").html(), data);
          localStorage.clear();
        }
      }).always(function () {
        consoleLog("loadSettingsFromServerDone fired");
        $(GLOBAL).trigger("loadSettingsFromServerDone");
      });
    } else {
      generateUniqueId(checkEntrance);
    }
  }
}

/**
 * Load settings.
 */
function loadSettings() {
  if (hasLocalStorage()) {
    consoleLog("start loadSettings local");
    /**
     * Below we'll load the settings from localStorage.
     */

    if(localStorage["#profilePanel"] != null) {
      if($("#profilePanelContent").is(":visible") === false) {
        toggleOptionsHeader(localStorage["#profilePanel"], false);
      }
    }
    if(localStorage["#preferencePanel"] != null) {
      if($("#preferencePanelContent").is(":visible") === false) {
        toggleOptionsHeader(localStorage["#preferencePanel"], false);
      }
    }
    if (localStorage["#protectPanel"] != null) {
      if ($("#protectPanelContent").is(":visible") === false) {
        toggleOptionsHeader(localStorage["#protectPanel"], false);
      }
    }

    /**
     * We hide all the rows with the data-show-id attribute.
     * The visibility of the rows will be recalculated.
     */
    $(".row[data-show-id]").hide();
    
    $("input[type=radio].autosave").each(function () {
      if(localStorage["#" + $(this).attr("id")] == "checked") {
        $("#" + $(this).attr("id")).prop('checked', 'checked');
        
        /**
         * Here we recalculate the visibility of a row with the data-show-id attribute.
         */
        if($(this).attr("id").indexOf("show") == 0) {
          $( ".row[data-show-id='" + $(this).attr("id") + "']" ).each(function() {
            $(this).show();
          });
        }
      }
    });
    
    $("input[type=text].autosave, input[type=date].autosave").each(function () {
      var id = $(this).attr("id");
      if (localStorage["#" + id] != null) {
        if (id == "nickname") {
          $("#" + id).val(htmlDecode(localStorage["#" + id]));
        } else {
          $("#" + id).val(localStorage["#" + id]);
        }
      }
    });
    
    $("select.autosave").each(function () {
      if(localStorage["#" + $(this).attr("id")] != null) {
        $("#" + $(this).attr("id")).val(localStorage["#" + $(this).attr("id")]);
      }
    });

    /**
     * Load photo if visible and url is available.
     */
    if (localStorage["#showPhotoField"] === "checked" && localStorage["photoUrl"] != null) {
      var d = new Date();
      $("#photoOutput").html("<img src='" + window.location.protocol + "//" + window.location.host + "/" + localStorage["photoUrl"] + "?" + d.getTime() + "'/>");
    }

    /**
     * Load QR image.
     */
    if (localStorage["uniqueId"] != null) {
      var qrUrl = window.location.protocol + "//" + window.location.host + "/?qr=" + localStorage["id"];
      $("#fb-qr").attr("data-href", qrUrl);
      $("#tw-qr").attr("data-url", qrUrl);
      $("#qrUrl").val(qrUrl);
      $("#qrImage").attr("src", "/api/v1/getQrImage.php?id=" + localStorage["id"]);
      $("#connect-wrapper").show();
      twitterStarted = false;
      fbStarted = false;
    } else {
      $("#connect-wrapper").hide();
    }
    if(typeof(refreshYourMarker) != 'undefined'){
      refreshYourMarker();
    }
    consoleLog("finish loadSettings local");
    if ($("#tw-qr").length > 0 && typeof (twitterStart) != "undefined") {
      twitterStart();
    }
    if($("#fb-qr").length > 0 && typeof(fbStart) != "undefined") {
      fbStart();
    }
    if (typeof (gplusStart) != "undefined") {
      gplusStart();
    }

    /**
     * Detect loginToken.
     */
    consoleLog("loginToken: " + localStorage["loginToken"])
    if (localStorage["loginToken"] != null) {
      $(GLOBAL).trigger("isLoggedIn");
    }
  }
}

/**
 * Save settings.
 */
function saveSettings() {
  if (hasLocalStorage()) {
    if($("#profilePanelContent").is(":visible")) {
      localStorage.setItem("#profilePanel", "#profilePanel");
    }
    else {
      localStorage.setItem("#profilePanel", null);
    }
    if($("#preferencePanelContent").is(":visible")) {
      localStorage.setItem("#preferencePanel", "#preferencePanel");
    }
    else {
      localStorage.setItem("#preferencePanel", null);
    }
    if ($("#protectPanelContent").is(":visible")) {
      localStorage.setItem("#protectPanel", "#protectPanel");
    }
    else {
      localStorage.setItem("#protectPanel", null);
    }
    $("input[type=text].autosave, input[type=date].autosave").each(function () {
        localStorage.setItem("#" + $(this).attr("id"), $(this).val());
    });
    $("input[type=radio].autosave").each(function () {
        localStorage.setItem("#" + $(this).attr("id"), (($(this).is(':checked')) ? "checked" : ""));
    });
    $("select.autosave").each(function () {
        localStorage.setItem("#" + $(this).attr("id"), $(this).val());
    });
    if (localStorage["uniqueId"] != null) {
      saveSettingsToServer();
    }
  }
}

/**
 * Save settings to server.
 * Create JSON object from localStorage array and POST it to the server.
 */
function saveSettingsToServer() {
  if (hasLocalStorage()) {
    var jsonArray = {};
    for (key in localStorage) {
      jsonArray[key.toString()] = localStorage[key];
    }
    var json = JSON.stringify(jsonArray);
    consoleLog("saveSettings called");

    ajaxCall("/api/v1/saveSettings.php", {
      uuid: localStorage["uniqueId"], settings: json
    }).fail(function (data) {
      consoleLog("saveSettings error: " + data.toString());
    }).done(function (data) {
      if (data.response != undefined) {
        if (data.response.responseCode == 200) {
          consoleLog(data.response.responseCode + ": " + data.response.message);
        } else {
          consoleLog("saveSettings error: " + data.response.responseCode + ":" + data.response.message);
        }
      } else {
        consoleLog("saveSettings error unexpected response: " + data);
      }
    }).always(function () {
      consoleLog("saveSettingsToServerDone fired");
      $(GLOBAL).trigger("saveSettingsToServerDone");
    });

    consoleLog(JSON.stringify(jsonArray));
  }
}

/**
 * Toggle the panels which can be minimized or expanded.
 * By default this function will call the saveSettings function
 * you can disable the saveFunctions call by passing false
 * as second argument.
 */
function toggleOptionsHeader(selector, save) {
  if (save == undefined) {
    save = true;
  }
  if($(selector).find(".arrow-up").length > 0) {
    $(selector).find(".arrow-up").addClass("arrow-down");
    $(selector).find(".arrow-up").removeClass("arrow-up");
  }
  else {
    $(selector).find(".arrow-down").addClass("arrow-up");
    $(selector).find(".arrow-down").removeClass("arrow-down");
  }
  var content = $(selector + "Content");
  content.toggle('hide', function () {
    if (save) {
      saveSettings();
    }
  });
}

function checkEntrance() {
  consoleLog("Check entrance");
  var gender = getUrlVars()["gender"];
  if (gender != null && gender == "female") {
    consoleLog("Female entrance");
    $("#female").click();
  } else {
    saveSettings();
  }
}