jpk100 / ShowTeamDetails

// ==UserScript==
// @name        ShowTeamDetails
// @namespace   MultiDreamTeams
// @include     https://www.dreamteamfc.com/*
// @version     2.01
// @require     https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
// @require     http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js
// @downloadURL https://openuserjs.org/install/jpk100/ShowTeamDetails.user.js
// @updateURL   https://openuserjs.org/install/jpk100/ShowTeamDetails.user.js
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_addStyle
// ==/UserScript==
var liveStatus = 'off'
var transferMode = 'off'
var stylc = 'font: 12px "Aptifer-Medium" !important; height:15px; padding: 1px 2px; text-align:center'
var styl = 'font: 12px "Aptifer-Medium" !important; height:15px; padding: 1px 2px; '
var stylu = 'font: 12px "Aptifer-Medium" !important; height:15px; padding: 1px 2px;text-decoration: underline;text-align:center '
var stylq = 'font: 12px \'Aptifer-Medium\' !important; height:18px; padding:0px;text-indent:0px ;border-radius:0px;border:0px;'
var stIsIE = /*@cc_on!@*/
false;
sorttable = {
  init: function () {
    // quit if this function has already been called
    if (arguments.callee.done) return;
    // flag this function so we don't do the same thing twice
    arguments.callee.done = true;
    // kill the timer
    if (_timer) clearInterval(_timer);
    if (!document.createElement || !document.getElementsByTagName) return;
    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
    forEach(document.getElementsByTagName('table'), function (table) {
      if (table.className.search(/\bsortable\b/) != - 1) {
        sorttable.makeSortable(table);
      }
    });
  },
  makeSortable: function (table) {
    if (table.getElementsByTagName('thead').length == 0) {
      // table doesn't have a tHead. Since it should have, create one and
      // put the first table row in it.
      the = document.createElement('thead');
      the.appendChild(table.rows[0]);
      table.insertBefore(the, table.firstChild);
    } // Safari doesn't support table.tHead, sigh

    if (table.tHead == null) table.tHead = table.getElementsByTagName('thead') [0];
    if (table.tHead.rows.length != 1) return; // can't cope with two header rows
    // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
    // "total" rows, for example). This is B&R, since what you're supposed
    // to do is put them in a tfoot. So, if there are sortbottom rows,
    // for backwards compatibility, move them to tfoot (creating it if needed).
    sortbottomrows = [
    ];
    for (var i = 0; i < table.rows.length; i++) {
      if (table.rows[i].className.search(/\bsortbottom\b/) != - 1) {
        sortbottomrows[sortbottomrows.length] = table.rows[i];
      }
    }
    if (sortbottomrows) {
      if (table.tFoot == null) {
        // table doesn't have a tfoot. Create one.
        tfo = document.createElement('tfoot');
        table.appendChild(tfo);
      }
      for (var i = 0; i < sortbottomrows.length; i++) {
        tfo.appendChild(sortbottomrows[i]);
      }
      delete sortbottomrows;
    } // work through each column and calculate its type

    headrow = table.tHead.rows[0].cells;
    for (var i = 0; i < headrow.length; i++) {
      // manually override the type with a sorttable_type attribute
      if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
        if (mtch) {
          override = mtch[1];
        }
        if (mtch && typeof sorttable['sort_' + override] == 'function') {
          headrow[i].sorttable_sortfunction = sorttable['sort_' + override];
        } else {
          headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);
        } // make it clickable to sort

        headrow[i].sorttable_columnindex = i;
        headrow[i].sorttable_tbody = table.tBodies[0];
        dean_addEvent(headrow[i], 'click', sorttable.innerSortFunction = function (e) {
          if (this.className.search(/\bsorttable_sorted\b/) != - 1) {
            // if we're already sorted by this column, just
            // reverse the table, which is quicker
            sorttable.reverse(this.sorttable_tbody);
            this.className = this.className.replace('sorttable_sorted', 'sorttable_sorted_reverse');
            this.removeChild(document.getElementById('sorttable_sortfwdind'));
            sortrevind = document.createElement('span');
            sortrevind.id = 'sorttable_sortrevind';
            sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
            this.appendChild(sortrevind);
            return;
          }
          if (this.className.search(/\bsorttable_sorted_reverse\b/) != - 1) {
            // if we're already sorted by this column in reverse, just
            // re-reverse the table, which is quicker
            sorttable.reverse(this.sorttable_tbody);
            this.className = this.className.replace('sorttable_sorted_reverse', 'sorttable_sorted');
            this.removeChild(document.getElementById('sorttable_sortrevind'));
            sortfwdind = document.createElement('span');
            sortfwdind.id = 'sorttable_sortfwdind';
            sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
            this.appendChild(sortfwdind);
            return;
          } // remove sorttable_sorted classes

          theadrow = this.parentNode;
          forEach(theadrow.childNodes, function (cell) {
            if (cell.nodeType == 1) { // an element
              cell.className = cell.className.replace('sorttable_sorted_reverse', '');
              cell.className = cell.className.replace('sorttable_sorted', '');
            }
          });
          sortfwdind = document.getElementById('sorttable_sortfwdind');
          if (sortfwdind) {
            sortfwdind.parentNode.removeChild(sortfwdind);
          }
          sortrevind = document.getElementById('sorttable_sortrevind');
          if (sortrevind) {
            sortrevind.parentNode.removeChild(sortrevind);
          }
          this.className += ' sorttable_sorted';
          sortfwdind = document.createElement('span');
          sortfwdind.id = 'sorttable_sortfwdind';
          sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
          this.appendChild(sortfwdind);
          // build an array to sort. This is a Schwartzian transform thing,
          // i.e., we "decorate" each row with the actual sort key,
          // sort based on the sort keys, and then put the rows back in order
          // which is a lot faster because you only do getInnerText once per row
          row_array = [
          ];
          col = this.sorttable_columnindex;
          rows = this.sorttable_tbody.rows;
          for (var j = 0; j < rows.length; j++) {
            row_array[row_array.length] = [
              sorttable.getInnerText(rows[j].cells[col]),
              rows[j]
            ];
          } /* If you want a stable sort, uncomment the following line */
          //sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
          /* and comment out this one */

          row_array.sort(this.sorttable_sortfunction);
          tb = this.sorttable_tbody;
          for (var j = 0; j < row_array.length; j++) {
            tb.appendChild(row_array[j][1]);
          }
          delete row_array;
        });
      }
    }
  },
  guessType: function (table, column) {
    // guess the type of a column based on its first non-blank row
    sortfn = sorttable.sort_alpha;
    for (var i = 0; i < table.tBodies[0].rows.length; i++) {
      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
      if (text != '') {
        if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {
          return sorttable.sort_numeric;
        } // check for a date: dd/mm/yyyy or dd/mm/yy
        // can have / or . or - as separator
        // can be mm/dd as well

        possdate = text.match(sorttable.DATE_RE)
        if (possdate) {
          // looks like a date
          first = parseInt(possdate[1]);
          second = parseInt(possdate[2]);
          if (first > 12) {
            // definitely dd/mm
            return sorttable.sort_ddmm;
          } else if (second > 12) {
            return sorttable.sort_mmdd;
          } else {
            // looks like a date, but we can't tell which, so assume
            // that it's dd/mm (English imperialism!) and keep looking
            sortfn = sorttable.sort_ddmm;
          }
        }
      }
    }
    return sortfn;
  },
  getInnerText: function (node) {
    // gets the text we want to use for sorting for a cell.
    // strips leading and trailing whitespace.
    // this is *not* a generic getInnerText function; it's special to sorttable.
    // for example, you can override the cell text with a customkey attribute.
    // it also gets .value for <input> fields.
    if (!node) return '';
    hasInputs = (typeof node.getElementsByTagName == 'function') && node.getElementsByTagName('input').length;
    if (node.getAttribute('sorttable_customkey') != null) {
      return node.getAttribute('sorttable_customkey');
    } 
    else if (typeof node.textContent != 'undefined' && !hasInputs) {
      return node.textContent.replace(/^\s+|\s+$/g, '');
    } 
    else if (typeof node.innerText != 'undefined' && !hasInputs) {
      return node.innerText.replace(/^\s+|\s+$/g, '');
    } 
    else if (typeof node.text != 'undefined' && !hasInputs) {
      return node.text.replace(/^\s+|\s+$/g, '');
    } 
    else {
      switch (node.nodeType) {
        case 3:
          if (node.nodeName.toLowerCase() == 'input') {
            return node.value.replace(/^\s+|\s+$/g, '');
          }
        case 4:
          return node.nodeValue.replace(/^\s+|\s+$/g, '');
          break;
        case 1:
        case 11:
          var innerText = '';
          for (var i = 0; i < node.childNodes.length; i++) {
            innerText += sorttable.getInnerText(node.childNodes[i]);
          }
          return innerText.replace(/^\s+|\s+$/g, '');
          break;
        default:
          return '';
      }
    }
  },
  reverse: function (tbody) {
    // reverse the rows in a tbody
    newrows = [
    ];
    for (var i = 0; i < tbody.rows.length; i++) {
      newrows[newrows.length] = tbody.rows[i];
    }
    for (var i = newrows.length - 1; i >= 0; i--) {
      tbody.appendChild(newrows[i]);
    }
    delete newrows;
  },
  /* sort functions
     each sort function takes two parameters, a and b
     you are comparing a[0] and b[0] */
  sort_numeric: function (a, b) {
    aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));
    if (isNaN(bb)) bb = 0;
    return bb - aa;
  },
  sort_alpha: function (a, b) {
    if (a[0] == b[0]) return 0;
    if (a[0] < b[0]) return - 1;
    return 1;
  },
  sort_ddmm: function (a, b) {
    mtch = a[0].match(sorttable.DATE_RE);
    y = mtch[3];
    m = mtch[2];
    d = mtch[1];
    if (m.length == 1) m = '0' + m;
    if (d.length == 1) d = '0' + d;
    dt1 = y + m + d;
    mtch = b[0].match(sorttable.DATE_RE);
    y = mtch[3];
    m = mtch[2];
    d = mtch[1];
    if (m.length == 1) m = '0' + m;
    if (d.length == 1) d = '0' + d;
    dt2 = y + m + d;
    if (dt1 == dt2) return 0;
    if (dt1 < dt2) return - 1;
    return 1;
  },
  sort_mmdd: function (a, b) {
    mtch = a[0].match(sorttable.DATE_RE);
    y = mtch[3];
    d = mtch[2];
    m = mtch[1];
    if (m.length == 1) m = '0' + m;
    if (d.length == 1) d = '0' + d;
    dt1 = y + m + d;
    mtch = b[0].match(sorttable.DATE_RE);
    y = mtch[3];
    d = mtch[2];
    m = mtch[1];
    if (m.length == 1) m = '0' + m;
    if (d.length == 1) d = '0' + d;
    dt2 = y + m + d;
    if (dt1 == dt2) return 0;
    if (dt1 < dt2) return - 1;
    return 1;
  },
  shaker_sort: function (list, comp_func) {
    // A stable sort function to allow multi-level sorting of data
    // see: http://en.wikipedia.org/wiki/Cocktail_sort
    // thanks to Joseph Nahmias
    var b = 0;
    var t = list.length - 1;
    var swap = true;
    while (swap) {
      swap = false;
      for (var i = b; i < t; ++i) {
        if (comp_func(list[i], list[i + 1]) > 0) {
          var q = list[i];
          list[i] = list[i + 1];
          list[i + 1] = q;
          swap = true;
        }
      } // for

      t--;
      if (!swap) break;
      for (var i = t; i > b; --i) {
        if (comp_func(list[i], list[i - 1]) < 0) {
          var q = list[i];
          list[i] = list[i - 1];
          list[i - 1] = q;
          swap = true;
        }
      } // for

      b++;
    } // while(swap)

  }
} /* ******************************************************************
   Supporting functions: bundled here to avoid depending on a library
   ****************************************************************** */
