nickchild / FPL get team info

// ==UserScript==
// @name        FPL get team info
// @namespace   nickchild
// @include     https://fantasy.premierleague.com/a/leagues/standings/*
// @version     4.0.4
// @license	GPL-3.0-or-later; http://www.gnu.org/licenses/gpl-3.0.txt
// ==/UserScript==

links = document.getElementsByTagName("a");
gwnum = 0;
for (i = 0; i < links.length; i++) {
  if (links[i].innerHTML == "Points") {
    tmpurl = links[i].href;
    tmparr = tmpurl.split("/");
    gwnum = tmparr[tmparr.length - 1];
    break;
  }
}

config_items = new Array("teamval", "bankval", "totalval", "tt", "gwt", "hitpts", "wc", "chips", "captain", "h2h", "livepoints", "livetotal", "wide", "played");
config_values = {};
config_strs = {};
config_strs["teamval"] = "Team value";
config_strs["bankval"] = "Bank value";
config_strs["totalval"] = "Total value";
config_strs["tt"] = "Total transfers";
config_strs["gwt"] = "Gameweek transfers";
config_strs["wc"] = "Wildcard";
config_strs["chips"] = "Chips";
config_strs["captain"] = "Captain";
config_strs["h2h"] = "H2H league position";
config_strs["livepoints"] = "Live gameweek points";
config_strs["livetotal"] = "Live total points";
config_strs["wide"] = "Extra wide";
config_strs["played"] = "Playing stats";
config_strs["hitpts"] = "Transfer points hit";

for (i = 0; i < config_items.length; i++) {
  c = config_items[i];
  config_values[c] = getCookie(c);
}

optionWidth = "220px";
if (config_values["wide"] == 1) {
  refreshWidth = "1100px";
}
else {
  refreshWidth = "880px";
}

