$(GLOBAL).bind("zoomDone", function () {
  consoleLog("zoomDone event captured");
  showMarkerPersonalMessage();
  google.maps.event.trigger(map, 'resize');
});

$(GLOBAL).bind("getTravelsDone", function () {
  consoleLog("getTravelsDone event captured");
  $("#getTravelsButton").html($("#i18LoadLogButton").html());
  if (selectedPozcard.length > 0) {
    setPozcardFields(selectedPozcard);
  }
});

$(GLOBAL).bind("createPozcardDone", function () {
  consoleLog("createPozcardDone event captured");
  $("#savePozcardButton").html("Save");
});

$(GLOBAL).bind("loadSettingsFromServerSuccess", function () {
  consoleLog("loadSettingsFromServerSuccess event captured");
  loadPozcards();
});

$(GLOBAL).bind("removePozcardDone", function () {
  consoleLog("removePozcardDone event captured");
  loadPozcards();
  clearPozcard();
});

var pozcards = [];

google.maps.event.addDomListener(window, 'load', initialize);
var defaultLatLng = new google.maps.LatLng(52.13, 5.18);
var bounds = new google.maps.LatLngBounds();
var selectedPozcard = "";
//var infowindow = new google.maps.InfoWindow();

function initialize() {
  var mapOptions = {
    center: defaultLatLng,
    zoom: zoom,
    scrollwheel: false,
    disableDoubleClickZoom: true,
    zoomControl: false,
    draggable: false,
    streetViewControl: false,
    panControl: false,
    mapTypeControl: false
  };
  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

  google.maps.event.addListener(map, 'zoom_changed', function () {
    if (initialZoom) {
      var zoomLevel = map.getZoom();
      consoleLog('Zoom: ' + zoomLevel);
      if (zoom > zoomLevel) {
        setTimeout(zoomMap, 500);
      } else {
        $(GLOBAL).trigger('zoomDone');
        initialZoom = false;
      }
    }
  });

  var timezone = jstz.determine();
  setTimezone(timezone.name());

  loadPozcards();
}

function clearPozcard() {
  $('#pozcardFields').hide();
  $('#pozcardTitle').val('');
  $('#pozcardDescription').html('');
  $('#pozcardTravelLogs').html('');
  removeLines();
  deleteMarkers();
  deletePlaces();
}

/**
 * Retrieve checkins.
 */
function getTravels() {
  consoleLog("getTravels fired");
  $(GLOBAL).trigger("getTravels");
  clearPozcard();
  $("#getTravelsButton").html("<img src='img/smallLoader.gif'/>");

  ajaxCall("/api/v1/getCheckins.php", {
    uuid: localStorage["uniqueId"],
    loginToken: localStorage["loginToken"],
    startDate: $("#startDate").val(),
    endDate: $("#endDate").val(),
    skip: 0,
    maxRows: 1000,
    sortOrder: "asc",
    descriptions: "true",
  }).fail(function (data) {
    consoleLog("getCheckins error: " + JSON.stringify(data));
    $("#pozcardsMessage").html($("#i18NoTravelLogsFoundDescription").html());
  }).done(function (data) {
    if (data.response != null) {
      switch (data.response.responseCode) {
        case 200:
          var empty = true;
          var html = '<div>';
          pozcardNickname = data.response.value.nickname;
          for (var key in data.response.value.places) {
            empty = false;
            html += '<hr/>';
            html += '<div><span title="' + data.response.value.places[key]["name"] + '">' + checkStringLength(data.response.value.places[key]["name"], 60) + '</span><span class="lightGrey right">' + data.response.value.places[key]["checkin_date"] + '</span></div>';
            html += '<div><textarea onBlur="savePlaceDescription(false, {uuid: localStorage[\'uniqueId\'], placeId: \'' + data.response.value.places[key]["id"] + '\', checkinDate: \'' + data.response.value.places[key]["date_time"] + '\', description: this.innerHTML});" id="description' + data.response.value.places[key]["id"] + '" type="text" name="description[' + data.response.value.places[key]["id"] + '][' + data.response.value.places[key]["date_time"] + ']" placeholder="' + $("#i18ShortDescriptionLabel").html() + '" rows="4" onkeyup="placesObjArray[\'' + data.response.value.places[key]["id"] + "" + data.response.value.places[key]["date_time"] + '\'].setPozcardDescription($(this).val());">' + data.response.value.places[key]["description"] + '</textarea></div>';
            createPozcardMarker(data.response.value.places[key]);
          }
          html += '</div>';
          if (empty) {
            $("#pozcardsMessage").html($("#i18NoTravelLogsFoundDescription").html());
            $("#pozcardFields").hide();
          } else {
            $("#pozcardsMessage").html("");
            $("#pozcardFields").show();
          }
          $("#pozcardTravelLogs").html(html);
          break;
        default:
          $("#pozcardsMessage").html($("#i18NoTravelLogsFoundDescription").html());
          break;
      }
    } else {
      $("#pozcardsMessage").html($("#i18NoTravelLogsFoundDescription").html());
    }
  }).always(function () {
    consoleLog("getTravelsDone fired");
    $(GLOBAL).trigger("getTravelsDone");
  });
}

