var autoloadRankings = true;
$(GLOBAL).bind("appStart", function () {
  if (autoloadRankings) {
    if ($("#totalGenderPercentages").length > 0) {
      getPointsMenVsWomen();
    }
    if ($("#getRankingsAllUsers").length > 0) {
        getRankings("getRankingsAllUsers", null, processRanking);
    }
    if ($("#getRankingsAllMen").length > 0) {
        getRankings("getRankingsAllMen", null, processRanking);
    }
    if ($("#getRankingsAllWomen").length > 0) {
        getRankings("getRankingsAllWomen", null, processRanking);
    }
    if ($("#getRankingsTitles").length > 0) {
        getRankings("getRankingsTitles", "PlacesConquered", processTitles);
    }
    if ($("#getRankingsConquestAll").length > 0) {
        getRankings("getRankingsConquestAll", "PlacesConquered", processRanking);
    }
    if ($("#getRankingsConquestMen").length > 0) {
        getRankings("getRankingsConquestMen", "PlacesConquered", processRanking);
    }
    if ($("#getRankingsConquestWomen").length > 0) {
        getRankings("getRankingsConquestWomen", "PlacesConquered", processRanking);
    }
    if ($("#getRankingsCheckinAll").length > 0) {
        getRankings("getRankingsCheckinAll", "CheckinCount", processRanking);
    }
    if ($("#getRankingsCheckinMen").length > 0) {
        getRankings("getRankingsCheckinMen", "CheckinCount", processRanking);
    }
    if ($("#getRankingsCheckinWomen").length > 0) {
        getRankings("getRankingsCheckinWomen", "CheckinCount", processRanking);
    }
  }
});

var nobleTitles = {
"m1" : "Emperor",
"m2" : "King",
"m3" : "Duke",
"f1" : "Empress",
"f2" : "Queen",
"f3" : "Duchess",
};

/**
 * Get retrieve rankings from given apiCall.
 * Rankings are set to an HTML element of which id is apiCall.
 */
function getRankings(apiCall, columnName, handler) {
  consoleLog("getRankings fired");
  $(GLOBAL).trigger('getRankings');
  if (columnName == null) {
    columnName = "Points";
  }
  ajaxCall("/api/v1/" + apiCall + ".php", {
    uuid: localStorage["uniqueId"]
  }).fail(function(data) {
    consoleLog(apiCall + " error: " + JSON.stringify(data));
  }).done(function(data) {
    if (data.response != null) {
      switch (data.response.responseCode) {
        case 200:
          handler(apiCall, columnName, data);
          break;
        default:
          revealMessageDialog(apiCall + " error", data.response.responseCode + ": " + data.response.message);
          break;
      }
    } else {
      revealMessageDialog(apiCall + " error", data);
    }
  }).always(function() {
    // Trigger event.
    consoleLog("getRankingsDone fired");
    $(GLOBAL).trigger('getRankingsDone');
  });
}

function processRanking(apiCall, columnName, data) {
  var html = '<table class="left small-12 columns"><thead>';
  html += '<tr>';
  html += '<th width="50"></th>';
  html += '<th>' + $("#i18NicknameLabel").html() + '</th>';
  html += '<th>' + $("#i18" + columnName + "Label").html() + '</th>';
  html += '</tr></thead><tbody>';
  var empty = true;
  var count = 0;
  for (var key in data.response.value.rankings) {
    count++;
    empty = false;
    html += '<tr>';
    html += '<td>';
    if (data.response.value.rankings[key]["photo_url"] != null && data.response.value.rankings[key]["photo_url"].length > 0) {
      html += '<img class="conquerorImage" alt="' + data.response.value.rankings[key]["nickname"] + '" src="' + data.response.value.rankings[key]["photo_url"] + '"></img>';
    }
    html += '</td>';
    html += '<td><span title="' + data.response.value.rankings[key]["nickname"] + '">' + checkStringLength(data.response.value.rankings[key]["nickname"], 60) + '</span></td>';
    html += '<td>' + Number(parseFloat(data.response.value.rankings[key]["points"]).toFixed(2)).toString() + '</td>';
    html += '</tr>';
  }
  for (var i = count; i < 10; ++i) {
    html += '<tr>';
    html += '<td></td>';
    html += '<td>--</td>';
    html += '<td>--</td>';
    html += '</tr>';
  }
  html += '</tbody></table>';
  if (empty) {
    html = "No rankings";
  }
  $("#" + apiCall).html(html);
}

