function getCookie(name) {
  var allCookies = document.cookie;
  var position = allCookies.indexOf(name);
  if (position != -1) {
    var start = position + name.length + 1;
    var end = allCookies.indexOf(";", start);
    if (end == -1) end = allCookies.length;
    var value = allCookies.substring(start, end);
    return unescape(value);
  } else {
    return null;
  }
}

var scoreboardCookie = getCookie("expandedGameIds");
var expandedIds      = (scoreboardCookie == null || scoreboardCookie == "") ? new Array() : scoreboardCookie.split("|");
var nextYear         = new Date();
nextYear.setFullYear(nextYear.getFullYear() + 1);

Array.prototype.contains = function(item) {
  for (var i = 0; i < this.length; ++i) {
    if (this[i] == item) {
      return true;
    }
  }
  return false;
}

function expandStats(gameId, lang) {
  var gameDiv  = document.getElementById(gameId + "_expand");
  var gameLink = document.getElementById(gameId + "_togglelink");
  if (gameDiv && gameLink) {
    gameDiv.style.display = "block";
    if (lang == "en") {
      gameLink.innerHTML = "Close -";
    } else {
      gameLink.innerHTML = "Cerrar -";
    }
    if (!expandedIds.contains(gameId)) {
      expandedIds.push(gameId);
      document.cookie = "expandedGameIds=" + expandedIds.join("|") + ";"
    }
  }
}

function collapseStats(gameId, lang) {
  var gameDiv  = document.getElementById(gameId + "_expand");
  var gameLink = document.getElementById(gameId + "_togglelink");
  if (gameDiv && gameLink) {
    gameDiv.style.display = "none";
    if (lang == "en") {
      gameLink.innerHTML = "Expand +";
    } else {
      gameLink.innerHTML = "Expandir +";
    }
    if (expandedIds.contains(gameId)) {
      for (var i = 0; i < expandedIds.length; ++i) {
        if (expandedIds[i] == gameId) {
          expandedIds.splice(i, 1);
        }
      }
      document.cookie = "expandedGameIds=" + expandedIds.join("|") + ";"
    }
  }
}

function toggleStats(gameId, lang) {
  var gameDiv = document.getElementById(gameId + "_expand");
  if (gameDiv) {
    if (gameDiv.style.display == "none") {
      expandStats(gameId, lang);
    } else {
      collapseStats(gameId, lang);
    }
  }
}


