var checkedInModalDescriptionSaveDelay;
$('#checkedInModalDescription').keyup(function (e) {
  if (checkedInModalDescriptionSaveDelay != null) {
    clearTimeout(checkedInModalDescriptionSaveDelay);
  }
  checkedInModalDescriptionSaveDelay = setTimeout("savePlaceDescription(false)", 2000);
});


function checkIn(placeCont) {
  consoleLog("checkinStart event fired");
  $(GLOBAL).trigger("checkinStart");
  if (placeCont != undefined) {
    var placeResult = placeCont.getPlaceResult();
    var lat = placeCont.getLat();
    var lng = placeCont.getLng();
    var distance = getDistance(defaultLatLng.lat(), defaultLatLng.lng(), lat, lng).toFixed(3);
    ajaxCall("/api/v1/checkIn.php", {
      uuid: localStorage["uniqueId"],
      name: placeResult.name,
      vicinity: placeResult.vicinity,
      city: placeCont.getCity(),
      lat: lat,
      lng: lng,
      ulat: defaultLatLng.lat(),
      ulng: defaultLatLng.lng(),
      gender: $("input[name=gender]:checked").val()
    }).fail(function (data) {
      consoleLog("check-in error: " + data);
    }).done(function (data) {
      if (data.response != null) {
        switch (data.response.responseCode) {
          case 200:
            consoleLog(JSON.stringify(data));
            $("#checkedInModalPlaceName").html(placeResult.name);
            $("#checkedInModalLat").val(lat);
            $("#checkedInModalLng").val(lng);
            $("#checkedInModalPoints").html(data.response.value.points);
            $("#checkedInModalPlaceId").val(data.response.value.placeId);
            $("#checkedInModalCheckinDate").val(data.response.value.checkinDate);
            if (data.response.value.otherUsersCheckedIn) {
              $("#checkedInModalAnotherPlayerBeforeYou").html($("#i18AnotherPlayerCheckedInBeforeYouLabel").html());
            } else {
              $("#checkedInModalAnotherPlayerBeforeYou").html("");
            }
            revealDialog("#checkedInModal");
            checkCooldown();
            getPointsTotal();
            showChallengesCount();
            placeCont.loadPoints();

            break;
          case 409.1:
            consoleLog(JSON.stringify(data.response.value));
            movementSpeedTooFast(data.response.message);
            break;
          case 409.2:
            consoleLog(JSON.stringify(data.response.value));
            tooFarAway();
            break;
          case 429.1:
            consoleLog(JSON.stringify(data.response.value));
            tooManyRequests(data.response.value[0]);
            break;
          case 429.2:
            consoleLog(JSON.stringify(data.response.value));
            tooManySameRequests(data.response.value[0], data.response.value[1]);
            break;
          default:
            revealMessageDialog($("#i18CheckinErrorLabel").html(), data.response.responseCode + ": " + data.response.message);
            break;
        }
      } else {
        revealMessageDialog($("#i18CheckinErrorLabel").html(), data);
      }
    }).always(function () {
      consoleLog("checkinDone fired");
      $(GLOBAL).trigger("checkinDone");
    });
  } else {
    revealMessageDialog($("#i18CheckinErrorLabel").html(), $("#i18CheckinPlaceNotExistErrorDescription").html());
  }
}

function savePlaceDescription(showResponseModals, data) {
  consoleLog("savePlaceDescription event fired");
  $(GLOBAL).trigger("savePlaceDescription");

  if (typeof (data) == "undefined") {
    data = {
      uuid: localStorage["uniqueId"],
      placeId: $("#checkedInModalPlaceId").val(),
      checkinDate: $("#checkedInModalCheckinDate").val(),
      description: $("#checkedInModalDescription").val()
    };
  }

  ajaxCall("/api/v1/setPlaceDescription.php", data).fail(function (data) {
    consoleLog("check-in error: " + data);
  }).done(function (data) {
    if (showResponseModals) {
      if (data.response != null) {
        switch (data.response.responseCode) {
          case 200:
            revealMessageDialog($("#i18PlaceSavedLabel").html(), $("#i18PlaceSavedDescription").html());
            break;
          default:
            revealMessageDialog($("#i18SavePlaceFailedLabel").html(), data.response.responseCode + ": " + data.response.message);
            break;
        }
      } else {
        revealMessageDialog($("#i18SavePlaceFailedLabel").html(), data);
      }
    } else {
      // We show indication that it's saved because we don't show a success modal.
      consoleLog("saveSettingsToServerDone fired");
      $(GLOBAL).trigger("saveSettingsToServerDone");
    }
  }).always(function () {
    consoleLog("savePlaceDescriptionDone fired");
    $(GLOBAL).trigger("savePlaceDescriptionDone");
  });
}