var trailOfVictoryRows = Array();
var autoloadRankingsPersonal = true;
$(GLOBAL).bind("appStart", function () {
  if (localStorage["uniqueId"] != null) {
    if (autoloadRankingsPersonal) {
      if ($("#getCheckins").length > 0) {
        getCheckins("getCheckins", "Show more trails!");
      }
      if ($("#getConquests").length > 0) {
        getCheckins("getConquests", "Show more conquests!");
      }
    }
    $("#personalRankings").show();
  }
});

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

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

$(GLOBAL).bind("getCheckinsDone", function () {
  consoleLog("getCheckinsDone event captured");
  $(".getCheckinsButton").html("Show more trails!");
});

$(GLOBAL).bind("getConquestsDone", function () {
  consoleLog("getConquestsDone event captured");
  $(".getConquestsButton").html("Show more conquests!");
});

/**
 * Get retrieve checkins from given apiCall.
 * Checkins are set to an HTML element of which id is apiCall.
 */
function getCheckins(apiCall, uuid, buttonMoreText) {
  consoleLog(apiCall + " fired");
  $(GLOBAL).trigger(apiCall);
  trailOfVictoryRows[apiCall] = 0;
  var emptyText = $("#i18NoMarksLabel").html();
  if (buttonMoreText == null) {
    buttonMoreText = $("#i18ShowMoreLabel").html();
  }
  ajaxCall("/api/v1/" + apiCall + ".php", {
    uuid: localStorage["uniqueId"],
    loginToken: localStorage["loginToken"]
  }).fail(function(data) {
    consoleLog(apiCall + " error: " + data);
    $("#" + apiCall).html(emptyText);
  }).done(function(data) {
    if (data.response != null) {
      switch (data.response.responseCode) {
        case 200:
          var empty = true;
          var html = '<table id="' + apiCall + 'Table" class="left small-12 columns"><thead>';
          html += '<tr>';
          html += '<th>' + $("#i18NameLabel").html() + '</th>';
          html += '<th>' + $("#i18DateLabel").html() + '</th>';
          html += '</tr></thead><tbody>';
          for (var key in data.response.value.places) {
            trailOfVictoryRows[apiCall]++;
            empty = false;
            html += '<tr>';
            html += '<td><span title="' + data.response.value.places[key]["name"] + '">' + checkStringLength(data.response.value.places[key]["name"], 60) + '</span></td>';
            html += '<td><span>' + data.response.value.places[key]["checkin_date"] + '</span></td>';
            html += '</tr>';
          }
          html += '</tbody></table>';
          if (data.response.value.total_rows > trailOfVictoryRows[apiCall]) {
            html += '<div class="row" id="more' + apiCall + '"><div class="small-12 large-4 small-centered columns text-center"><a class="button small secondary ' + apiCall + 'Button" href="javascript: void(0);" onClick="getNextCheckins(\'' + apiCall + '\', \'' + uuid + '\');">' + buttonMoreText + '</a></div></div>';
          }
          if (empty) {
            html = emptyText;
          }
          $("#" + apiCall).html(html);
          break;
        default:
          consoleLog(data.response.responseCode + ": " + data.response.message);
          $("#" + apiCall).html(emptyText);
          break;
      }
    } else {
      consoleLog(data);
    }
  }).always(function() {
    // Trigger event.
    consoleLog(apiCall + "Done fired");
    $(GLOBAL).trigger(apiCall + 'Done');
  })
}

function getNextCheckins(apiCall, uuid) {
  // Trigger event.
  consoleLog(apiCall + " fired");
  $(GLOBAL).trigger(apiCall);

  ajaxCall("/api/v1/" + apiCall + ".php", {
    uuid: localStorage["uniqueId"],
    loginToken: localStorage["loginToken"],
    skip: trailOfVictoryRows[apiCall]
  }).fail(function(data){
    consoleLog(apiCall + " next error: " + data);
  }).done(function(data){
    if (data.response != null) {
      switch (data.response.responseCode) {
        case 200:
          var html = '';
          for (var key in data.response.value.places) {
            trailOfVictoryRows[apiCall]++;
            html += '<tr>';
            html += '<td><span title="' + data.response.value.places[key]["name"] + '">' + checkStringLength(data.response.value.places[key]["name"], 60) + '</span></td>';
            html += '<td><span>' + data.response.value.places[key]["checkin_date"] + '</span></td>';
            html += '</tr>';
          }
          if (data.response.value.total_rows <= trailOfVictoryRows[apiCall]) {
            $("#more" + apiCall).remove();
          }
          $('#' + apiCall + 'Table').find('tbody:last').append(html);
          break;
        default:
          consoleLog(data.response.responseCode + ": " + data.response.message);
          break;
      }
    } else {
      consoleLog(data);
    }
  }).always(function(){
    // Trigger event.
    consoleLog(apiCall + "Done fired");
    $(GLOBAL).trigger(apiCall + 'Done');
  });
}