// Dean Edwards/Matthias Miller/John Resig
/* for Mozilla/Opera9 */

if (document.addEventListener) {
  document.addEventListener('DOMContentLoaded', sorttable.init, false);
} /* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
    var script = document.getElementById("__ie_onload");
    script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            sorttable.init(); // call the onload handler
        }
    };
/*@end @*/
/* for Safari */

if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function () {
    if (/loaded|complete/.test(document.readyState)) {
      sorttable.init(); // call the onload handler
    }
  }, 10);
} /* for other browsers */

window.onload = sorttable.init;
main()
function main() {
  var eur = '';
  if (location.pathname.split('/') [1] === 'europe') {
    eur = '/europe'
  }
  if (location.pathname.split('/') [1] === 'intl') {
    eur = '/intl'
  } //loadthe players

  var jsonP = (function () {
    var jsonP = null;
    $.ajax({
      'async': false,
      'global': false,
      'url': eur + '/json/players',
      'dataType': 'json',
      'success': function (data) {
        jsonP = data;
      }
    });
    return jsonP;
  }) ();
  function oPlayer() {
    this.pid = '';
    this.name = '';
    this.team = 'UKN';
    this.value = 0;
    this.group = 'G';
    this.points = 0;
    this.pickedk = 0;
    this.status = 'RSSUSPEN';
    this.display = '';
    this.shortname = 'N';
    this.shortnamec = 'N';
    this.suspended = 'N';
  }
  var oPlayers = new Object;
  var GKs = new Object;
  var DEFs = new Object;
  var MIDs = new Object;
  var FWDs = new Object;
  /* sets up or updates the player information */
  json_players = jsonP.players;
  json_team = jsonP.team;
  json_teamname = jsonP.teamname;
  json_group = jsonP.group;
  var iGroupLen = json_group.length;
  while (iGroupLen--) {
    var sGroup = json_group[iGroupLen];
    var plaGroup = json_players[iGroupLen];
    var iPlaLen = plaGroup.length;
    while (iPlaLen--) {
      var currPlayer = plaGroup[iPlaLen];
      var newPlayer = new oPlayer;
      var season = currPlayer[0]
      newPlayer.pid = season[0];
      newPlayer.name = season[1];
      newPlayer.team = json_team[season[2]];
      newPlayer.teamname = json_teamname[season[2]];
      newPlayer.value10 = (season[3] )
      newPlayer.value = (season[3] / 10).toFixed(1);
      newPlayer.score = season[4];
      newPlayer.status = season[5];
      newPlayer.shortname = season[7].split(',') [0];
      if (newPlayer.status != 'A')
      newPlayer.shortnamec = '<font color="red">' + newPlayer.shortname + '</font>';
      if (newPlayer.status == 'E')
      newPlayer.shortnamec = '<font color="blood red">' + newPlayer.shortname + '</font>';
      newPlayer.points = season[8];
      oPlayers[season[0]] = newPlayer;
      if (sGroup == 'S')
      FWDs[season[0]] = newPlayer;
      if (sGroup == 'M')
      MIDs[season[0]] = newPlayer;
      if (sGroup == 'D')
      DEFs[season[0]] = newPlayer;
      if (sGroup == 'G')
      GKs[season[0]] = newPlayer;
    }
  } //create a table 

  var table = $('<table></table>').attr('class', 'sortable').attr('id', 'detailTable')
  var thead = $('<thead></thead>')
  $('<th></th>').attr('style', stylc).text('ID').appendTo(thead);
  $('<th></th>').attr('style', stylc).text('NAME').appendTo(thead);
  $('<th></th>').attr('style', stylc).text('Transfer').appendTo(thead);
  var j = 0
  var plyrs = ''
  while (j <= 10) {
    $('<th></th>').text(j + 1).attr('style', styl).appendTo(thead);
    j++;
  } // $('<th></th>').attr('style', stylc).text('TEAM').appendTo(thead);

  $('<th></th>').attr('style', stylc).text('Val').appendTo(thead);
  $('<th></th>').attr('style', stylc).text('Overall Points').appendTo(thead);
  $('<th></th>').attr('style', stylc).text('Overall Position').appendTo(thead);
  if (eur == '') {
    $('<th></th>').attr('style', stylc).text('Month Points').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('Month Position').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('Week Points').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('Week Position').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('Emergency Used ').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('Transfers Made').appendTo(thead);
  }
  if (eur == '/europe') {
    $('<th></th>').attr('style', stylc).text('P1 Points').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P1 Position').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P2 Points').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P2 Position').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P3 Points').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P3 Position').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('Emergency Used ').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('Transfers Made').appendTo(thead);
  }
  if (eur == '/intl') {
    $('<th></th>').attr('style', stylc).text('P1 Points').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P1 Position').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P2 Points').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P2 Position').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P3 Points').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P3 Position').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P4 Points').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P4 Position').appendTo(thead);
    $('<th></th>').attr('style', stylc).text('P Transfers Left ').appendTo(thead);
  }
  table.append(thead);
  $('#new_sect').remove()
  var newsect = $('<section></section>').attr('id', 'new_sect')
  newsect.append(table)
  var TeamList //load players
  //if on season page then load teams
  //load teams
  //and add rows to table
  if (window.location.pathname === '/season/' || window.location.pathname === '/season' || window.location.pathname === '/europe/' || window.location.pathname === '/europe' || window.location.pathname === '/intl/' || window.location.pathname === '/intl')
  {
    //remove banenr
    $('#billboard').remove()
    $('.mainImg').remove()
    $('.mainContent .site-container').prepend(newsect)
    $.getJSON(eur + '/json/team/load/', function (data) {
      $.each(data.TEAM, function (i, field) {
        $.getJSON(eur + '/json/team/load/' + i, function (data) {
          var table = $('#detailTable')
          var currTeam = data.TEAM[i]
          var row = $('<tr id="row_' + i + '"></tr>').attr('style', styl);
          $('<td></td>').html('<a href=https://www.dreamteamfc.com' + eur + '/team/view/' + i + '>' + i + '</a>').attr('style', stylc).appendTo(row);
          $('<td></td>').html(data.TEAM[i].NAME).attr('style', styl).appendTo(row);
          var sdiv = $('<td class="sdiv" id="save_' + i + '"></td>')
          var tranlink = i
          $(sdiv).html('Transfer').attr('style', stylu).appendTo(row);
          /*
        
        */
          var j = 0
          var plyrs = ''
          var plyrsid = ''
          if (currTeam.PENDING === undefined)
          {
            while (j <= 10)
            {
              //plyrs += oPlayers[currTeam.PLAYERS[j]].shortname + ', '
              plyrs = oPlayers[currTeam.PLAYERS[j]].shortname
           
           if (oPlayers[currTeam.PLAYERS[j]].status!='A')
              $('<td id="tdrow_' + i + '_pos_' + j + '"></td>').html(plyrs).attr('style', styl).css('color', 'red').appendTo(row);
              else
               $('<td id="tdrow_' + i + '_pos_' + j + '"></td>').html(plyrs).attr('style', styl).css('color', 'black').appendTo(row);
      
              j++
            } // $('<td></td>').html(plyrs).attr('style', styl).appendTo(row);

          } 
          else
          {
            //go through pending and players and work out which are in and which are out
            var tranin = [
              '0',
              '0',
              '0'
            ]
            var tranout = [
              '0',
              '0',
              '0'
            ]
            j = 0
            var countTran = 0
            var found = 0
            var k = 0 //get the players out
            while (k <= 10) {
              found = 0
              while (j <= 10) {
                if (currTeam.PLAYERS[k] == currTeam.PENDING.PLAYERS[j]) found = 1
                j++
              }
              j = 0
              if (found == 0)
              {
                tranout[countTran] = currTeam.PLAYERS[k];
                countTran++;
              }
              k++
            }
            k = 0
            j = 0
            countTran = 0 //get the players in
            while (k <= 10) {
              found = 0
              while (j <= 10) {
                if (currTeam.PENDING.PLAYERS[k] == currTeam.PLAYERS[j]) found = 1
                j++
              }
              j = 0
              if (found == 0)
              {
                tranin[countTran] = currTeam.PENDING.PLAYERS[k];
                countTran++;
              }
              k++
            }
            k = 0
            countTran = 0
            plyrs = ''
            j = 0
            while (j <= 10)
            {
              if (currTeam.PLAYERS[j] == tranout[countTran])
              {
                plyrs += '<i>' + oPlayers[currTeam.PLAYERS[j]].shortname + '</i>' +
                '<img src=\'https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Go-green.svg/12px-Go-green.svg.png\'/>' +
                '<b>' + oPlayers[tranin[countTran]].shortname + '</b>,'
                countTran++
              } 
              else
              {
                plyrs += oPlayers[currTeam.PLAYERS[j]].shortname + ', '
              }
              j++
            }
            $('<td></td>').html(plyrs).attr('style', styl).appendTo(row);
          }
          $('<td id="teamval_' + i +'"></td>').html(data.TEAM[i].VALUE).attr('style', stylc).appendTo(row);
          $('<td></td>').html(data.TEAM[i].SCORES.TOTALPOINTS).attr('style', stylc).appendTo(row);
          $('<td></td>').html(data.TEAM[i].SCORES.POSITION).attr('style', stylc).appendTo(row);
          if (eur == '') {
            $('<td></td>').html(data.TEAM[i].SCORES.MONTHPOINTS).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.MONTHPOS).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.WEEKSPOINTS).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.WEEKSPOS).attr('style', stylc).appendTo(row);
          }
          if (eur == '/europe') {
            $('<td></td>').html(data.TEAM[i].SCORES.P1POINTS).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P1POSITION).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P2POINTS).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P2POSITION).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P3POINTS).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P3POSITION).attr('style', stylc).appendTo(row);
          }
          if (eur == '/intl') {
            $('<td></td>').html(data.TEAM[i].SCORES.P1POINTS).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P1POSITION).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P2POINTS).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P2POSITION).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P3POINTS).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P3POSITION).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P4POINTS).attr('style', stylc).appendTo(row);
            $('<td></td>').html(data.TEAM[i].SCORES.P4POSITION).attr('style', stylc).appendTo(row);
            var tdiv = $('<td class="tdiv" id="team_' + i + '"></td>')            /*       $(tdiv).click(function () {
              var tranlink = $(this).attr('id').replace('team_', '')
              var url = eur + '/team/view/' + tranlink
              $.ajax({
                url: url,
                dataType: 'html',
                success: function (response) {
                  var nxturl = eur + '/team/transfer'
                  window.location = nxturl;
                  // callgetTran(nxturl, th);
                }
              });
            });*/
            $(tdiv).html(data.TEAM[i].TRANSFERS.TRANSFER).attr('style', stylu).appendTo(row);
          } /*
          if (data.TEAM[i].EMERGENCY == '0')
          $('<td></td>').html('<img src=\'http://upload.wikimedia.org/wikipedia/commons/thumb/0/03/Green_check.svg/13px-Green_check.svg.png\'/>').attr('style', stylc).appendTo(row);
           else
          $('<td></td>').html('-').attr('style', stylc).appendTo(row);
          //$('<td></td>').html('<img src=\'https://upload.wikimedia.org/wikipedia/commons/2/28/X_mark_18x18_02.gif\'/>').appendTo(row);
          if (data.TEAM[i].PENDING === undefined)
          $('<td></td>').html('-').attr('style', stylc).appendTo(row);
           else
          $('<td></td>').html('<img src=\'http://upload.wikimedia.org/wikipedia/commons/thumb/0/03/Green_check.svg/13px-Green_check.svg.png\'/>').attr('style', stylc).appendTo(row);
         */

          table.append(row)
        })
      }) //each team
      //add click event to table for open transfer page
      $(table).on('click', '.tdiv', function (e) {
        var tranlink = $(this).attr('id').replace('team_', '')
        var url = eur + '/team/view/' + tranlink
        $.ajax({
          url: url,
          dataType: 'html',
          success: function (response) {
            var nxturl = eur + '/team/transfer'
         /*   var win = window.open('nxturl', '_blank');
                if (win) {
                    //Browser has allowed it to be opened
                    win.focus();
                } else {
                    //Browser has blocked it
                    alert('Please allow popups for this website');
                }
            */
           window.location = nxturl;
            // callgetTran(nxturl, th);
          }
        });
      });
      //add click event to table for on page transfer logic
      $(table).on('click', '.sdiv', function (e) {
        var j = 0;
        //if in transfer mode then carry out transfer
        if ($(this).html() == 'Save')
        {
          $(this).html('Transfer')
          var tranlink = $(this).attr('id').replace('save_', '')
          var teamstring = '?'
          var j = 1
          while (j <= 11)
          {
            var oj = j - 1
            teamstring += 'p' + j + '=' + $('#select_' + tranlink + '_pos_' + (oj) + ' option:selected').val()
            if (j != 11)
            teamstring += '&'
            j++
          } // $('<td></td>').html(plyrs).attr('style', styl).appendTo(row);

          var url = eur + '/team/view/' + tranlink
          $.ajax({
            url: url,
            dataType: 'html',
            success: function (response) {
              var nxturl = eur + '/json/team/modify/' + teamstring
              $.ajax({
                url: nxturl,
                dataType: 'json',
                success: function (response) {
              
                  if(response.error==undefined)
                    alert('Transfer complete')
                  else
                    {
                    alert(response.error)
                    //revert team
                    
                    }
                  //https://www.dreamteamfc.com/intl/json/team/modify/?p1=1007&p2=2028&p3=2031&p4=2037&p5=2088&p6=3029&p7=3056&p8=3113&p9=4018&p10=4027&p11=4071
                }
              });
            }
          }
          )
          var j = 0;
          while (j <= 10)
          {
            var plyrs = $('#select_' + i + '_pos_' + (j) + ' option:selected').text()
            var id = $('#select_' + i + '_pos_' + (j) + ' option:selected').val()
            
             if (oPlayers[id].status!='A')
              $('#tdrow_' + i + '_pos_' + j).html(plyrs).css('color', 'red')
              else
             $('#tdrow_' + i + '_pos_' + j).html(plyrs).css('color', 'black')
             
        
            j++;
          }
        } 
        else //otherwise set up transfer on the row
        {
          j = 0;
          $(this).html('Save')
          //get latest team
          
          i = $(this).attr('id').replace('save_', '')
          
             $.getJSON(eur + '/json/team/load/' + i, function (data) {
          
                while (j <= 10)
                {
                  var cTeam = data.TEAM[i].TEAMSTRING
                  var plyrsid = cTeam.substring(j * 4, (j * 4) + 4)
                  var plyrs = oPlayers[plyrsid].shortname
                   var playerd = '  <select style="' + stylq + '" name="playerselect" class="playerselector" id="select_' + i + '_pos_' + j + '">  <option value="' + plyrsid + '">' + plyrs + '</option>   '
                  if (j == 0) {
                    $.each(GKs, (function (e) {
                      playerd += ' <option value="' + this.pid + '">' + this.shortname + '</option>   '
                    }));
                  }
                  if (j >= 1 && j <= 4) {
                    $.each(DEFs, (function (e) {
                      playerd += ' <option value="' + this.pid + '">' + this.shortname + '</option>   '
                    }));
                  }
                  if (j >= 5 && j <= 7) {
                    $.each(MIDs, (function (e) {
                      playerd += ' <option value="' + this.pid + '">' + this.shortname + '</option>   '
                    }));
                  }
                  if (j == 8) {
                    $.each(MIDs, (function (e) {
                      playerd += ' <option value="' + this.pid + '">' + this.shortname + '</option>   '
                    }));
                    $.each(FWDs, (function (e) {
                      playerd += ' <option value="' + this.pid + '">' + this.shortname + '</option>   '
                    }));
                  }
                  if (j > 8) {
                    $.each(FWDs, (function (e) {
                      playerd += ' <option value="' + this.pid + '">' + this.shortname + '</option>   '
                    }));
                  } // console.log(GKs)

                  playerd += '</select>' //   alert($('#tdrow_' + tranlink + '_pos_' + j ).html())
                  $('#tdrow_' + i + '_pos_' + j).html(playerd)
                   
                  
                  
                  j++;
                }//while
                $( ".playerselector" ).change(function() {
                       //go through all selects and add up value
                       var teamval=0;
                        var tranlink = $(this).parent().parent().attr('id').replace('row_', '')
                        var j = 1
                        while (j <= 11)
                        {
                          var oj = j - 1
                          teamval +=  oPlayers[$('#select_' + tranlink + '_pos_' + (oj) + ' option:selected').val()].value10
                          
                          j++
                        }
                       //alert(teamval/10 );
                       //update val column
                  if(teamval>500)
                   $('#teamval_' + tranlink ).html(teamval/10).css('color', 'red');
                     else
                      $('#teamval_' + tranlink ).html(teamval/10).css('color', 'black');
                 
                  
                    });
             });//getjson
          //set up refresh score events for each dropdown
        
        }
      });
    }) // load all teams
    $.getJSON('/intl/json/livescores', function (data) {
      // Looks for the error message;
      if (data.error) {
        alert(data.error);
        return;
      }
      var json_playerspts = data.players;
      var json_breakdown = data.breakdown;
      var json_gamestatus = data.gamestatus;
      var json_matches = data.matches;
      liveStatus = 'OFF';
      if (json_gamestatus !== undefined && json_gamestatus.length !== 0) {
        if (json_gamestatus[0].state === 'ON') {
          if (json_playerspts !== undefined && json_playerspts.length !== 0) {
            // display a table with live scores on it
            var whichtable
            var livetable = $('<table class="table table-condensed"></table>').attr('id', 'collapseme')
            var livetablehead = $('<thead></thead>')
            $('<th></th>').text('Live Scores').appendTo(livetablehead);
            livetable.append(livetablehead);
            //   var menu = '<button type="button" class="btn" data-toggle="collapse" data-target="#collapseme"> Click to expand </button> '
            //              livetable.append(menu);
            $('#new_livesect').remove()
            var newlivesect = $('<section></section>').attr('id', 'new_livesect')
            newlivesect.append(livetable)
            $('.mainContent .site-container').prepend(newlivesect)
            $.each(json_matches, function (key, val) {
              var lrow = $('<tr></tr>') //.attr('style', styl);
              //add a new table per match
              var matchtable = $('<table></table>').attr('id', 'matchTable' + val[0] + val[1]).attr('class', 'table')
              var matchtablehead = $('<thead></thead>')
              $('<th></th>').attr('style', styl).text(val[0] + ' ' + val[2]).appendTo(matchtablehead);
              $('<th></th>').attr('style', styl).text(val[1] + ' ' + val[3]).appendTo(matchtablehead);
              matchtable.append(matchtablehead);
              var lcol = $('<td></td>')
              var lcol2 = $('<td></td>')
              var ltab1 = $('<table></table>').attr('id', 'matchTable' + val[0].replace(/\s+/g, '')).attr('class', 'table')
              $('<th></th>').attr('style', styl).text('Name').appendTo(ltab1);
              $('<th></th>').attr('style', styl).text('Rating').appendTo(ltab1);
              $('<th></th>').attr('style', styl).text('Points').appendTo(ltab1);
              var ltab2 = $('<table></table>').attr('id', 'matchTable' + val[1].replace(/\s+/g, '')).attr('class', 'table')
              $('<th></th>').attr('style', styl).text('Name').appendTo(ltab2);
              $('<th></th>').attr('style', styl).text('Rating').appendTo(ltab2);
              $('<th></th>').attr('style', styl).text('Points').appendTo(ltab2);
              lcol.append(ltab1)
              lcol2.append(ltab2)
              lrow.append(lcol)
              lrow.append(lcol2)
              matchtable.append(lrow)
              newlivesect.append(matchtable)
              matchtable.append(lrow)
              $.each(json_playerspts, function (key, val1) {
                var lrow = $('<tr></tr>').attr('style', styl);
                //add 2 cols
                // add 2 cols with a table in each
                var matchtable1 = $('#matchTable' + val[0].replace(/\s+/g, ''))
                var matchtable2 = $('#matchTable' + val[1].replace(/\s+/g, ''))
                console.log(val[0])
                if (oPlayers[val1[0]].teamname == val[0])
                {
                  //  $('<td></td>').html(oPlayers[val1[0]].shortname +' ' +     val1[15] + ', ' +    val1[1]      ).attr('style', styl).appendTo(lrow);
                  $('<td></td>').html(oPlayers[val1[0]].shortname).attr('style', styl).appendTo(lrow);
                  $('<td></td>').html(val1[15]).attr('style', styl).appendTo(lrow);
                  $('<td></td>').html(val1[1]).attr('style', styl).appendTo(lrow);
                  matchtable1.append(lrow)
                }
                console.log(val[1])
                if (oPlayers[val1[0]].teamname == val[1])
                {
                  $('<td></td>').html(oPlayers[val1[0]].shortname).attr('style', styl).appendTo(lrow);
                  $('<td></td>').html(val1[15]).attr('style', styl).appendTo(lrow);
                  $('<td></td>').html(val1[1]).attr('style', styl).appendTo(lrow);
                  matchtable2.append(lrow)
                }
              });
              $.each(json_breakdown, function (key, val1) {
                var matchtable1 = $('#matchTable' + val[0].replace(/\s+/g, ''))
                var matchtable2 = $('#matchTable' + val[1].replace(/\s+/g, ''))
                if (oPlayers[val1[0]].teamname == val[0])
                {
                  // $(matchtable1).find('td').eq(3).append($('<div></div>').html(val1[5] + ', ' + oPlayers[val1[0]].shortname + ', ' +
                  // val1[2]  ).attr('style', styl))
                  var lrow = $('<tr></tr>').attr('style', styl);
                  $('<td></td>').html(val1[5] + ', ' + oPlayers[val1[0]].shortname + ', ' +
                  val1[2]
                  ).attr('style', styl).appendTo(lrow);
                  matchtable1.append(lrow)
                }
                if (oPlayers[val1[0]].teamname == val[1])
                {
                  var lrow = $('<tr></tr>').attr('style', styl);
                  $('<td></td>').html(val1[5] + ', ' + oPlayers[val1[0]].shortname + ', ' +
                  val1[2]
                  ).attr('style', styl).appendTo(lrow);
                  matchtable2.append(lrow)
                }
              });
            });
          }
        }
      }
    })
  }
}
function addrows(Teams) {
  var table = $('#detailTable')
  table.find('tr').remove();
  console.log('teams')
  console.log(Teams)
  for (var iteam in Teams) {
    var currTeam = Teams[iteam];
    var row = $('<tr></tr>');
    console.log('Each')
    $('<td></td>').html('<a href="/team/view/' + iteam + '">' + iteam + '</a>').attr('style', styl).appendTo(row);
    table.append(row)
  }
}
function oTeam() {
  this.name = 'UKN';
  this.value = 0;
  this.points = 0;
  this.position = 0;
  this.weekpoints = 0;
  this.teampin = 0;
  this.leagues = '-';
}
function oTeamDetails() {
  this.name = 'UKN';
  this.value = 0;
  this.formation = 0;
  this.transfers = 'G';
  this.points = 0;
  this.weekpoints = 0;
}