function createPozcard() {
  consoleLog("createPozcard fired");
  $(GLOBAL).trigger('createPozcard');
  if ($("#pozcardTitle").val().length == 0) {
    return;
  }

  for (var key in pozcards) {
    if (pozcards[key].getTitle() == $("#pozcardTitle").val()) {
      var r = confirm($("#i18OverwritePozcardLabel").html() + pozcards[key].getTitle());
      if (r == false) {
        return;
      }
    }
  }

  consoleLog(JSON.stringify($("#pozcardForm").serializeArray()));

  $("#savePozcardButton").html("<img src='img/smallLoader.gif'/>");
  $("#uuid").val(localStorage["uniqueId"]);
  $("#loginToken").val(localStorage["loginToken"]);
  ajaxCall("/api/v1/createPozcard.php", $("#pozcardForm").serialize()).fail(function (data) {
    revealMessageDialog("createPozcard server error", JSON.stringify(data));
  }).done(function (data) {
    if (data.response != null) {
      switch (data.response.responseCode) {
        case 200:
          revealMessageDialog($("#i18PozcardSavedLabel").html(), $("#i18PozcardSavedDescription").html());
          loadPozcards();
          setSocialLinks(data.response.value);
          break;
        default:
          revealMessageDialog($("#i18PozcardSaveErrorLabel").html(), data.response.responseCode + ": " + $("#i18PozcardSaveErrorDescription").html());
          break;
      }
    } else {
      revealMessageDialog($("#pozcardSaveErrorLabel").html(), data);
    }
  }).always(function () {
    consoleLog("createPozcardDone fired");
    $(GLOBAL).trigger("createPozcardDone");
  });
}