function GetXmlHttpObject() {
  var xmlHttp = null;
  try {
    xmlHttp = new XMLHttpRequest();
  }
  catch (e) {
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  return xmlHttp;
}

function numberWithCommas(x) {
  var parts = x.toString().split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join(".");
}

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function getData() {
  if (!document.getElementById("ismr-classic-standings")) {
    setTimeout(function () {
      getData();
    }, 2000);
    return;
  }

  standingsDiv = document.getElementById("ismr-classic-standings");
  tables = standingsDiv.getElementsByTagName("table");
  table = tables[0];
  trs = table.getElementsByTagName("tr");
  for (j = 0; j < trs.length; j++) {

    ancs = trs[j].getElementsByTagName("a");
    tds = trs[j].getElementsByTagName("td");
    if (ancs.length > 0) {
      anc = tds[1].getElementsByTagName("a");
      arr1 = anc[0].href.split("team/");
      teamID = arr1[1];
      idpn = "row" + teamID;
      trs[j].id = idpn;

      url = "https://fantasy.premierleague.com/drf/entry/" + teamID + "/event/" + gwnum + "/picks";
      var xmlHttp = GetXmlHttpObject();
      xmlHttp.onreadystatechange = stateChangedEvent;
      xmlHttp.open("GET", url, true);
      xmlHttp.send(null);

    }
    else if (j == 0) {
      headstr = "";
      if (config_values["teamval"] == 1) {
        headstr += "<th title='Team value'>Value</th>";
      }
      if (config_values["bankval"] == 1) {
        headstr += "<th title='Bank value'>Bank</th>";
      }
      if (config_values["totalval"] == 1) {
        headstr += "<th title='Total value'>Total</th>";
      }
      if (config_values["tt"] == 1) {
        headstr += "<th><abbr title='Total transfers'>TT</abbr></th>";
      }
      if (config_values["gwt"] == 1) {
        headstr += "<th><abbr title='Gameweek transfers'>GWT</abbr></th>";
      }
      if (config_values["hitpts"] == 1) {
        headstr += "<th><abbr title='Transfer points hit'>TPH</abbr></th>";
      }
      if (config_values["wc"] == 1) {
        headstr += "<th><abbr title='Wildcard available'>WC</abbr></th>";
      }
      if (config_values["chips"] == 1) {
        headstr += "<th><abbr title='Chips played'>Chips</abbr></th>";
      }
      if (config_values["captain"] == 1) {
        headstr += "<th>Captain</th>";
      }
      if (config_values["h2h"] == 1) {
        headstr += "<th><abbr title='Associated H2H league position'>H2H</abbr></th>";
      }
      if (config_values["livepoints"] == 1) {
        headstr += "<th><abbr title='Live gameweek points'>Live</abbr></th>";
      }
      if (config_values["livetotal"] == 1) {
        headstr += "<th><abbr title='Live points total'>Total</abbr></th>";
      }
      if (config_values["played"] == 1) {
        headstr += "<th><abbr title='Players played'>P</abbr></th>";
        headstr += "<th><abbr title='Players to play'>TP</abbr></th>";
        headstr += "<th><abbr title='Players who did not play'>DNP</abbr></th>";
      }
      ths = trs[j].getElementsByTagName("th");
      ths[0].className = "sorttable_nosort";
      ths[0].innerHTML = '<abbr onclick="divs=document.getElementsByTagName(\'div\');onoff=\'\';for(i=0;i<divs.length;i++){tmpid=divs[i].id;if(tmpid.lastIndexOf(\'teamdiv_\', 0) === 0){if(onoff==\'\'){if(divs[i].style.display == \'none\'){onoff=\'on\'}else{onoff=\'off\'}}if(onoff==\'on\'){divs[i].style.display=\'\'}else{divs[i].style.display=\'none\'}}}" title="Toggle teams">T</abbr>';
      ths[1].className = "sorttable_nosort";
      trs[j].innerHTML = trs[j].innerHTML + headstr;
    }
  }
  table.innerHTML = table.innerHTML + "<tr><td colspan=21><div id='configrow'></div></td></tr>";
  configrow = document.getElementById("configrow");

  for (i = 0; i < config_items.length; i++) {
    c = config_items[i];
    var div = document.createElement('div');
    div.style.display = "inline-block";
    div.style.float = "left";
    div.style.width = optionWidth;
    var span = document.createElement('span');
    span.appendChild(document.createTextNode(config_strs[c] + ': '));
    div.appendChild(span);

    var a = document.createElement('a');
    if (config_values[c] == 0) {
      a.style.color = "#bbb";
    }
    a.id = c + '_on';
    a.appendChild(document.createTextNode('On'));
    a.href = 'javascript:null(0)';
    eval("a.addEventListener('click', function(){document.getElementById(\"" + c + "_on\").style.color='#000'; document.getElementById(\"" + c + "_off\").style.color='#bbb'; setCookie(\"" + c + "\", 1,1);}, false);");
    div.appendChild(a);

    var span = document.createElement('span');
    span.appendChild(document.createTextNode(' | '));
    div.appendChild(span);

    var a = document.createElement('a');
    if (config_values[c] == 1) {
      a.style.color = "#bbb";
    }
    a.id = c + '_off';
    a.appendChild(document.createTextNode('Off'));
    a.href = 'javascript:null(0)';
    eval("a.addEventListener('click', function(){document.getElementById(\"" + c + "_off\").style.color='#000'; document.getElementById(\"" + c + "_on\").style.color='#bbb'; setCookie(\"" + c + "\", 0, 1);}, false);");
    div.appendChild(a);
    configrow.appendChild(div);
  }

  var div = document.createElement('div');
  div.style.display = "inline-block";
  div.style.float = "left";
  div.style.width = optionWidth;
  var span = document.createElement('span');
  span.appendChild(document.createTextNode('All: '));
  div.appendChild(span);

  var a = document.createElement('a');
  a.id = 'all_on';
  a.appendChild(document.createTextNode('On'));
  a.href = 'javascript:null(0)';
  a.addEventListener('click', function () {
    for (i = 0; i < config_items.length; i++) {
      c = config_items[i];
      document.getElementById(c + "_on").style.color = '#000';
      document.getElementById(c + "_off").style.color = '#bbb';
      setCookie(c, 1);
    }
  }, false);
  div.appendChild(a);

  var span = document.createElement('span');
  span.appendChild(document.createTextNode(' | '));
  div.appendChild(span);

  var a = document.createElement('a');
  a.id = 'all_off';
  a.appendChild(document.createTextNode('Off'));
  a.href = 'javascript:null(0)';
  a.addEventListener('click', function () {
    for (i = 0; i < config_items.length; i++) {
      c = config_items[i];
      document.getElementById(c + "_off").style.color = '#000';
      document.getElementById(c + "_on").style.color = '#bbb';
      setCookie(c, 0);
    }
  }, false);
  div.appendChild(a);
  configrow.appendChild(div);

  var div = document.createElement('div');
  div.style.display = "inline-block";
  div.style.float = "left";
  div.style.width = optionWidth;
  var span = document.createElement('span');
  span.appendChild(document.createTextNode('Quick picks: '));
  div.appendChild(span);

  var a = document.createElement('a');
  a.id = 'all_on';
  a.appendChild(document.createTextNode('Team Info'));
  a.href = 'javascript:null(0)';
  a.addEventListener('click', function () {
    for (i = 0; i < config_items.length; i++) {
      if (i < 8) {
        c = config_items[i];
        document.getElementById(c + "_on").style.color = '#000';
        document.getElementById(c + "_off").style.color = '#bbb';
        setCookie(c, 1);
      }
      else {
        c = config_items[i];
        document.getElementById(c + "_off").style.color = '#000';
        document.getElementById(c + "_on").style.color = '#bbb';
        setCookie(c, 0);
      }
    }
  }, false);
  div.appendChild(a);

  var span = document.createElement('span');
  span.appendChild(document.createTextNode(' | '));
  div.appendChild(span);

  var a = document.createElement('a');
  a.id = 'all_off';
  a.appendChild(document.createTextNode('Live Data'));
  a.href = 'javascript:null(0)';
  a.addEventListener('click', function () {
    for (i = 0; i < config_items.length; i++) {
      if (i == 7 || i == 8 || i == 10 || i == 11 || i == 13) {
        c = config_items[i];
        document.getElementById(c + "_on").style.color = '#000';
        document.getElementById(c + "_off").style.color = '#bbb';
        setCookie(c, 1);
      }
      else {
        c = config_items[i];
        document.getElementById(c + "_off").style.color = '#000';
        document.getElementById(c + "_on").style.color = '#bbb';
        setCookie(c, 0);
      }
    }
  }, false);
  div.appendChild(a);
  configrow.appendChild(div);

  var div = document.createElement('div');
  div.style.display = "inline-block";
  div.style.width = refreshWidth;
  div.style.float = "bottom";
  div.style.paddingTop = "10px";
  var span = document.createElement('span');
  var a = document.createElement('a');
  a.appendChild(document.createTextNode('Reload'));
  a.href = 'javascript:location.reload()';
  a.style.border = "1px solid #000";
  a.style.padding = "3px";
  a.style.borderRadius = "6px";
  span.appendChild(a);
  div.appendChild(span);
  configrow.appendChild(div);

}

setTimeout(function () {
  getData();
}, 2000);

var playersObj = [];
var teamsObj = [];
var livePlayersObj = [];
var fixturesObj = [];

function stateChangedPlayers() {
  if (this.readyState == 4) {
    retval = this.responseText;
    playersObjTmp = JSON.parse(retval);
    for (i = 0; i < playersObjTmp.elements.length; i++) {
      playersObj[playersObjTmp.elements[i].id] = playersObjTmp.elements[i];
    }
    for (i = 0; i < playersObjTmp.teams.length; i++) {
      teamsObj[playersObjTmp.teams[i].code] = playersObjTmp.teams[i];
    }
  }
}


function stateChangedFixtures() {
  if (this.readyState == 4) {
    retval = this.responseText;
    fixturesObjTmp = JSON.parse(retval);
    for (i = 0; i < fixturesObjTmp.length; i++) {
      fixturesObj[fixturesObjTmp[i].id] = fixturesObjTmp[i];
      if (fixturesObjTmp[i].event == gwnum) {
        tmpPlayedArray = [];
        for (ai = 0; ai < fixturesObjTmp[i].stats[9].bps.a.length; ai++) {
          tmpPlayedArray.push(fixturesObjTmp[i].stats[9].bps.a[ai].element);
        }
        for (ai = 0; ai < fixturesObjTmp[i].stats[9].bps.h.length; ai++) {
          tmpPlayedArray.push(fixturesObjTmp[i].stats[9].bps.h[ai].element);
        }
        fixturesObj[fixturesObjTmp[i].id].playedArray = tmpPlayedArray;
      }
    }
  }
}

function stateChangedLive() {
  if (this.readyState == 4) {
    retval = this.responseText;
    liveObjTmp = JSON.parse(retval);
    fixturesObjTmp = liveObjTmp.fixtures;
    for (i = 0; i < fixturesObjTmp.length; i++) {
      fixturesObj[fixturesObjTmp[i].id] = fixturesObjTmp[i];
    }
    livePlayersObj = liveObjTmp.elements;
  }
}

url = "https://fantasy.premierleague.com/drf/bootstrap-static";
var xmlHttp = GetXmlHttpObject();
xmlHttp.onreadystatechange = stateChangedPlayers;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);