function processTitles(apiCall, columnName, data) {
  var html = '<table class="left small-12 columns"><thead>';
  html += '<tr>';
  html += '<th width="50"></th>';
  html += '<th>' + $("#i18NicknameLabel").html() + '</th>';
  html += '<th>' + $("#i18" + columnName + "Label").html() + '</th>';
  html += '</tr></thead><tbody>';
  var empty = true;
  var count = 0;
  for (var key in data.response.value.rankings) {
    count++;
    empty = false;
    html += '<tr>';
    html += '<td>';
    if (data.response.value.rankings[key]["photo_url"] != null && data.response.value.rankings[key]["photo_url"].length > 0) {
      html += '<img class="conquerorImage" alt="' + data.response.value.rankings[key]["nickname"] + '" src="' + data.response.value.rankings[key]["photo_url"] + '"></img>';
    }
    html += '</td>';
    var title = getNobleTitle(data.response.value.rankings[key]["rank"], data.response.value.rankings[key]["gender"]) + " " + data.response.value.rankings[key]["nickname"] + " of " + data.response.value.rankings[key]["city"];
    var aRGB = argbToRGB(hashCode(data.response.value.rankings[key]["nickname"]));
    consoleLog("Color: " + aRGB);
    var titleHtml = getNobleTitle(data.response.value.rankings[key]["rank"], data.response.value.rankings[key]["gender"]) + " <span style='font-weight: bold; color: #" + aRGB + "'>" + data.response.value.rankings[key]["nickname"] + "</span> of " + data.response.value.rankings[key]["city"];
    html += '<td><span title="' + title + '">' + titleHtml + '</span></td>';
    html += '<td>' + Number(parseFloat(data.response.value.rankings[key]["points"]).toFixed(2)).toString() + '</td>';
    html += '</tr>';
  }
  for (var i = count; i < 10; ++i) {
    html += '<tr>';
    html += '<td></td>';
    html += '<td>--</td>';
    html += '<td>--</td>';
    html += '</tr>';
  }
  html += '</tbody></table>';
  if (empty) {
    html = "No rankings";
  }
  $("#" + apiCall).html(html);
}

function getNobleTitle(rank, gender) {
  //consoleLog("getNobleTitle: " + rank + " " + gender)
  var result = "";
  if (gender == "male") {
    switch (rank) {
      case "1":
        result = nobleTitles["m1"];
        break;
      case "2":
        result = nobleTitles["m2"];
        break;
      case "3":
        result = nobleTitles["m3"];
        break;
    }
  } else {
    switch (rank) {
      case "1":
        result = nobleTitles["f1"];
        break;
      case "2":
        result = nobleTitles["f2"];
        break;
      case "3":
        result = nobleTitles["f3"];
        break;
    }
  }
  //consoleLog("getNobleTitle: " + result)
  return result;
}

function getPointsMenVsWomen() {
  consoleLog("getPointsMenVsWomen fired");
  $(GLOBAL).trigger('getPointsMenVsWomen');
  ajaxCall("/api/v1/getPointsMenVsWomen.php", {}).fail(function (data) {
    consoleLog("getPointsMenVsWomen error: " + JSON.stringify(data));
  }).done(function (data) {
    if (data.response != null) {
      switch (data.response.responseCode) {
        case 200:
          consoleLog(JSON.stringify(data));
          for (var key in data.response.value.rankings) {
            var ranking = data.response.value.rankings[key];
            var name = ranking["name"];
            if (name == "malePoints") {
              $("#byPointsMalePercentage").html(ranking["value"]);
            } else if (name == "femalePoints") {
              $("#byPointsFemalePercentage").html(ranking["value"]);
            } else if (name == "maleConquests") {
              $("#byConquestsMalePercentage").html(ranking["value"]);
            } else if (name == "femaleConquests") {
              $("#byConquestsFemalePercentage").html(ranking["value"]);
            } else if (name == "maleCheckins") {
              $("#byCheckinsMalePercentage").html(ranking["value"]);
            } else if (name == "femaleCheckins") {
              $("#byCheckinsFemalePercentage").html(ranking["value"]);
            }
          }
          break;
        default:
          revealMessageDialog("getPointsMenVsWomen error", data.response.responseCode + ": " + data.response.message);
          break;
      }
    } else {
      revealMessageDialog("getPointsMenVsWomen error", data);
    }
  }).always(function () {
    // Trigger event.
    consoleLog("getPointsMenVsWomenDone fired");
    $(GLOBAL).trigger('getPointsMenVsWomenDone');
  });
}