function loadPozcards() {
  consoleLog("loadPozcards");
  $(GLOBAL).trigger('loadPozcards');
  pozcards = [];
  ajaxCall("/api/v1/getPozcards.php", {
    uuid: localStorage["uniqueId"],
    loginToken: localStorage["loginToken"],
  }).fail(function (data) {
    revealMessageDialog("loadPozcards server error", JSON.stringify(data));
  }).done(function (data) {
    if (data.response != null) {
      switch (data.response.responseCode) {
        case 200:
          consoleLog(data.response.message);
          var html = '<ul>';
          var empty = true;
          for (var key in data.response.value.pozcards) {
            empty = false;
            var pozcard = new Pozcard();
            pozcard.setUniqid(data.response.value.pozcards[key]["uniqid"]);
            pozcard.setTitle(data.response.value.pozcards[key]["title"]);
            pozcard.setDescription(data.response.value.pozcards[key]["description"]);
            pozcard.setStartDate(data.response.value.pozcards[key]["start_date"]);
            pozcard.setEndDate(data.response.value.pozcards[key]["end_date"]);
            html += '<li><a href="javascript: void(0);" onClick="loadPozcard(\'' + pozcard.getUniqid() + '\');">';
            html += $("<div/>").text(data.response.value.pozcards[key]["title"]).html();
            consoleLog(data.response.value.pozcards[key]);
            html += '</a>';
            html += '<a href="javascript: void(0);" class="right" onClick="removePozcard(\'' + pozcard.getUniqid() + '\');">[X]</a>';
            html += '</li>';
            pozcards[pozcard.getUniqid()] = pozcard;
          }
          html += '</ul>';
          if (empty) {
            html = $("#i18SavedPozcardEmpty").html();
          }
          $("#savedPozcards").html(html);
          break;
        default:
          consoleLog("loadPozcards error" + data.response.responseCode + ": " + data.response.message);
          revealMessageDialog("loadPozcards error", data.response.responseCode + ": " + data.response.message);
          break;
      }
    } else {
      consoleLog("loadPozcards server error" + data);
      revealMessageDialog("loadPozcards server error", data);
    }
  }).always(function () {
    consoleLog("loadPozcardsDone fired");
    $(GLOBAL).trigger("loadPozcardsDone");
  });
}

function loadPozcard(index) {
  consoleLog("loadPozcard: " + index);
  selectedPozcard = index;
  setPozcardFields(selectedPozcard);
  getTravels();
}

function setPozcardFields(index) {
  setSocialLinks(index);
  $("#startDate").val(pozcards[index].getStartDate());
  $("#endDate").val(pozcards[index].getEndDate());
  $("#pozcardTitle").val(pozcards[index].getTitle());
  $("#pozcardDescription").text(pozcards[index].getDescription());
}

function setSocialLinks(index) {
  consoleLog("setSocialLinks");
  var url = window.location.protocol + "//" + window.location.hostname + "/pozcard.php?pozcard=" + index;
  consoleLog("setSocialLinks: " + url);
  $("#pozcardUrl").val(url);
  $("#fb-pozcard").attr("data-href", url);
  $("#tw-pozcard").attr("data-url", url);
  $("#socialLinks").show();
  if (typeof (fbStart) != "undefined") fbStart();
  if (typeof (twitterStart) != "undefined") twitterStart();
  if (typeof (gplusStart) != "undefined") gplusStart();
}

function removePozcard(uniqid) {
  consoleLog("Delete pozcard: " + uniqid);
  consoleLog("removePozcard fired");
  $(GLOBAL).trigger("removePozcard");
  var r = confirm($("#i18DeletePozcardLabel").html() + pozcards[uniqid].getTitle());
  if (r == false) {
    return;
  }

  ajaxCall("/api/v1/removePozcard.php", {
    uuid: localStorage["uniqueId"],
    loginToken: localStorage["loginToken"],
    uniqid: uniqid
  }).fail(function (data) {
    revealMessageDialog("removePozcard server error", JSON.stringify(data));
  }).done(function (data) {
    if (data.response != null) {
      switch (data.response.responseCode) {
        case 200:
          consoleLog(data.response.message);
          revealMessageDialog($("#i18PozcardRemovedLabel").html(), $("#i18PozcardRemovedDescription").html());
          break;
        default:
          consoleLog("removePozcard error" + data.response.responseCode + ": " + data.response.message);
          revealMessageDialog("removePozcard server error", data.response.responseCode + ": " + data.response.message);
          break;
      }
    } else {
      consoleLog("removePozcard server error" + data);
      revealMessageDialog("removePozcard server error", data);
    }
  }).always(function () {
    consoleLog("removePozcardDone fired");
    $(GLOBAL).trigger("removePozcardDone");
  });
}