/*
url = "https://fantasy.premierleague.com/drf/fixtures";
var xmlHttp = GetXmlHttpObject();
xmlHttp.onreadystatechange = stateChangedFixtures;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
*/

url = "https://fantasy.premierleague.com/drf/event/"+gwnum+"/live";
var xmlHttp = GetXmlHttpObject();
xmlHttp.onreadystatechange = stateChangedLive;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);

function stateChangedEntry() {
  if (this.readyState == 4) {
    retval = this.responseText;
    entryObj = JSON.parse(retval);
    info = entryObj.entry;
    chipsObj = entryObj.chips;
    tmpid = info.id;
    tt = info.total_transfers;
    et = info.event_transfers;
    etc = info.event_transfers_cost;

    value = info.value / 10;
    bank = info.bank / 10;
    total_value = Math.round((value + bank) * 10) / 10;

    chipCount = chipsObj.length;
    chipStr = "";
    chipActive = false;

    wildcardUsed = 0;
    for (ci = 0; ci < chipCount; ci++) {
      if (chipsObj[ci].event == gwnum) {
        chipActive = true
      };
      tmpname = chipsObj[ci].name;
      if (tmpname == "bboost") {
        tmpname = "Bench Boost";
      }
      if (tmpname == "wildcard") {
        tmpname = "Wildcard";
      }
      if (tmpname == "bboost") {
        tmpname = "Bench Boost";
      }
      if (tmpname == "3xc") {
        tmpname = "Triple Captain";
      }
      if (tmpname == "fhit" || tmpname == "freehit") {
        tmpname = "Free Hit";
      }
      if (chipStr != "") {
        chipStr += "\n";
      }
      chipStr += tmpname + " (GW" + chipsObj[ci].event + ")";
      if (chipsObj[ci].name == "wildcard") {
        wildcardUsed = chipsObj[ci].event;
      }
    }

    document.getElementById("teamval" + tmpid).innerHTML = value;
    document.getElementById("bankval" + tmpid).innerHTML = bank;
    document.getElementById("totalval" + tmpid).innerHTML = total_value;

    document.getElementById("tt" + tmpid).innerHTML = tt;
    document.getElementById("gwt" + tmpid).innerHTML = et;
    document.getElementById("hitpts" + tmpid).innerHTML = etc;

    if (wildcardUsed == 0) {
      document.getElementById("wc" + tmpid).innerHTML = "<span title='Available' style='color: green'>&#10003;</span>";
    }
    else {
      document.getElementById("wc" + tmpid).innerHTML = "<span title='Used GW" + wildcardUsed + "' style='color: red'>X</span>";
    }
    chipStyleStr = "";
    if (chipActive) {
      chipStyleStr = " style='background-color: #ffe6e6; padding: 10px'";
    }
    document.getElementById("chips" + tmpid).innerHTML = "<span title='" + chipStr + "'" + chipStyleStr + ">" + chipCount + "</span>";
  }
}

function stateChangedEvent() {
  if (this.readyState == 4) {
    retval = this.responseText;
    teamObj = JSON.parse(retval);

    value = "";
    bank = "";
    total_value = "";
    total_transfers = "";
    gw_transfers = "";
    transfers_hit = "";

    team_id = teamObj.entry_history.entry;
    picks = teamObj.picks;
    live_score = 0;

    playedstr = "";
    playednum = 0;
    toplaystr = "";
    toplaynum = 0;
    didntplaystr = "";
    didntplaynum = 0;
    startingStr = "";
    benchStr = "";

    captain_dnp = false;
    for (pick_i = 0; pick_i < (picks.length); pick_i++) {
      playerData = playersObj[picks[pick_i].element];

      if (picks[pick_i].position < 12) {
        live_score = live_score + playerData.event_points * picks[pick_i].multiplier;
        if (startingStr != "") {
          startingStr += ", ";
        }
        startingStr += playerData.web_name;
        if (picks[pick_i].is_captain == true) {
          startingStr += " (C)";
        }
        if (picks[pick_i].is_vice_captain == true) {
          startingStr += " (vc)";
        }
      }
      else {
        if (benchStr != "") {
          benchStr += ", ";
        }
        benchStr += playerData.web_name;
      }
      is_captain = false;
      is_vice = false;
      if (picks[pick_i].is_captain == true) {
        captain_id = picks[pick_i].element;
        captain = playerData.web_name;
        is_captain = true;
        captain_points = playerData.event_points;
      }
      if (picks[pick_i].is_vice_captain == true) {
        vice_captain_id = picks[pick_i].element;
        vice_captain = playerData.web_name;
        is_vice = true;
        vice_points = playerData.event_points;
      }
      if (picks[pick_i].position < 12) {
        tmpteamid = playerData.team_code;
        tmpfixtureid = teamsObj[tmpteamid].current_event_fixture[0].id;
        if (fixturesObj[tmpfixtureid].started == true) {
          hasPlayed = false;
          if(livePlayersObj[playerData.id].stats.minutes > 0) {
            hasPlayed = true
          };
          if (hasPlayed) {
            if (playedstr != "") {
              playedstr += "\n";
            }
            playednum++;
            playedstr += playerData.web_name
          }
          else {
            if (didntplaystr != "") {
              didntplaystr += "\n";
            }
            didntplaynum++;
            didntplaystr += playerData.web_name;
            if (is_captain) {
              captain_dnp = true;
            }
          }
        }
        else {
          if (toplaystr != "") {
            toplaystr += "\n";
          }
          toplaynum++;
          toplaystr += playerData.web_name
        }
      }

    }

    squadStr = "<div style='margin-left: 10px'>Starting XI: " + startingStr + "<br />Subs: " + benchStr + '</div>';
    rowstr = "";
    current_points = teamObj.entry_history.total_points;
    week_points = teamObj.entry_history.points;

    live_total = (current_points - week_points) + live_score;

    h2hpos = 0;

    if (config_values["teamval"] == 1) {
      rowstr += "<td id='teamval" + team_id + "' align='right' nowrap>" + value + "</td>";
    }
    if (config_values["bankval"] == 1) {
      rowstr += "<td id='bankval" + team_id + "' align='right' nowrap>" + bank + "</td>";
    }
    if (config_values["totalval"] == 1) {
      rowstr += "<td id='totalval" + team_id + "' align='right' nowrap>" + total_value + "</td>";
    }
    if (config_values["tt"] == 1) {
      rowstr += "<td id='tt" + team_id + "'>" + total_transfers + "</td>";
    }
    if (config_values["gwt"] == 1) {
      rowstr += "<td id='gwt" + team_id + "'>" + gw_transfers + "</td>";
    }
    if (config_values["hitpts"] == 1) {
      rowstr += "<td id='hitpts" + team_id + "'>" + transfers_hit + "</td>";
    }
    if (config_values["wc"] == 1) {
      rowstr += "<td id='wc" + team_id + "' align='center'>&nbsp;</td>";
    }
    if (config_values["chips"] == 1) {
      rowstr += "<td id='chips" + team_id + "' align='center'></td>";
    }
    if (config_values["captain"] == 1) {
      rowstr += "<td title='" + vice_captain + " (vc)' nowrap>" + captain + "</td>";
    }
    if (config_values["h2h"] == 1) {
      rowstr += "<td><span style='display: none'>-" + h2hpos + "</span>" + h2hpos + "</td>";
    }
    if (config_values["livepoints"] == 1) {
      rowstr += "<td>" + live_score + "</td>";
    }
    if (config_values["livetotal"] == 1) {
      rowstr += "<td id='livetotal" + team_id + "' nowrap align='right'>" + numberWithCommas(live_total) + "</td>";
    }
    if (config_values["played"] == 1) {
      rowstr += "<td title='" + playedstr + "' nowrap>" + playednum + "</td>";
      rowstr += "<td title='" + toplaystr + "' nowrap>" + toplaynum + "</td>";
      rowstr += "<td title='" + didntplaystr + "' nowrap>" + didntplaynum + "</td>";
    }
    tmpRow = document.getElementById("row" + team_id);
    tmpRow.innerHTML = tmpRow.innerHTML + rowstr;
    tmpCells = tmpRow.getElementsByTagName("td");
    teamDiv = "<div id='teamdiv_" + team_id + "' style='display: none; position: absolute; overflow: auto; height: 100%; width: 1000px; left: 0; background: white; color: black; line-height: 25px; font-size: 11px; top: 0;'>" + squadStr + "</div>";
    tmpCells[2].style.position = "relative";
    tmpCells[2].innerHTML = tmpCells[2].innerHTML + teamDiv;
    tmpCells[0].innerHTML = tmpCells[0].innerHTML + "<abbr onclick=\"tmpdiv=document.getElementById('teamdiv_" + team_id + "');if(tmpdiv.style.display=='block'){tmpdiv.style.display='none'}else{tmpdiv.style.display='block'}\" title='Toggle Team'>T</abbr>";
  }

  url = "https://fantasy.premierleague.com/drf/entry/" + team_id + "/history";
  var xmlHttp2 = GetXmlHttpObject();
  xmlHttp2.onreadystatechange = stateChangedEntry;
  xmlHttp2.open("GET", url, true);
  xmlHttp2.send(null);

}