/* Styles go here */

html, body {

  font-family: sans-serif;
}


button {

    padding: 0;

    height: 25px;

    text-align: center;
}


table .table, .matchTable {

      background: #EEEEEE;

      -moz-border-radius: 5px 5px 5px 5px;

      -webkit-border-radius: 5px 5px 5px 5px;

      -khtml-border-radius: 5px 5px 5px 5px;

      -icab-border-radius: 5px 5px 5px 5px;

      -o-border-radius: 5px 5px 5px 5px;

      border-radius: 5px 5px 5px 5px;

      border: 1px solid #9C9C9C;

      position: relative;
 }
 
 .matchTable td:nth-child(2), 
 .matchTable td:nth-child(3) {
 	border-right:0;
 }
      
table .table tr td {

        background: #F5F5F5;
 }
        table .table tr:last-child td
 {
          
border-bottom: 0;
 }
          
table .table tr:last-child td:first-child {

            -moz-border-radius: 0 0 0 5px;

            -webkit-border-radius: 0 0 0 5px;

            -khtml-border-radius: 0 0 0 5px;

            -icab-border-radius: 0 0 0 5px;

            -o-border-radius: 0 0 0 5px;

            border-radius: 0 0 0 5px;
 }
            
table .table tr:last-child td:last-child {

              -moz-border-radius: 0 0 5px 0;

              -webkit-border-radius: 0 0 5px 0;

              -khtml-border-radius: 0 0 5px 0;

              -icab-border-radius: 0 0 5px 0;

              -o-border-radius: 0 0 5px 0;

              border-radius: 0 0 5px 0; 
}
      
table .table th {

        width: 30px;
 }
    
table th:first-child {

      -moz-border-radius: 5px 0 0 0;

      -webkit-border-radius: 5px 0 0 0;

      -khtml-border-radius: 5px 0 0 0;

      -icab-border-radius: 5px 0 0 0;

      -o-border-radius: 5px 0 0 0;

      border-radius: 5px 0 0 0;
 }
      
table th:last-child {

        -moz-border-radius: 0 5px 0 0;

        -webkit-border-radius: 0 5px 0 0;

        -khtml-border-radius: 0 5px 0 0;

        -icab-border-radius: 0 5px 0 0;

        -o-border-radius: 0 5px 0 0;

        border-radius: 0 5px 0 0; 
}
        
table tr {

          position: relative; 
}


th:not(:last-child), 
td:not(:last-child) {

  border-right: 1px solid #9C9C9C; 
}

  
th {
    
border-bottom: 1px solid #000; 
}

    
#table th:first-child {

      width: 95px; 
}

      
td {

        text-align: center; 
}

        
td:first-child {

          text-align: left; 
}

          
tr td {

						border-bottom-width: 1px;
						border-bottom-style: solid;
						border-bottom-color:#9C9C9C;
}

            
#table tr:nth-child(2) td {

              border-bottom: 2px solid #21AD21; 
}

              
img {

                width: 25px;

                height: 25px; 
}
table .table tr.loss td,

.homeWin td:nth-last-child(2),

.homeWin td:nth-last-child(1),

.awayWin td:nth-last-child(5),

.awayWin td:nth-last-child(4){
  
background: #FFCCCC;

}

table .table tr.win td,

.homeWin td:nth-last-child(5),

.homeWin td:nth-last-child(4),

.awayWin td:nth-last-child(2),

.awayWin td:nth-last-child(1){

  background: #CCFFCC;

}

table .table tr.flash td{
	transition-delay: 0s;
	transition-duration: 0.5s;
	transition-property: background;
	transition-timing-function: cubic-bezier(.47,3,.47,3);
}

table tr .bothDraw td:nth-last-child(5),

table tr .bothDraw td:nth-last-child(4),

table tr .bothDraw td:nth-last-child(2),

table tr .bothDraw td:nth-last-child(1){

  background: #FFE65F;

}




                    
#groupEdit th {

                      width: auto; 
}

                      
#groupEdit tr:not(:last-child) td {

						border-bottom-width: 1px;
						border-bottom-style: solid;
						border-bottom-color:#9C9C9C;
                        border-radius: 0; 
}
                        
                        
table.groupEdit tBody tr:last-child td:last-child{

        -moz-border-radius: 0 0 5px 5px;

        -webkit-border-radius: 0 0 5px 5px;

        -khtml-border-radius: 0 05px 5px;

        -icab-border-radius: 0 0 5px 5px;

        -o-border-radius: 0 0 5px 5px;

        border-radius: 0 0 5px 5px;

        border-bottom: 0;
                        
}

                        
table .groupEdit th {

                          width: auto; 
                        
}
                        
table .groupEdit tr td{

                          height:35px;
                        
}
                          
#teamsTable tr td:hover {

                            background: #FFE65F; 
}



#container {

    width: 95%;

    max-width: 800px;

}

#container .block {

    padding:1px;

    border-bottom: 1px solid #9C9C9C;

    border-right: 1px solid #9C9C9C;

    float: left;
    width: 24.5%;

    height: 50%;

}


.export {

  border: 0;

  margin: 0;

  padding: 0;

  top: 0;

  left: 0;

  bottom: 0;

  right: 0;

  width:100%;

  height:350px;

}

.unselectable img {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: text;
    -ms-user-select: none;
    user-select: none;
    cursor: default;
}

.unselectable :not(img) {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    cursor: default;
}


tr.dragging {
	position: absolute;
	background: #E0E0E0;
	z-index: 100;
}
tr.dragging > td {
	overflow: hidden;
}

tr.spaceAbove > td
{
	border-top-width: 32px;
	border-top-style: solid;
	border-top-color: #EEEEEE;
}

tr.spaceBelow > td
{
	border-bottom-width: 32px;
	border-bottom-style: solid;
	border-bottom-color: #EEEEEE;
}

.groupButton {
	display: none;
}

.groupButton + label{
	border-width: 1px;
	border-color: #C7C7C7;
	border-style: outset;
	padding: 0 3px;
	margin: 0 2px 0 2px;
	background-color: #CECECE;
	-webkit-box-shadow: inset 0px 20px 15px -10px #F2F2F2;
	-moz-box-shadow: inset 0px 20px 15px -10px #F2F2F2;
	box-shadow: inset 0px 20px 15px -10px #F2F2F2;
}

.groupButton:checked + label{
	border-style: inset;
	background-color: #BABABA;
	box-shadow: inset 0px -16px 15px -8px #E5E5E5;
}

.groupButton.showing + label {
	background-color: #99D7FF;
	box-shadow: inset 0px -16px 15px -8px #82B7D8;
	border-color: #6C97B2;
}

.groupButton.showing:checked + label {
	background-color: #72A1BF;
	box-shadow: inset 0px -16px 15px -8px #99D7FF;
	border-color: #6C97B2;
}
var teamIcons = {
    3:{id:"3",icon:"http://implyingrigged.info/w/images/thumb/4/41/3_icon.png/25px-3_icon.png"},
    a:{id:"a",icon:"http://implyingrigged.info/w/images/3/3a/A_icon.png"},
    adv:{id:"adv",icon:"http://implyingrigged.info/w/images/thumb/1/1b/Adv_icon.png/25px-Adv_icon.png"},
    an:{id:"an",icon:"http://implyingrigged.info/w/images/7/79/An_icon.png"},
    asp:{id:"asp",icon:"http://implyingrigged.info/w/images/f/f3/Asp_icon.png"},
    b:{id:"b",icon:"http://implyingrigged.info/w/images/thumb/9/9f/B_icon.png/25px-B_icon.png"},
    biz:{id:"biz",icon:"http://implyingrigged.info/w/images/thumb/0/04/Biz_icon.png/25px-Biz_icon.png"},
    c:{id:"c",icon:"http://implyingrigged.info/w/images/thumb/1/18/C_icon.png/25px-C_icon.png"},
    cgl:{id:"cgl",icon:"http://implyingrigged.info/w/images/thumb/c/ce/Cgl_icon.png/25px-Cgl_icon.png"},
    ck:{id:"ck",icon:"http://implyingrigged.info/w/images/f/f4/Ck_icon.png"},
    cm:{id:"cm",icon:"http://implyingrigged.info/w/images/c/c3/Cm_icon.png"},
    co:{id:"co",icon:"http://implyingrigged.info/w/images/8/8d/Co_icon.png"},
    d:{id:"d",icon:"http://implyingrigged.info/w/images/e/e0/D_icon.png"},
    diy:{id:"diy",icon:"http://implyingrigged.info/w/images/8/8a/Diy_icon.png"},
    e:{id:"e",icon:"http://implyingrigged.info/w/images/9/96/E_icon.png"},
    f:{id:"f",icon:"http://implyingrigged.info/w/images/2/2c/F_icon.png"},
    fa:{id:"fa",icon:"http://implyingrigged.info/w/images/5/5e/Fa_icon.png"},
    fit:{id:"fit",icon:"http://implyingrigged.info/w/images/2/20/Fit_icon.png"},
    g:{id:"g",icon:"http://implyingrigged.info/w/images/5/53/G_icon.png"},
    gd:{id:"gd",icon:"http://implyingrigged.info/w/images/e/e1/Gd_icon.png"},
    gif:{id:"gif",icon:"http://implyingrigged.info/w/images/thumb/6/6c/Gif_icon.png/25px-Gif_icon.png"},
    h:{id:"h",icon:"http://implyingrigged.info/w/images/f/f0/H_icon.png"},
    hm:{id:"hm",icon:"http://implyingrigged.info/w/images/thumb/9/9e/Hm_icon.png/25px-Hm_icon.png"},
    hr:{id:"hr",icon:"http://implyingrigged.info/w/images/1/13/Hr_icon.png"},
    i:{id:"i",icon:"http://implyingrigged.info/w/images/f/f4/I_icon.png"},
    ic:{id:"ic",icon:"http://implyingrigged.info/w/images/thumb/9/94/Ic_icon.png/25px-Ic_icon.png"},
    int:{id:"int",icon:"http://implyingrigged.info/w/images/0/08/Int_icon.png"},
    jp:{id:"jp",icon:"http://implyingrigged.info/w/images/8/82/Jp_icon.png"},
    k:{id:"k",icon:"http://implyingrigged.info/w/images/thumb/5/54/K_icon.png/25px-K_icon.png"},
    lgbt:{id:"lgbt",icon:"http://implyingrigged.info/w/images/2/24/Lgbt_icon.png"},
    lit:{id:"lit",icon:"http://implyingrigged.info/w/images/8/80/Lit_icon.png"},
    m:{id:"m",icon:"http://implyingrigged.info/w/images/e/e8/M_icon.png"},
    mlp:{id:"mlp",icon:"http://implyingrigged.info/w/images/d/d4/Mlp_icon.png"},
    mu:{id:"mu",icon:"http://implyingrigged.info/w/images/e/e6/Mu_icon.png"},
    n:{id:"n",icon:"http://implyingrigged.info/w/images/5/55/N_icon.png"},
    o:{id:"o",icon:"http://implyingrigged.info/w/images/7/7b/O_icon.png"},
    out:{id:"out",icon:"http://implyingrigged.info/w/images/thumb/f/f4/Out_icon.png/25px-Out_icon.png"},
    po:{id:"po",icon:"http://implyingrigged.info/w/images/thumb/4/4c/Po_icon.png/25px-Po_icon.png"},
    pol:{id:"pol",icon:"http://implyingrigged.info/w/images/0/0c/Pol_icon.png"},
    r9k:{id:"r9k",icon:"http://implyingrigged.info/w/images/f/f9/R9k_icon.png"},
    s:{id:"s",icon:"http://implyingrigged.info/w/images/thumb/9/9d/S_icon.png/25px-S_icon.png"},
    s4s:{id:"s4s",icon:"http://implyingrigged.info/w/images/thumb/3/31/S4s_icon.png/25px-S4s_icon.png"},
    sci:{id:"sci",icon:"http://implyingrigged.info/w/images/thumb/e/e1/Sci_icon.png/25px-Sci_icon.png"},
    soc:{id:"soc",icon:"http://implyingrigged.info/w/images/b/be/Soc_icon.png"},
    sp:{id:"sp",icon:"http://implyingrigged.info/w/images/8/83/Sp_icon.png"},
    t:{id:"t",icon:"http://implyingrigged.info/w/images/thumb/d/d9/T_icon.png/25px-T_icon.png"},
    tg:{id:"tg",icon:"http://implyingrigged.info/w/images/5/54/Tg_icon.png"},
    toy:{id:"toy",icon:"http://implyingrigged.info/w/images/e/e4/Toy_icon.png"},
    trv:{id:"trv",icon:"http://implyingrigged.info/w/images/thumb/8/8e/Trv_icon.png/25px-Trv_icon.png"},
    tv:{id:"tv",icon:"http://implyingrigged.info/w/images/3/3b/Tv_icon.png"},
    u:{id:"u",icon:"http://implyingrigged.info/w/images/4/4d/U_icon.png"},
    v:{id:"v",icon:"http://implyingrigged.info/w/images/thumb/4/44/V_icon.png/25px-V_icon.png"},
    vg:{id:"vg",icon:"http://implyingrigged.info/w/images/thumb/f/f1/Vg_icon.png/25px-Vg_icon.png"},
    vp:{id:"vp",icon:"http://implyingrigged.info/w/images/1/15/Vp_icon.png"},
    vr:{id:"vr",icon:"http://implyingrigged.info/w/images/thumb/f/ff/Vr_icon.png/25px-Vr_icon.png"},
    w:{id:"w",icon:"http://implyingrigged.info/w/images/thumb/c/c9/W_icon.png/25px-W_icon.png"},
    wg:{id:"wg",icon:"http://implyingrigged.info/w/images/0/0a/Wg_icon.png"},
    wsg:{id:"wsg",icon:"http://implyingrigged.info/w/images/thumb/c/cb/Wsg_icon.png/25px-Wsg_icon.png"},
    x:{id:"x",icon:"http://implyingrigged.info/w/images/thumb/4/43/X_icon.png/25px-X_icon.png"},
    y:{id:"y",icon:"http://implyingrigged.info/w/images/2/2f/Y_icon.png"}
};
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="teamIcons.js"></script>
    <script type="text/javascript" src="groupEdit.js"></script>
  </head>
  <body>
  <table style="width:795px; border: 0px; border-spacing: 0; background:inherit; table-layout:fixed;">
    <tbody id="groupsEdit">
        <tr>
            <th colspan="2" style="text-align:left; background:#EEEEEE; font-weight:normal; border-right:0px;">
                <input id="newGroup" type="button" value="New Group" />
                <input name="newsize" type="radio" value="5" />5
                <input name="newsize" type="radio" value="4" />4
                <input id="deleteGroup" type="button" value="Delete Group"/>
                </th>
            <th colspan="2" style="text-align:right; background:#EEEEEE; font-weight:normal;">
                <form target="_self" style="display: inline;" action="index.html" >
                	<input id="editSave" type="submit" value="Save Changes" />	
                	<input id="editCancel" type="submit" value="Cancel" />
                </form>
            </th>
        </tr>
        <tr>
            <td id="container" colspan="4">
              <div class="block">
                <table style="width:auto;  border-spacing: 0px;" id="editTableTemplate" class="table groupEdit">
                    <thead id="editHeadTemp">
                        <tr>
                            <th id="groupName" style="border-right:0px;">Group
                                <input type="text" style="border:0px; background:inherit; text-align:right; font-weight:bold; width:1em;" />:</th>
                            <th id="groupNick"><b>"<input type="text" style="border:0px; background:inherit; text-align:center; font-weight:bold; width:2em;"/>"</b>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr id="editTemplate">
                            <td colspan="2">
                                <img src="http://implyingrigged.info/w/images/thumb/c/cf/TBD_icon.png/25px-TBD_icon.png" /> <b> /?/ </b>
                            </td>
                        </tr>
                    </tbody>
                </table>
                </div>
            </td>
        </tr>
    </tbody>
</table>
</body>
</html>
/*
 * groupData: [
 * 	 {
 * 	   name: "",
 * 	   nick: "",
 * 	   teams: ["(team)"],
 *     matches: [{home:"(team)", away:"(team)", awayScore:0, homeScore:0}]
 *   }
 * ]
 */
var groupsEdit;
var editTableTemplate;
var editTemplate;
var editHead;
var container;

var selectedEditGroup = null;
var prevEditRow = null;
var deletedKeys = [];


var groupData;

function loadData(){
  var dataString = window.localStorage.getItem("groupData");
  groupData = dataString ? JSON.parse(dataString) : {};
  var teamString = window.localStorage.getItem("teamData");
  if(teamString){
    teamIcons = JSON.parse(teamString);
  }
}
loadData();

function setOnchangeTeam(element,minWidth){
	minWidth = minWidth || "1.5em";
    element.onkeypress = element.onkeydown = function(){
        window.setTimeout(function(){
        	element.style.width = minWidth;
        	window.getComputedStyle(element);
        	element.style.width = (element.scrollWidth)+"px";
        var img = element.parentNode.parentNode.querySelector("img");
        
        if(typeof teamIcons[element.value] === 'undefined'){
            replace(getTeamIcon(null),img);
        }else{
            replace(getTeamIcon(element.value),img);
        }
        img.alt = element.value.toUpperCase() + " icon.png";
        if(element.value == "s4s"){
          replace(new Text("["),element.previousSibling);
          replace(new Text("]"),element.nextSibling);
        }else{
          replace(new Text("/"),element.previousSibling);
          replace(new Text("/"),element.nextSibling);
        }
        },10);
    };
}

function setOnchange(element,minWidth){
	minWidth = minWidth || "1.5em";
    element.onkeypress = element.onkeydown = function(){
    	
        window.setTimeout(function(){
        	element.style.width = minWidth;
        	window.getComputedStyle(element);
        	element.style.width = (element.scrollWidth)+"px";},10);
    };
}

function editTextClick(event){
  var text = event.target;
  if(text.tagName != "B")
    return;
  text.innerHTML = ' /<input type="text"  style="border:0px; background:inherit; text-align:center; font-weight:bold;s"/>/ ';
  var input = text.querySelector("input");
  input.value = text.parentNode.parentNode.dataset.team ? text.parentNode.parentNode.dataset.team : "?";
  input.value = input.value == "?" ? "" : input.value;
  setOnchangeTeam(input);
  input.onkeydown();
  input.focus();
  text.removeEventListener("click",editTextClick);
  input.onblur = function(){
    this.parentNode.addEventListener("click",editTextClick);
    this.parentNode.innerHTML = getTeamName(this.parentNode.parentNode.parentNode.dataset.team = this.value == "" ? "?":this.value);
  };
}

function getTeamIcon(team){
    var icon = document.createElement("img");
    if(!team){
        icon.src = "http://implyingrigged.info/w/images/thumb/c/cf/TBD_icon.png/25px-TBD_icon.png";
        return icon;
    }
    icon.src = teamIcons[team].icon;
    icon.alt = team.toUpperCase() + " icon.png";
    if(teamIcons[team].allIcons)
        teamIcons[team].allIcons.push(icon);
    else
        teamIcons[team].allIcons = [icon];
    return icon;
}

function getTeamName(team){
  return (team == "s4s")? "[s4s]":"/"+team+"/";
}

function replace(New, Old){
    Old.parentNode.replaceChild(New, Old);
}

window.onload = function() {
  container =  document.getElementById("container");
  groupEdit = document.getElementById("groupEdit");  
  groupsEdit = document.getElementById("groupsEdit");
  editTableTemplate = document.getElementById("editTableTemplate");
  editTemplate = document.getElementById("editTemplate");
  editHead = document.getElementById("editHeadTemp");
  editTableTemplate.removeAttribute("id");
  editTemplate.removeAttribute("id");
  editHead.removeAttribute("id");
  editTableTemplate.tBodies[0].removeChild(editTableTemplate.tBodies[0].rows[0]);
  editTableTemplate.removeChild(editTableTemplate.tHead);
  container.removeChild(container.firstElementChild);
  
  groupsEdit.querySelector("#deleteGroup").onclick = function(){
    if(!selectedEditGroup)
      return;
    selectedEditGroup.style.background = "";
    container.removeChild(selectedEditGroup);
    if(groupData.hasOwnProperty(selectedEditGroup.firstElementChild.dataset.name)){
      groupsDeleted.push(selectedEditGroup);
    }
    selectedEditGroup = null;
  };
  
  var editGroupRadios = groupsEdit.rows[0].cells[0].querySelectorAll("input[type='radio']");
  editGroupRadios[0].onchange = editGroupRadios[1].onchange = function(event) {
    if(!selectedEditGroup)
      return;
    var selEditTable = selectedEditGroup.firstElementChild;
    var newSize = parseInt(event.target.value, 10);
    if (newSize == 4) {
      selEditTable.tBodies[0].deleteRow(4);
    } else if (newSize == 5) {
      selEditTable.tBodies[0].appendChild(editTemplate.cloneNode(true));
    }
  };
  
  groupsEdit.onclick = function(event){
    var target = event.target;
    while(target.tagName != "DIV" && target != groupsEdit)
      target = target.parentNode;
    if(target.tagName != "DIV")
      return;
    if(selectedEditGroup)
      selectedEditGroup.style.background = "";
    selectedEditGroup = target;
    selectedEditGroup.style.background = "#FFE65F";
    var radios = groupsEdit.rows[0].cells[0].querySelectorAll("input[type='radio']");
    switch(selectedEditGroup.querySelector("tBody").rows.length){
      case 4:{
        radios[1].checked = true;
        radios[0].checked = false;
        break;
      }
      case 5:{
        radios[0].checked = true;
        radios[1].checked = false;
        break;
      }
    }
  };
  
  document.getElementById("newGroup").onclick = function() {
    var key;
    for (key = "A"; groupsEdit.querySelector("#" + key + "edit") !== null; key = String.fromCharCode(key.charCodeAt(0) + 1));
    if (!this.parentNode.querySelector("input:checked"))
      return;
    var newsize = parseInt(this.parentNode.querySelector("input:checked").value, 10);
    var teamEdit = editTableTemplate.cloneNode(true);
    teamEdit.id = key + "edit";
    teamEdit.dataset.name = key;

    for (var i = 0; i < newsize; ++i) {
      var editTemp = editTemplate.cloneNode(true);
      editTemp.id = "";
      editTemp.onclick = editTextClick;
      teamEdit.tBodies[0].appendChild(editTemp);
    }

    var head = editHead.cloneNode(true);
    head.querySelector("input").value = key;
    setOnchange(head.querySelector("input"));
    setOnchange(head.querySelectorAll("input")[1]);
    teamEdit.insertBefore(head, teamEdit.firstChild);
    container.appendChild(document.createElement("div")).classList.add("block");
    container.lastElementChild.appendChild(teamEdit);
    container.lastElementChild.dataset.index = container.children.length-1;
    
    if(selectedEditGroup)
      selectedEditGroup.style.background = "";
    selectedEditGroup = container.lastElementChild;
    selectedEditGroup.style.background = "#FFE65F";
  };

  document.getElementById("editCancel").onclick = function() {
    //TODO: go back to other page
    //window.location.reload();
  };
  
  document.getElementById("editSave").onclick = function() {
  	var oldGroups = {};
  	Object.keys(groupData).forEach(function(key){ oldGroups[groupData[key].teams.join(",")] = groupData[key].matches; });
  	var newData = [];
  	var groupNodes = container.querySelectorAll(".groupEdit");
  	for(var i = 0; i < groupNodes.length; ++i){
  		newData.push(groupNodes[i]);
  	}
    newData = newData.map(function(groupTable){
    	var hInputs = groupTable.tHead.querySelectorAll("input");
    	var group = {};
    	group.name = hInputs[0].value || groupTable.dataset.name;
    	group.nick = hInputs[1].value;
    	group.teams = [];
    	for (var i = 0; i < groupTable.tBodies[0].rows.length; ++i) {
          group.teams[i] = groupTable.tBodies[0].rows[i].dataset.team;
        }
        group.matches = oldGroups[group.teams.join(",")];
        return group;
    });
    
    window.localStorage.setItem("groupData",JSON.stringify(newData));
    
    //TODO: go back to other page
    //window.location.reload();
  };
  
  (setup = function () {
    for(var key of Object.keys(groupData)) {
   	  var group = groupData[key];
      var teamEdit = editTableTemplate.cloneNode(true);
      teamEdit.id = group.name + "edit";
      teamEdit.dataset.name = group.name;
	
      for(var teamName of group.teams) {
        var editTemp = editTemplate.cloneNode(true);
        replace(getTeamIcon(teamName), editTemp.firstElementChild.querySelector("img"));
        editTemp.querySelector("b").innerHTML = getTeamName(teamName);
        editTemp.querySelector("b").onclick = editTextClick;
        editTemp.dataset.team = teamName;
        teamEdit.tBodies[0].appendChild(editTemp);
      }
      
      var head = editHead.cloneNode(true);
      head.querySelector("input").value = group.name;
      setOnchange(head.querySelector("input"),"1em");
      if (typeof group.nick != 'undefined') {
        head.querySelectorAll("input")[1].value = group.nick;
      }
      setOnchange(head.querySelectorAll("input")[1],"2em");
      teamEdit.insertBefore(head, teamEdit.firstChild);
      container.appendChild(document.createElement("div")).classList.add("block");
      container.lastElementChild.appendChild(teamEdit);
    }
  });
  setup();
};
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="teamIcons.js"></script>
    <script type="text/javascript" src="matches.js"></script>
    <script type="text/javascript" src="status.js"></script>
    <script type="text/javascript" src="main.js"></script>
  </head>
  <body>
  <table style="width:795px; border: 0px; border-spacing: 0; background:inherit; table-layout:fixed;">
    <tbody id="playing">
        <tr>
            <th id="selectGroup" style="border-right: 0px; background: #EEEEEE; text-align:left;" title="Select the group to view">
                <input id="byDay" type="button" value="by Match Day" style=" display:none;"/>
                <label>Group: </label>
                <input id="radioTemp" type="radio" name="group" class="groupButton"/>
            </th>
            <th id="selectDay" style="border-right: 0px; background: #EEEEEE; text-align:left; display:none;">
                <select id="daySel"></select>
                <input id="byGroup" type="button" value="by Group"/>
            </th>
            <th colspan="1" style="text-align:right; background:#EEEEEE; font-weight:normal;">
            	<form target="_self" style="display: inline;" action="matchEdit.html" ><input id="matchEdit" type="submit" value="Edit Matches" title="Change the order and sides of matches"/></form>
                <form target="_self" style="display: inline;" action="groupEdit.html" ><input id="editGroupsLink" type="submit"  value="Edit Groups" title="Add/Remove groups and edit their teams"/></form>
                <form target="_self" style="display: inline;" action="teamEdit.html" ><input id="editTeamsLink" type="submit" value="Edit Teams" title="Edit the icons for each team"/></form>
            </th>
        </tr>
        <tr>
          <td colspan="2" style="border: 0px;">
            <div style="margin:0; float:left; width:50%"> 
              <div style="border: 0px; vertical-align:middle; display:none;" id="groupButtons">
                Showing:<b>none</b>
          		<input id="groupUnshow" type="button" value="Unshow" style="display: none;" disabled />
          		<input id="groupShow" type="button" value="Show Group " style="display: none;" disabled />
          		
          		<input id="winOpen" type="button" value="Open Output Window" />
              </div>
              <h3 id="groupTitle"></h3>

             <table cellspacing="0" id="table" class="table">
               <thead>
                 <tr style="text-align:center;">
                   <th colspan="2" style="text-align:left;">Team</th>
                   <th>Pld</th>
                   <th>W</th>
                   <th>D</th>
                   <th>L</th>
                   <th>GF</th>
                   <th>GA</th>
                   <th>GD</th>
                   <th>Pts</th>
                 </tr>
               </thead>
               <tbody>
                 <tr id="template">
                   <td colspan="2"> <a> <img src="http://implyingrigged.info/w/images/thumb/c/cf/TBD_icon.png/25px-TBD_icon.png"/> </a>
 <b> <a></a> </b> 
                   </td>
                   <td>0</td>
                   <td>0</td>
                   <td>0</td>
                   <td>0</td>
                   <td>0</td>
                   <td>0</td>
                   <td>0</td>
                   <td> <b>0</b> 
                   </td>
                 </tr>
               </tbody>
             </table>
            </div>
            <div style="margin:0; float:left; width:50%">
              <table style="width:auto;  border-spacing: 0; margin-left: auto; margin-right: auto;" class="matchTable" id="matchTable">
                        <thead>
                            <tr>
                                <th colspan="2" style="width:auto; border-right:0px; text-align: left;">Home</th>
                                <th style="border-right:0px;" colspan="3">
                                </th>
                                <th colspan="2" style="text-align: right;">Away</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr id="matchTemplate">
                                <td colspan="2"> <a> 
                                    <img src="http://implyingrigged.info/w/images/thumb/c/cf/TBD_icon.png/25px-TBD_icon.png" draggable="false"/> 
                                </a>  <b> <a></a> </b> 
                                </td>
                                <td style="width:2em;">
                                    <input type="text" style="border:0px; background:inherit; width:90%; text-align:center; font-weight:bold;" />
                                </td>
                                <td style=""><b>vs</b>
                                </td>
                                <td style=" width:2em;">
                                    <input type="text" style="border:0px; background:inherit; width:90%; text-align:center; font-weight:bold;" />
                                </td>
                                <td colspan="2" style="text-align: right;"> <b> <a></a> </b>  <a> 
                                    <img src="http://implyingrigged.info/w/images/thumb/c/cf/TBD_icon.png/25px-TBD_icon.png" draggable="false"/> 
                                </a>

                                </td>
                            </tr>
                        </tbody>
                        <tfoot><tr>
                          <th colspan="7" style="border-top: 1px solid #000; border-bottom:0; border-radius:0; text-align:center; height:5px;">
                            <input id="matchAnimate" type="button" value="Animate" style="padding:0px;" title="Update selected standings with FANCY animations"/>
                            <input id="matchSet" type="button" value="Set" style="padding:0px;" title="Update selected standings (without animations)"/>
                          </th>
                        </tr></tfoot>
                    </table>
          </div></td>
        <!--td id="groupButtons" style="border: 0px; vertical-align:middle;">
        </td>
        <td style="border: 0px;" rowspan="2" id="MatchesByGroup">
                    
            </td>
        </tr>
        <tr style="background:inherit;">
            <td style="border: 0px;" >
               
            </td>
            
        </tr-->
    </tbody>
    
</table>
</body>
</html>

var tableTemplate;
var table;
var groupTitle;
var scoreDiv;
var outWindow = null;
var showing = null;
var unShow, showGroup, showButtons;
var radioTemplate, selectGroup;
var openWin;

var teamIcons;
var groupData;


function onMessage(event){
  if(event.data == "opened"){
    outWindow = event.source;
    showGroup.removeAttribute("disabled");
    openWin.setAttribute("disabled","1");
    showGroup.style.display = unShow.style.display = "";
    openWin.style.display = "none";
  }else if(event.data == "closing"){
  	var prev = selectGroup.querySelector(".showing");
  	if(prev)
  		prev.classList.remove("showing");
    setShowing(outWindow = null);
    showGroup.setAttribute("disabled","1");
    openWin.removeAttribute("disabled");
    showGroup.style.display = unShow.style.display = "none";
    openWin.style.display = "";
  }
}

function setShowing(group){
  if(group === null){
    showing = null;
    showButtons.querySelector("b").innerHTML = "none";
    unShow.setAttribute("disabled","1");
    showGroup.removeAttribute("disabled");
    if(outWindow)
      outWindow.postMessage({command:"unshow"},"*");
  }else{
    if(outWindow){
        outWindow.postMessage({command:(showing===null?"show":"switch"),
           name:"Group "+selectedGroup.name+(selectedGroup.nick? ": "+selectedGroup.nick : ""),
           standings:getRanks(selectedGroup.standings, group).map(function(rank){ return{team:rank.team,W:rank.W, D:rank.D, L:rank.L, GF:rank.GF, GA:rank.GA};})
        },"*");
      showing = group;
      showButtons.querySelector("b").innerHTML = "Group "+selectedGroup.name;
      unShow.removeAttribute("disabled");
      showGroup.setAttribute("disabled","1");
    }
  }
}

function winOpen(){
  if(!outWindow){
    outWindow = window.open("output.html","outWindow","menubar=0,toolbar=0,location=0,dependent=1,resizable=0");
    showGroup.removeAttribute("disabled");
    openWin.setAttribute("disabled","1");
    showGroup.style.display = "";
    unShow.style.display = "";
    openWin.style.display = "none";
  }
}

function loadData(){
  var dataString = window.localStorage.getItem("groupData");
  groupData = dataString ? JSON.parse(dataString) : [];
  if(typeof(groupData) == "object" && !Array.isArray(groupData)){
  	var tempData = [];
  	for(var i = 0; i < Object.keys(groupData).length; ++i){
  		tempData.push(groupData[Object.keys(groupData)[i]]);
  		tempData[i].name = Object.keys(groupData)[i];
  	}
  	groupData = tempData;
  }
  var teamString = window.localStorage.getItem("teamData");
  if(teamString){
    teamIcons = JSON.parse(teamString);
  }
}

var selectedGroup;
var setup;

function buildDayTable(order){
  var dayTbody = document.createElement("tbody");
  for(var i = 0; i < order.length; ++i){
    var row =  dayTbody.appendChild(groupData[order[i].group].standings.matches.rows[order[i].match].cloneNode(true));
    row.dataset.group = order[i].group;
    row.dataset.match = order[i].match;
    row.insertCell(0).innerHTML = (1700 + i*30) + "";
    if(i === 0 ||  order[i].group != order[i-1].group){
      var rSpn;
      for(rSpn = i; rSpn < order.length && order[i].group == order[rSpn].group; ++rSpn);
      var showButton = row.insertCell(0);
      if((rSpn-=i)>0) showButton.setAttribute("rowSpan",rSpn);
      showButton = showButton.appendChild(document.createElement("button"));
      showButton.innerHTML = "Show "+order[i].group;
      showButton.dataset.group = order[i].group;
      showButton.onclick = dayGroupShow;
    }
  }
}



function updateRow(standing) {
    var set = function (cell, num) {
        standing.row.cells[cell].innerHTML = (cell == 8) ? "<b>" + num + "</b>" : num;
    };
    set(1, standing.W + standing.D + standing.L);
    set(2, standing.W);
    set(3, standing.D);
    set(4, standing.L);
    set(5, standing.GF);
    set(6, standing.GA);
    set(7, standing.GF - standing.GA);
    standing.row.cells[8].innerHTML = "<b>" + (3 * standing.W + standing.D) + "</b>";
}

function buildStandings(group){
    var matches = group.matches;
    var standings = {};
    for(var teamName of group.teams){
        standings[teamName] = {team:teamName, W:0, D:0, L:0, GF:0, GA:0};
    }
    if(typeof matches != 'object'){
        group.matches = matches = getMatches(group.teams);
    }else{
        for(var match of matches){
            updateStandings(standings,match);
        }
        var status, perms = permutateMatches(matches);
        if(perms.length > 1){
        	status = getStatus(perms.map(function(perm){ return shallowStatus(shallowRanks(shallowStandings(perm)));}),group.teams);
        }else {
        	var ranks = getRanks(standings,group);
        	var teamRanks = {};
        	ranks.forEach(function(team,index,arr){ teamRanks[team.team] = index+1;});
        	status = shallowStatus(teamRanks);
        }
        Object.keys(status).forEach(function(key){ standings[key].status = status[key]; });
    }
    return standings;
}

function build_standings(teams, matches){
    var standings = {};
    for(var teamName of teams){
      standings[teamName] = {team:teamName, W:0, D:0, L:0, GF:0, GA:0};
    }
    for(var match of matches){
      updateStandings(standings,match);
    }
    return standings;
}

function buildRankTable(key,standings,teams){
  var Tbody = document.createElement("tbody");
  Tbody.id = key+"ranks";
  Tbody.style.display = "none";
  for(var teamName of teams){
    var template;
    template = tableTemplate.cloneNode(true);
    template.id = teamName;
    replace(getTeamIcon(teamName),template.querySelector("img"));
    var links = template.querySelectorAll("a");
    links[1].href = links[0].href = "http://implyingrigged.info/wiki//" + teamName + "/";
    links[1].innerHTML = links[1].title = links[0].title = getTeamName(teamName);
    if(standings[teamName].status){
    	if(standings[teamName].status == "A")
    		template.classList.add("win");
    	else if(standings[teamName].status == "E")
    		template.classList.add("loss");
    }
    standings[teamName].row = template;
    updateRow(standings[teamName]);
  }
  for(var rank of getRanks(standings,key)){
    Tbody.appendChild(rank.row);
  }
  return Tbody;
}

function getDiff(stand, Nstand) {
  return [null, //create gap for first cell
    (Nstand.W + Nstand.D + Nstand.L - stand.W - stand.D - stand.L), //Pld
    (Nstand.W - stand.W), //W
    (Nstand.D - stand.D), //D
    (Nstand.L - stand.L), //L
    (Nstand.GF - stand.GF), //GF
    (Nstand.GA - stand.GA), //GA
    (Nstand.GF - Nstand.GA - stand.GF + stand.GA), //GD
    (3 * Nstand.W + Nstand.D - 3 * stand.W - stand.D) //Pts
  ];
}

function updateStandings(standings, match) {
    if(typeof match.homeScore != 'undefined' && typeof match.awayScore != 'undefined'){
        if(match.homeScore > match.awayScore){
            standings[match.home].W ++;  
            standings[match.away].L ++;
        }else if(match.homeScore < match.awayScore){
            standings[match.home].L ++;  
            standings[match.away].W ++;                  
        }else{
            standings[match.home].D ++;  
            standings[match.away].D ++;                  
        }
        standings[match.home].GF += match.homeScore;
        standings[match.home].GA += match.awayScore;
        standings[match.away].GF += match.awayScore;
        standings[match.away].GA += match.homeScore;
    }
}

function getRanks(standings, group){
    if(typeof group === 'string' || typeof group === 'number')
      group = groupData[group];
    var teams = group.teams;
      
    //build temporary wrapper objects for better rank calculation
    var ranks = teams.map(function (team) {
        return {
            THIS: team,
            score: (3 * standings[team].W + standings[team].D),
            GD: (standings[team].GF - standings[team].GA),
            GF: standings[team].GF,
            rank: 0,
            team: standings[team],
        };
    });
    
    var compareRank = function(A,B){//returns if A is ranked higher than B
      var ptTied =           A.score == B.score;
      var GDTied = ptTied && A.GD    == B.GD;
      var  Tied   = GDTied && A.GF    == B.GF;
      var ptA = A.score > B.score;//A wins on points
      var ptB = B.score > A.score;//B wins on points
      var GDA = !ptB && A.GD    > B.GD;   //A wins on GD
      var GDB = !ptA && B.GD    > A.GD;   //B wins on GD
      var GFA = !ptB && !GDB && A.GF    > B.GF;   //A wins on GF
      var GFB = !ptB && !GDA && B.GF    > A.GF;   //B wins on GF
          
      //if tied the rank will be set equal to indicate so
      //otherwise it will be set to the current position of the list
      //example: 1,2,2,4,5
      if(ptA || GDA || GFA){
        return "A";
      }else if(ptB || GDB || GFB)
        return "B";
      else
        return "D";
    };
    
    //selection sort, Innitial sort pass
    var o, i;
    for(o = 0; o < ranks.length; ++o){
      var selected = o;
      ranks[o].rank = o;
      for(i = o+1; i < ranks.length; ++i){
        if(compareRank(ranks[i],ranks[selected]) == 'A')
          selected = i;
      }
      //swap selected element to end of the sorted list
      if(o != 0 && compareRank(ranks[o-1],ranks[selected]) == "D")
        ranks[selected].rank = ranks[o-1].rank;
      else
        ranks[selected].rank = o;
      var tmp = ranks[o];
      ranks[o] = ranks[selected];
      ranks[selected] = tmp;
    }
    
    //second pass: tie resolution
    var b, e;//beginning and end indicies of the currently tied rank
    for(b = 0; b < ranks.length; b = e){
      for(e = b+1; e < ranks.length && ranks[e].rank == ranks[b].rank; ++e);
      if(e-b > 1){//tie detected; more than one team is the same rank
        var tiedTeams = ranks.slice(b,e).map(function(rank){ return rank.team; });
        //get matches the only contain tied teams
        var matches = group.matches.filter(function(match){
          return tiedTeams.indexOf(match.home) >= 0 && tiedTeams.indexOf(match.away) >= 0;
        });
        //create new standings 
        var tmpStandings = build_standings(tiedTeams,matches);
        for(o = b; o < e; ++o){
          var standing = tmpStandings[tiedTeams[o-b]];
          ranks[o].score = 3 * standing.W + standing.D;
          ranks[o].GD = standing.GF - standing.GA;
          ranks[o].GF = standing.GF;
        }
        //selection sort within tie bounds
        for(o = b; o < e; ++o){
          var selected = o;
          for(i = o+1; i < e; ++i){
            if(compareRank(ranks[i],ranks[selected],o))
              selected = i;
            
          }
          //swap selected element to end of the sorted list
          var tmp = ranks[o];
          ranks[o] = ranks[selected];
          ranks[selected] = tmp;
        }
      }//end if tie
      
    }
    
    return ranks.map(function (rank) { return rank.team; });
}

function updateTable() {
    animate( getRanks(selectedGroup.standings, selectedGroup) ,1.5);
}

function animate(ranks,dur){
    var tableBody = selectedGroup.standings.ranks;
    var i, Heights = [0, 0, 0, 0, 0, 0];
    for (i = 0; i < ranks.length; i++) {
        var top = 0;
        var dest = 0;
        for (var j = 0; j < i; j++) {
            top -= tableBody.rows[j].offsetHeight;
            dest += ranks[j].row.offsetHeight;
        }
        Heights[i] += top;
        Heights[ranks[j].row.sectionRowIndex] += dest;
    }
    for (i = 0; i < ranks.length; i++) {
        tableBody.rows[i].style.transition = "all " + dur + "s";
        tableBody.rows[i].style.transform = "translateY(" + Heights[i] + "px)";
        tableBody.rows[i].classList.add("flash");
    }
        
    //set final positions
    window.setTimeout(function(){
       	for (var i = 0; i < ranks.length; i++) {
            tableBody.removeChild(ranks[i].row);
            ranks[i].row.removeAttribute("style");
            tableBody.appendChild(ranks[i].row);
        	
        }
        
    }, dur*1000);
    window.setTimeout(function(){
    	for (var i = 0; i < ranks.length; i++) {
    		var stand = selectedGroup.standings[ranks[i].row.id];
        	stand.row.classList.remove("win");
        	stand.row.classList.remove("loss");
        	if(stand.status){
       	  		if(stand.status == "A"){
        			stand.row.classList.remove("loss");
    	    		stand.row.classList.add("win");
    	  		}else if(stand.status == "E"){
        			stand.row.classList.remove("win");
    	    		stand.row.classList.add("loss");
    	    	}else{
        			stand.row.classList.remove("win");
        			stand.row.classList.remove("loss");
    	    	}
    	    	
        	}
        }
    	
    }, dur*1000+300);
    window.setTimeout(function(){
        for(var i = 0; i < tableBody.rows.length; ++i){
          	tableBody.rows[i].classList.remove("flash");
        }
    },dur*1000+800);
}

function getTeamIcon(team){
    var icon = document.createElement("img");
    if(!team){
        icon.src = "http://implyingrigged.info/w/images/thumb/c/cf/TBD_icon.png/25px-TBD_icon.png";
        return icon;
    }
    icon.src = teamIcons[team].icon;
    icon.alt = team.toUpperCase() + " icon.png";
    if(teamIcons[team].allIcons)
        teamIcons[team].allIcons.push(icon);
    else
        teamIcons[team].allIcons = [icon];
    return icon;
}

function getTeamName(team){
  return (team == "s4s")? "[s4s]":"/"+team+"/";
}

function replace(New, Old){
    Old.parentNode.replaceChild(New, Old);
}

function groupSelChange(target) {
  if(selectedGroup){
    selectedGroup.standings.ranks.style.display = "none";
    selectedGroup.standings.matches.style.display = "none";
    selectedGroup = groupData[target.value];
  }
  if(selectedGroup){
    selectedGroup.standings.ranks.style.display = "";
    selectedGroup.standings.matches.style.display = "";
    groupTitle.innerHTML = "Group " + groupData[target.value].name + (selectedGroup.nick ? ": \"" + selectedGroup.nick + "\"" : "");
  }
  showGroup.value = "Show Group "+groupData[target.value].name;
  if(showing === target.value){
    showGroup.setAttribute("disabled","1");
  }else if(outWindow){
    showGroup.removeAttribute("disabled");
  }
};

function makeOption(key){
  var option = groupSel.appendChild(document.createElement("option"));
  option.innerHTML = "Group " + groupData[key].name;
  option.value = option.name = key;
  option.id = "option"+key;
  return option;
}

function makeRadio(key){
  var radio = selectGroup.appendChild(radioTemplate.cloneNode(true));
  var label = selectGroup.appendChild(document.createElement("label"));
  radio.value = key;
  radio.id = "radio"+key;
  label.setAttribute("for","raido"+key);
  label.innerHTML = groupData[key].name;
  label.onclick = function(e){ e.target.previousSibling.checked = true; groupSelChange(e.target.previousSibling); };
  return radio;
}

window.onload = function() {
  table = document.getElementById("table");
  tableTemplate = document.getElementById("template");
  groupTitle = document.getElementById("groupTitle");
  matchTable = document.getElementById("matchTable");
  matchTemplate = document.getElementById("matchTemplate");
  scoreDiv = document.getElementById("scoreDiv");
  matchEdit = document.getElementById("matchEdit");
  unShow = document.getElementById("groupUnshow");
  showGroup = document.getElementById("groupShow");
  showButtons = document.getElementById("groupButtons");
  openWin = document.getElementById("winOpen");
  radioTemplate = document.getElementById("radioTemp");
  selectGroup = document.getElementById("selectGroup");
  
  unShow.onclick = function(){
  	var prev = selectGroup.querySelector(".showing");
  	if(prev)
  		prev.classList.remove("showing");
    setShowing(null);
  };
  
  showGroup.onclick = function(){
  	var groupRadio = selectGroup.querySelector("input[name='group']:checked");
  	var prev = selectGroup.querySelector(".showing");
  	if(prev)
  		prev.classList.remove("showing");
  	groupRadio.classList.add("showing");
    setShowing(groupRadio.value);
  };
  
  
  document.getElementById("winOpen").addEventListener("click",winOpen,false);
  
  window.onunload = function(){
    if(outWindow)
      outWindow.postMessage({command:"close"},"*");
  };
  
  window.addEventListener("message",onMessage,false);
  
  tableTemplate.removeAttribute("id");
  table.removeChild(table.tBodies[0]);
  matchTemplate.removeAttribute("id");
  matchTable.removeChild(matchTable.tBodies[0]);
  selectGroup.removeChild(radioTemplate);
  radioTemplate.removeAttribute("id");
  
  

  document.getElementById("matchAnimate").onclick = function() {
    parseMatches();
    var i;
    var timeout = function() { selectedGroup.standings.ranks.deleteRow(-1); };
    var newStandings = buildStandings(selectedGroup);
    var diffs = {};
    var messageDelay = 1;
    if(outWindow && showing != groupData.indexOf(selectedGroup)){
      setShowing(groupData.indexOf(selectedGroup));
      messageDelay = 8000;
    }
    for (var team of selectedGroup.teams) {
      var stand = selectedGroup.standings[team];
      var Nstand = newStandings[team];
      var diff = getDiff(stand,Nstand);
      diff[0] = team;
      diffs[team] = diff;
        Nstand.row = stand.row;
        selectedGroup.standings[team] = Nstand;
        updateRow(Nstand);
      if (diff[2] !== 0 || diff[3] !== 0 || diff[4] !== 0 || diff[5] !== 0 || diff[6] !== 0) {
        //add some fancy popup stuff
        var textFloaty = selectedGroup.standings.ranks.insertRow();
        var textFloatyCell = textFloaty.insertCell();
        textFloatyCell.style.width = "98px";
        textFloatyCell.style.border = "0px";
        textFloatyCell.style.backgroundColor = "transparent";
        for (i = 1; i < 9; ++i) {
          textFloatyCell = textFloaty.insertCell();
          if (diff[i] !== 0) {
            textFloatyCell.innerHTML = "<b>" + (diff[i] < 0 ? "" : "+") + diff[i] + "</b>";
            textFloatyCell.style.color = diff[i] < 0 ? "red" : "lime";
          }
          textFloatyCell.style.border = "0px";
          textFloatyCell.style.width = "32px";
          textFloatyCell.style.backgroundColor = "transparent";
        }
        textFloaty.style.backgroundColor = "transparent";
        textFloaty.style.position = "absolute";
        textFloaty.style.top = Nstand.row.offsetTop + "px";
        textFloaty.style.transitionProperty = "opacity, transform";
        textFloaty.style.transitionDuration = "1s, 1s";
        textFloaty.style.transitionDelay = ".5s, 0s";
        textFloaty.style.transitionTimingFunction = "linear";
        textFloaty.style.transform = "translateY(-16px)";
        textFloaty.style.opacity = "0";
        window.setTimeout(timeout, 1500);
      }
    }
    var newRanks = getRanks(selectedGroup.standings, selectedGroup);
    if(outWindow){
      window.setTimeout(function() {
        outWindow.postMessage({command:"update", standings:newRanks.map(function(rank){ var d = diffs[rank.team]; return {team:d[0], W:d[2], D:d[3], L:d[4], GF:d[5], GA:d[6]}; }) },"*");
      }, messageDelay);
    }
    window.setTimeout(function() {
     animate( newRanks ,1.5);
    }, 1500);
  };

  document.getElementById("matchSet").onclick = function() {
    parseMatches();
    var newStandings = buildStandings(selectedGroup);
    for (var team of selectedGroup.teams) {
      var stand = selectedGroup.standings[team];
      var Nstand = newStandings[team];
      var diff = getDiff(stand,Nstand);
        Nstand.row = stand.row;
        selectedGroup.standings[team] = Nstand;
        updateRow(Nstand);
        Nstand.row.classList.remove("win");
        Nstand.row.classList.remove("loss");
        if(Nstand.status){
       	  if(Nstand.status == "A")
    	    Nstand.row.classList.add("win");
    	  else if(Nstand.status == "E")
    	    Nstand.row.classList.add("loss");
        }
    }
    var ranks = getRanks(selectedGroup.standings, selectedGroup);
    for (i = 0; i < ranks.length; i++) {
      selectedGroup.standings.ranks.removeChild(ranks[i].row);
      ranks[i].row.removeAttribute("style");
      selectedGroup.standings.ranks.appendChild(ranks[i].row);
    }
  };

  (setup = function () {
    loadData();

    for (key of Object.keys(groupData)) {
      makeRadio(key);
      var Tbody = document.createElement("tbody");
      Tbody.id = key + "ranks";
      Tbody.style.display = "none";

      var standings = buildStandings(groupData[key]);
      table.appendChild(standings.ranks = buildRankTable(key, standings, groupData[key].teams));

      matchTable.appendChild(standings.matches = buildMatchTable(key, groupData[key].matches)).style.display = "none";

      groupData[key].standings = standings;

    }
    if (groupData.length > 0) {
      var firstGroup = groupData[0];
      firstGroup.standings.ranks.style.display = "";
      firstGroup.standings.matches.style.display = "";
      groupTitle.innerHTML = "Group " + firstGroup.name + (firstGroup.nick ? ": \"" + firstGroup.nick + "\"" : "");
      selectedGroup = groupData[0];
  	  showGroup.value = "Show Group "+ firstGroup.name;
  	  selectGroup.querySelector("input[type='radio']").checked = true;
    }else {
  	  selectedGroup = null;
    	
    }
  })();
  
};
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="teamIcons.js"></script>
    <script type="text/javascript" src="matchEdit.js"></script>
    <script type="text/javascript">
    	
    </script>
  </head>
  <body>
  <table style="width:795px; border: 0px; border-spacing: 0; background:inherit; table-layout:fixed;">
    <tbody id="matchEdit">
        <tr>
            <th colspan="3" style="text-align:left; background:#EEEEEE; font-weight:normal; border-right:0px;">
              <i>drag up&amp;down to change order, drag across to swap sides</i>
            </th>
            <th colspan="1" style="text-align:right; background:#EEEEEE; font-weight:normal;">
                <form target="_self" style="display: inline;" action="index.html" >
                	<input id="editSave" type="submit" value="Save Changes" />	
                	<input id="editCancel" type="submit" value="Cancel" />
                </form>
            </th>
        </tr>
        <tr>
            <td id="container" colspan="4">
              <div class="block">
                <table style="width:auto;  border-spacing: 0; margin-left: auto; margin-right: auto;" class="matchTable" id="matchTableTemplate">
                        <thead>
                            <tr>
                                <th colspan="2" style="width:auto; border-right:0px; text-align: left;">Home</th>
                                <th style="border-right:0px; text-align: center;" colspan="3">
                                  <b></b>
                                </th>
                                <th colspan="2" style="text-align: right;">Away</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr id="matchTemplate">
                                <td colspan="2"> <a> 
                                    <img src="http://implyingrigged.info/w/images/thumb/c/cf/TBD_icon.png/25px-TBD_icon.png" draggable="false"/> 
                                </a>  <b> <a></a> </b> 
                                </td>
                                <td style="width:1px;">
                                    <input type="text" style="border:0px; background:inherit; width:90%; text-align:center; font-weight:bold;" />
                                </td>
                                <td style=""><b>vs</b>
                                </td>
                                <td style=" width:1px;">
                                    <input type="text" style="border:0px; background:inherit; width:90%; text-align:center; font-weight:bold;" />
                                </td>
                                <td colspan="2" style="text-align: right;"> <b> <a></a> </b>  <a> 
                                    <img src="http://implyingrigged.info/w/images/thumb/c/cf/TBD_icon.png/25px-TBD_icon.png" draggable="false"/> 
                                </a>

                                </td>
                            </tr>
                        </tbody>
                        <tfoot><tr>
                          <th colspan="7" style="border-top: 1px solid #000; border-bottom:0; border-radius:0; text-align:left; height:5px;">
                          </th>
                        </tr></tfoot>
                    </table>
                </div>
            </td>
        </tr>
    </tbody>
</table>
</body>
</html>

var matchTable;
var matchTableTemplate;
var matchTemplate;
var macthEdit, matchSave, matchCancel;
var container;
var groupData;

function loadData(){
  var dataString = window.localStorage.getItem("groupData");
  groupData = dataString ? JSON.parse(dataString) : {};
  var teamString = window.localStorage.getItem("teamData");
  if(teamString){
    teamIcons = JSON.parse(teamString);
  }
}
loadData();

function getTeamIcon(team){
	var icon = document.createElement("img");
	if(!team){
		icon.src = "http://implyingrigged.info/w/images/thumb/c/cf/TBD_icon.png/25px-TBD_icon.png";
		return icon;
  }
	icon.src = teamIcons[team].icon;
	icon.alt = team.toUpperCase() + " icon.png";
    if(teamIcons[team].allIcons)
        teamIcons[team].allIcons.push(icon);
    else
        teamIcons[team].allIcons = [icon];
    return icon;
}

function getTeamName(team){
  return (team == "s4s")? "[s4s]":"/"+team+"/";
}

function replace(New, Old){
    Old.parentNode.replaceChild(New, Old);
}
		
window.onload = function(){
	container =  document.getElementById("container");
	matchTableTemplate = document.getElementById("matchTableTemplate");
	matchTemplate = document.getElementById("matchTemplate");
	matchSave =  document.getElementById("editSave");
	matchCancel =  document.getElementById("editCancel");
			
	container.removeChild(container.firstElementChild);
	matchTemplate.removeAttribute("id");
	matchTableTemplate.removeAttribute("id");
  	matchTableTemplate.removeChild(matchTableTemplate.tBodies[0]);
	(setup = function () {
		for(var key of Object.keys(groupData)) {
		  var group = groupData[key];
		  var matchEdit = matchTableTemplate.cloneNode(true);
		  matchEdit.id = group.name + "edit";
		  matchEdit.dataset.name = group.name;
		  group.matches = group.matches || getMatches(group.teams);
	
		  matchEdit.appendChild(buildMatchTable(key,group.matches));
		  matchEdit.tHead.rows[0].cells[1].firstElementChild.innerHTML = group.name;
      
		  container.appendChild(document.createElement("div")).classList.add("block");
		  container.lastElementChild.appendChild(matchEdit);
		}
		onMatchEdit();
    });
	setup();
};

function getMatches(cur){
    var matches;
    if(cur.length == 5){
        matches = [
            { home: cur[0], away: cur[3] },
            { home: cur[1], away: cur[2] },
            { home: cur[2], away: cur[0] },
            { home: cur[3], away: cur[4] },
            { home: cur[4], away: cur[2] },
            { home: cur[0], away: cur[1] },
            { home: cur[1], away: cur[4] },
            { home: cur[2], away: cur[3] },
            { home: cur[3], away: cur[1] },
            { home: cur[4], away: cur[0] }
        ];
    }else{
        matches = [
            { home: cur[0], away: cur[2] },
            { home: cur[1], away: cur[3] },
            { home: cur[0], away: cur[1] },
            { home: cur[2], away: cur[3] },
            { home: cur[1], away: cur[2] },
            { home: cur[3], away: cur[0] }
        ];
    }
    return matches;
}

function buildMatchRow(match){
  var template = matchTemplate.cloneNode(true);
  var icons = template.querySelectorAll("img");
  var links = template.querySelectorAll("a");
  var inputs = template.querySelectorAll("input");
  if(typeof match.homeScore != 'undefined'){
    inputs[0].value = match.homeScore;
  }
  if(typeof match.awayScore != 'undefined'){
    inputs[1].value = match.awayScore;
  }
  if(typeof match.homeScore != 'undefined' && typeof match.awayScore != 'undefined'){
    template.className += match.homeScore > match.awayScore ? " homeWin": match.homeScore < match.awayScore ? " awayWin":" bothDraw";
  }
  replace(getTeamIcon(match.home),icons[0]);
  replace(getTeamIcon(match.away),icons[1]);
  links[1].innerHTML = links[1].title = links[0].title = getTeamName(match.home);
  links[2].innerHTML = links[2].title = links[3].title = getTeamName(match.away);
  return template;
}

function buildMatchTable(key,matches){
  var matchesTbody = document.createElement("tbody");
  matchesTbody.id = key+"matches";
  
  for(var match of matches){
    matchesTbody.appendChild(buildMatchRow(match));
  }
  return matchesTbody;
}

function parseMatches(selectedTbody, selectedMatches) {
  selectedTbody = selectedTbody || selectedGroup.standings.matches;
  selectedMatches = selectedMatches || selectedGroup.matches;
  for (var i = 0; i < selectedGroup.matches.length; ++i) {
    var match = selectedMatches[i];
    var inputs = selectedTbody.rows[i].querySelectorAll("input");
    var homeScore = parseInt(inputs[0].value, 10);
    var awayScore = parseInt(inputs[1].value, 10);
    if (!isNaN(homeScore) && !isNaN(awayScore)) {
      selectedMatches[i].homeScore = homeScore;
      selectedMatches[i].awayScore = awayScore;
      selectedTbody.rows[i].classList.remove("homeWin","awayWin","bothDraw");
      selectedTbody.rows[i].classList.add( homeScore>awayScore ?"homeWin":( awayScore>homeScore ?"awayWin":"bothDraw" ) );
    } else {
      delete selectedMatches[i].homeScore;
      delete selectedMatches[i].awayScore;
    }
  }
  var saveData = [];
  for(var groupKey of Object.keys(groupData)){
    saveData[groupKey] = { name:groupData[groupKey].name, nick:groupData[groupKey].nick, teams:groupData[groupKey].teams, matches:groupData[groupKey].matches};
  }
  window.localStorage.setItem("groupData",JSON.stringify(saveData));
}






var isMouseDown = false;
window.addEventListener("mousedown",function(){
	isMouseDown = true;
});
window.addEventListener("mouseup",function(){
	isMouseDown = false;
});

function onMatchEdit() {
    var changes = [];
    for(var j = 0; j < groupData.length; ++j){
    	changes[j] = [];
    	for(var i = 0; i < groupData[j].matches.length; ++i){
      		changes[j][i] = { origin:i, swap:false };
    	}
    }
    container.className += " unselectable";
    var imgs = container.querySelectorAll("img");
    for(i = 0; i < imgs.length; ++ i){
    	imgs[i].ondragstart = function (e){
    		e.preventDefault();
    		return false;
    	};
    }
    container.addEventListener("mousedown",matchMDown,true);
    
	function matchMDown(event) {
		document.body.classList.add("unselectable");
		var target,
		    delegater = event.currentTarget;
		//get delegated target
		for ( target = event.target; target.tagName != "TR"; target = target.parentNode) {
			if (target == delegater)
				return;
		}
		if (target.parentNode.tagName == "THEAD")
				return;

		var rect = target.getBoundingClientRect();
		target.style.top = target.offsetTop + "px";
		target.parentNode.parentNode.tHead.rows[0].cells[0].style.width = target.cells[0].style.width = target.cells[0].clientWidth -2 + "px";
		target.parentNode.parentNode.tHead.rows[0].cells[2].style.width = target.cells[4].style.width = target.cells[4].clientWidth -2 + "px";
		
		target.classList.add("dragging");
		window.getComputedStyle(target);
		var x = event.clientX,
		    y = event.clientY;
		var targMidX = rect.left + (rect.right - rect.left) / 2;
		var targOff = y - target.offsetTop;
		var swapped = false;
		var sibling = target.nextSibling;
		if (sibling)
			sibling.classList.add("spaceAbove");
		else
			target.previousSibling.classList.add("spaceBelow");
		var allSibs = [];
		for (var i = 0; i < target.parentNode.children.length; ++i) {
			if (target.parentNode.children[i] != target)
				allSibs.push(target.parentNode.children[i]);
		}
		var onMove = function(event) {
			if (!isMouseDown) {
				onUp();
				return;
			}

			var i;
			target.style.top = event.clientY - targOff + "px";
			window.getComputedStyle(target);
			var targRect = target.getBoundingClientRect();
			sibling = null;
			var sibRect;
			var sibTop,
			    sibBot,
			    sibMids = [],
			    targMidY = (targRect.top + targRect.bottom) / 2;
			for ( i = 0; i < allSibs.length; ++i) {
				sibRect = allSibs[i].getBoundingClientRect();
				sibTop = sibRect.top;
				sibBot = sibRect.bottom;
				if (allSibs[i].classList.contains("spaceAbove"))
					sibTop += 35;
				if (allSibs[i].classList.contains("spaceBelow"))
					sibBot -= 35;
				sibMids[i] = (sibTop + sibBot) / 2;
			}
			for ( i = 0; i < allSibs.length; ++i) {
				if ((!i || targMidY > sibMids[i - 1]) && targMidY <= sibMids[i]) {
					sibling = allSibs[i];
					allSibs[i].classList.add("spaceAbove");
				} else {
					allSibs[i].classList.remove("spaceAbove");
				}
			}
			if (!sibling) {
				sibling = null;
				allSibs[allSibs.length - 1].classList.add("spaceBelow");
				window.getComputedStyle(allSibs[allSibs.length - 1]);
			} else {
				allSibs[allSibs.length - 1].classList.remove("spaceBelow");
			}

			//if the mouse has moved to the other side
			var crossed = (x - targMidX) * (event.clientX - targMidX) < 0;
			//if the side has been switched
			if ((crossed && !swapped) || (!crossed && swapped)) {
				swapped = !swapped;
				//reverse cell order
				for ( i = 1; i < target.cells.length; ++i) {
					target.insertBefore(target.cells[i], target.cells[0]);
				}
				var tempWidth = target.cells[0].style.minWidth;
				target.cells[0].style.minWidth = target.cells[4].style.minWidth;
				target.cells[4].style.minWidth = tempWidth;
			}
		};
		var onUp = function(event) {
			if (!allSibs || !target)
				return;
			document.body.classList.remove("unselectable");
			for (var i = 0; i < allSibs.length; ++i) {
				allSibs[i].classList.remove("spaceAbove");
				allSibs[i].classList.remove("spaceBelow");
			}
			var editMatches = target.parentNode;
			var groupChanges = changes[parseInt(editMatches.id,10)];
			var change = groupChanges[target.sectionRowIndex];
			groupChanges.splice(target.sectionRowIndex,1);
			editMatches.removeChild(target);
			if(swapped)
				change.swap = !change.swap;
			if(sibling){
				groupChanges.splice(sibling.sectionRowIndex,0,change);
				editMatches.insertBefore(target,sibling);
			}else{
				groupChanges.push(change);
				editMatches.appendChild(target);
			}
			target.style.top = 0;
			target.classList.remove("dragging");
			target.parentNode.parentNode.tHead.rows[0].cells[0].style.width = target.cells[0].style.width = "";
			target.parentNode.parentNode.tHead.rows[0].cells[2].style.width = target.cells[4].style.width = "";
			window.getComputedStyle(target);

			window.removeEventListener("mousemove", onMove, true);
			window.removeEventListener("mouseup", onUp, true);
		};
		window.addEventListener("mousemove", onMove, true);
		window.addEventListener("mouseup", onUp, true);
	};

    
    //replace(editMatches,tempMatches);
    matchCancel.onclick = function(){
    };
    matchSave.onclick = function(){
    	for(var j = 0; j < groupData.length; ++j){
      		var newMatches = [];
      		for(var i = 0; i < changes[j].length; ++i){
        		//originMatch
        		var oM = groupData[j].matches[changes[j][i].origin];
        		newMatches[i] = (changes[j][i].swap) ? { home:oM.away, away:oM.home, homeScore:oM.awayScore, awayScore:oM.homeScore }:oM;
      		}
      		groupData[j].matches = newMatches;
     	}
     	window.localStorage.setItem("groupData",JSON.stringify(groupData));
    };
  };
  




var matchTable;
var matchTableTemplate;
var matchTemplate;
var macthEdit;

function getMatches(cur){
    var matches;
    if(cur.length == 5){
        matches = [
            { home: cur[0], away: cur[3] },
            { home: cur[1], away: cur[2] },
            { home: cur[2], away: cur[0] },
            { home: cur[3], away: cur[4] },
            { home: cur[4], away: cur[2] },
            { home: cur[0], away: cur[1] },
            { home: cur[1], away: cur[4] },
            { home: cur[2], away: cur[3] },
            { home: cur[3], away: cur[1] },
            { home: cur[4], away: cur[0] }
        ];
    }else{
        matches = [
            { home: cur[0], away: cur[2] },
            { home: cur[1], away: cur[3] },
            { home: cur[0], away: cur[1] },
            { home: cur[2], away: cur[3] },
            { home: cur[1], away: cur[2] },
            { home: cur[3], away: cur[0] }
        ];
    }
    return matches;
}

function buildMatchRow(match){
  var template = matchTemplate.cloneNode(true);
  var icons = template.querySelectorAll("img");
  var links = template.querySelectorAll("a");
  var inputs = template.querySelectorAll("input");
  if(typeof match.homeScore != 'undefined'){
    inputs[0].value = match.homeScore;
  }
  if(typeof match.awayScore != 'undefined'){
    inputs[1].value = match.awayScore;
  }
  if(typeof match.homeScore != 'undefined' && typeof match.awayScore != 'undefined'){
    template.className += match.homeScore > match.awayScore ? " homeWin": match.homeScore < match.awayScore ? " awayWin":" bothDraw";
  }
  replace(getTeamIcon(match.home),icons[0]);
  replace(getTeamIcon(match.away),icons[1]);
  links[1].innerHTML = links[1].title = links[0].title = getTeamName(match.home);
  links[2].innerHTML = links[2].title = links[3].title = getTeamName(match.away);
  return template;
}

function buildMatchTable(key,matches){
  var matchesTbody = document.createElement("tbody");
  matchesTbody.id = key+"matches";
  matchesTbody.style.display = "none";
  
  for(var match of matches){
    matchesTbody.appendChild(buildMatchRow(match));
  }
  return matchesTbody;
}

function parseMatches(selectedTbody, selectedMatches) {
  selectedTbody = selectedTbody || selectedGroup.standings.matches;
  selectedMatches = selectedMatches || selectedGroup.matches;
  for (var i = 0; i < selectedGroup.matches.length; ++i) {
    var match = selectedMatches[i];
    var inputs = selectedTbody.rows[i].querySelectorAll("input");
    var homeScore = parseInt(inputs[0].value, 10);
    var awayScore = parseInt(inputs[1].value, 10);
    selectedTbody.rows[i].classList.remove("homeWin","awayWin","bothDraw");
    if (!isNaN(homeScore) && !isNaN(awayScore)) {
      selectedMatches[i].homeScore = homeScore;
      selectedMatches[i].awayScore = awayScore;
      selectedTbody.rows[i].classList.add( homeScore>awayScore ?"homeWin":( awayScore>homeScore ?"awayWin":"bothDraw" ) );
    } else {
      delete selectedMatches[i].homeScore;
      delete selectedMatches[i].awayScore;
    }
  }
  var saveData = [];
  for(var groupKey of Object.keys(groupData)){
    saveData[groupKey] = { name:groupData[groupKey].name, nick:groupData[groupKey].nick, teams:groupData[groupKey].teams, matches:groupData[groupKey].matches};
  }
  window.localStorage.setItem("groupData",JSON.stringify(saveData));
}






var isMouseDown = false;
window.addEventListener("mousedown",function(){
	isMouseDown = true;
});
window.addEventListener("mouseup",function(){
	isMouseDown = false;
});

function onMatchEdit() {
    if(!selectedGroup)
      return;
    var tempMatches = selectedGroup.standings.matches;
    var editMatches = tempMatches.cloneNode(true);
    var changes = [];
    for(var i = 0; i < editMatches.rows.length; ++i){
      var inputs = editMatches.rows[i].querySelectorAll("input");
      replace(new Text(inputs[0].value) ,inputs[0]);
      replace(new Text(inputs[1].value) ,inputs[1]);
      changes[i] = { origin:i, swap:false };
    }
    editMatches.className += " unselectable";
    var imgs = editMatches.querySelectorAll("img");
    for(i = 0; i < imgs.length; ++ i){
    	imgs[i].ondragstart = function (e){
    		e.preventDefault();
    		return false;
    	};
    }
    editMatches.addEventListener("mousedown",matchMDown,true);
    
	function matchMDown(event) {
		document.body.classList.add("unselectable");
		var target,
		    delegater = event.currentTarget;
		//get delegated target
		for ( target = event.target; target.tagName != "TR"; target = target.parentNode) {
			if (target == delegater)
				return;
		}

		var rect = target.getBoundingClientRect();
		target.style.top = target.offsetTop + "px";
		target.cells[0].style.width = target.parentNode.parentNode.tHead.rows[0].cells[0].offsetWidth + "px";
		target.cells[4].style.width = target.parentNode.parentNode.tHead.rows[0].cells[2].offsetWidth + "px";
		target.classList.add("dragging");
		window.getComputedStyle(target);
		var x = event.clientX,
		    y = event.clientY;
		var targMidX = rect.left + (rect.right - rect.left) / 2;
		var targOff = y - target.offsetTop;
		var swapped = false;
		var sibling = target.nextSibling;
		if (sibling)
			sibling.classList.add("spaceAbove");
		else
			target.previousSibling.classList.add("spaceBelow");
		var allSibs = [];
		for (var i = 0; i < target.parentNode.children.length; ++i) {
			if (target.parentNode.children[i] != target)
				allSibs.push(target.parentNode.children[i]);
		}
		var onMove = function(event) {
			if (!isMouseDown) {
				onUp();
				return;
			}

			var i;
			target.style.top = event.clientY - targOff + "px";
			window.getComputedStyle(target);
			var targRect = target.getBoundingClientRect();
			sibling = null;
			var sibRect;
			var sibTop,
			    sibBot,
			    sibMids = [],
			    targMidY = (targRect.top + targRect.bottom) / 2;
			for ( i = 0; i < allSibs.length; ++i) {
				sibRect = allSibs[i].getBoundingClientRect();
				sibTop = sibRect.top;
				sibBot = sibRect.bottom;
				if (allSibs[i].classList.contains("spaceAbove"))
					sibTop += 35;
				if (allSibs[i].classList.contains("spaceBelow"))
					sibBot -= 35;
				sibMids[i] = (sibTop + sibBot) / 2;
			}
			for ( i = 0; i < allSibs.length; ++i) {
				if ((!i || targMidY > sibMids[i - 1]) && targMidY <= sibMids[i]) {
					sibling = allSibs[i];
					allSibs[i].classList.add("spaceAbove");
				} else {
					allSibs[i].classList.remove("spaceAbove");
				}
			}
			if (!sibling) {
				sibling = null;
				allSibs[allSibs.length - 1].classList.add("spaceBelow");
				window.getComputedStyle(allSibs[allSibs.length - 1]);
			} else {
				allSibs[allSibs.length - 1].classList.remove("spaceBelow");
			}

			//if the mouse has moved to the other side
			var crossed = (x - targMidX) * (event.clientX - targMidX) < 0;
			//if the side has been switched
			if ((crossed && !swapped) || (!crossed && swapped)) {
				swapped = !swapped;
				//reverse cell order
				for ( i = 1; i < target.cells.length; ++i) {
					target.insertBefore(target.cells[i], target.cells[0]);
				}
			}
		};
		var onUp = function(event) {
			if (!allSibs || !target)
				return;
			document.body.classList.remove("unselectable");
			for (var i = 0; i < allSibs.length; ++i) {
				allSibs[i].classList.remove("spaceAbove");
				allSibs[i].classList.remove("spaceBelow");
			}
			var change = changes[target.sectionRowIndex];
			changes.splice(target.sectionRowIndex,1);
			editMatches.removeChild(target);
			if(swapped)
				change.swap = !change.swap;
			if(sibling){
				changes.splice(sibling.sectionRowIndex,0,change);
				editMatches.insertBefore(target,sibling);
			}else{
				changes.push(change);
				editMatches.appendChild(target);
			}
			target.style.top = 0;
			target.classList.remove("dragging");
			window.getComputedStyle(target);

			window.removeEventListener("mousemove", onMove, true);
			window.removeEventListener("mouseup", onUp, true);
		};
		window.addEventListener("mousemove", onMove, true);
		window.addEventListener("mouseup", onUp, true);
	};

    
    replace(editMatches,tempMatches);
    matchCancel.onclick = function(){
      replace(tempMatches,editMatches);
      matchEdit.style.display = "";
      playing.rows[0].style.display = "";
      matchCancel.style.display = "none";
      matchSave.style.display = "none";
    };
    matchSave.onclick = function(){
      var newMatches = [];
      for(var i = 0; i < changes.length; ++i){
        //originMatch
        var oM = selectedGroup.matches[changes[i].origin];
        newMatches[i] = (changes[i].swap) ? { home:oM.away, away:oM.home, homeScore:oM.awayScore, awayScore:oM.homeScore }:oM;
      }
      selectedGroup.matches = newMatches;
      replace(selectedGroup.standings.matches = buildMatchTable("", selectedGroup.matches),editMatches);
      selectedGroup.standings.matches.id = tempMatches.id;
      selectedGroup.standings.matches.style.display = "";
      matchEdit.style.display = "";
      playing.rows[0].style.display = "";
      matchCancel.style.display = "none";
      matchSave.style.display = "none";
    };
    matchEdit.style.display = "none";
    playing.rows[0].style.display = "none";
    matchCancel.style.display = "";
    matchSave.style.display = "";
  };
  



function permutateMatches(matches){
	var baseMatches = matches.map(function(match){
		var result;
		if(typeof(match.homeScore) == 'undefined' || typeof(match.awayScore) == 'undefined')
			result = "?";
		else if(match.homeScore > match.awayScore)
			result = "H";
		else if(match.homeScore < match.awayScore)
			result = "A";
		else 
			result = "D";
		return result;
	});
	
	var permutations = [];
	var permutate = function(matchPerm){
		var unknownMatch = matchPerm.indexOf("?");
		if(unknownMatch < 0){
			permutations.push(matchPerm.slice());
		}else {
			matchPerm.splice(unknownMatch,1,"H");
			permutate(matchPerm.slice());
			matchPerm.splice(unknownMatch,1,"A");
			permutate(matchPerm.slice());
			matchPerm.splice(unknownMatch,1,"D");
			permutate(matchPerm.slice());
		}
	};
	permutate(baseMatches);
	return permutations.map(function(perm){
		var result = [];
		for(var i = 0; i < matches.length; ++i){
			result.push({home:matches[i].home, away:matches[i].away, result:perm[i]});
		}
		return result;
	});
}

function shallowStandings(matches){
	var standings = {};
	matches.forEach(function(match){
		if(!standings[match.home]) standings[match.home] = 0;
		if(!standings[match.away]) standings[match.away] = 0;
		switch(match.result){
			case "H": standings[match.home] += 3; break;
			case "A": standings[match.away] += 3; break;
			case "D": standings[match.home] += 1; 
			          standings[match.away] += 1; break;
		}
	});
	return standings;
}

function shallowRanks(points){
	var ranks = {};
	Object.keys(points).forEach(function(key){ 
      var count = 0;
      Object.keys(points).forEach(function(otherKey){ if(points[key] > points[otherKey]) count++; });
      ranks[key] = Object.keys(points).length - count;
    });
    return ranks;
}

function shallowStatus(ranks){
    var i,j,counts = [];
    for(i = 1; i <=Object.keys(ranks).length; ++i){
        counts[i] = 0;
      for(j = 0; j < Object.keys(ranks).length; ++j){
        if(ranks[Object.keys(ranks)[j]] == i) ++counts[i];
      }
    }
    var statuses = {};
    Object.keys(ranks).forEach(function(key){
      switch(ranks[key]){
        case 1: 
          if(counts[1] > 2)
            statuses[key] = "?";
          else
            statuses[key] = "A";
          break;
        case 2:
          if(counts[1] > 1)
            statuses[key] = "E";
          else if((counts[2] == 2 && counts[1] == 1) || counts[2] > 2)
            statuses[key] = "?";
          else
            statuses[key] = "A";
          break;
        case 3:
          if(counts[1] + counts[2] >= 2)
            statuses[key] = "E";
          else if(counts[3] > 1)
            statuses[key] = "?";
          else
            statuses[key] = "A";
          break;
        case 4:
          if(counts[1] + counts[2] + counts[3] >= 2)
            statuses[key] = "E";
          else if(counts[4] > 1)
            statuses[key] = "?";
          else
            statuses[key] = "A";
          break;
        case 5:
          if(counts[1] + counts[2] + counts[3] + counts[4] >= 2)
            statuses[key] = "E";
          else if(counts[5] > 1)
            statuses[key] = "?";
          else
            statuses[key] = "A";
      }
    });
    return statuses;
}

function getStatus(allStatuses,teams){
	var status = {};
	teams.forEach(function(team){ status[team] = ""; });
	allStatuses.forEach(function(statuses){
		teams.forEach(function(team){
			if(!status[team])
				status[team] = statuses[team];
			else if(status[team] != statuses[team])
				status[team] = "?";
		});
	});
	return status;
}
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="teamIcons.js"></script>
    <script type="text/javascript" src="teamEdit.js"></script>
    
  </head>
  <body>
  <table style="width:795px; border: 0px; border-spacing: 0; background:inherit; table-layout:fixed;">
    <thead></thead>
    <tbody id="teamsEdit">
        <tr>
            <th colspan="2" style="text-align:left; background:#EEEEEE; font-weight:normal; border-right:0px;">
                <!--input id="newTeam" type="button" value="New Team" /-->
            </th>
            <th colspan="2" style="text-align:right; background:#EEEEEE; font-weight:normal;">
                <form target="_self" style="display: inline;" action="index.html" >
                	<input id="teamSave" type="submit" value="Save Changes" />
                	<input id="teamCancel" type="submit" value="Cancel" />
                </form>
            </th>
        </tr>
        <tr><td colspan="4">
            <table id="teamsTable" class="table" style="border-spacing:0px;">
                <thead>
                    <tr><th colspan="10">Teams</th></tr>
                </thead>
                <tbody>
                    <tr></tr>
                </tbody>
            </table>
            </td></tr>
        <tr>
            <td colspan="4">
                <form id="teamForm" style="display:none; font-weight:bold;" action="javascript:void(0);">
                    Team:<b></b><br/>
                    Icon:<img style="position:relative; top:7px;"/> <input type="text" name="icon"/><br/>
                    <div style="display:none;">Logo:<input type="text" name="logo"/><br/></div>
                </form>
            </td>
        </tr>
    </tbody>
</table>
</body>
</html>
var teamsTable;
var teamForm;

var teamIcons;
var groupData;


var teamsEdited = {};
function loadData(){
  var dataString = window.localStorage.getItem("groupData");
  groupData = dataString ? JSON.parse(dataString) : {};
  var teamString = window.localStorage.getItem("teamData");
  if(teamString){
    teamIcons = JSON.parse(teamString);
  }
}
loadData();

function replace(New, Old){
    Old.parentNode.replaceChild(New, Old);
}

function getTeamIcon(team){
    var icon = document.createElement("img");
    if(!team){
        icon.src = "http://implyingrigged.info/w/images/thumb/c/cf/TBD_icon.png/25px-TBD_icon.png";
        return icon;
    }
    icon.src = teamIcons[team].icon;
    icon.alt = teamIcons[team].id.toUpperCase() + " icon.png";
    return icon;
}

function getTeamName(team){
  return (team == "s4s")? "[s4s]":"/"+team+"/";
}


window.onload = function() {
  teamsTable = document.getElementById("teamsTable");
  teamForm = document.getElementById("teamForm");
  
  teamsTable.onclick = function(event) {
    var target = event.target;
    target = target.tagName == "TD" ? target : target.parentNode;
    if (target.tagName != "TD") return;
    var key = target.dataset.id;
    if (teamForm.dataset.id)
    	for(var i = 0; i < teamForm.elements.length; ++i){
    		teamIcons[teamForm.dataset.id][teamForm.elements[i].name] = teamForm.elements[i].value  || teamIcons[teamForm.elements[i].name];
    	}
    teamForm.dataset.id = key;
    teamForm.querySelector("b").innerHTML = getTeamName(key);
    teamForm.icon.value = teamIcons[key].icon;
    teamForm.icon.size = teamIcons[key].icon.length;
    teamForm.querySelector("img").src = teamIcons[key].icon;
    teamForm.logo.value = teamIcons[key].logo;
    teamForm.icon.onkeypress();
    teamForm.logo.onkeypress();
    teamForm.style.display = "";
  };

  teamForm.icon.onkeypress = teamForm.icon.onkeydown = function() {
    var that = this;
    window.setTimeout(function() {
      that.style.width = "10em";
      window.getComputedStyle(that);
      that.style.width = (that.scrollWidth)+"px";
      teamsTable.querySelector("#team"+teamForm.dataset.id+" img").src = 
      that.parentNode.querySelector("img").src = that.value;
    }, 10);
  };
  
    teamForm.logo.onkeypress = teamForm.logo.onkeydown = function(){
    	var that = this;
        window.setTimeout(function(){
        	that.style.width = "10em";
        	window.getComputedStyle(that);
        	that.style.width = (that.scrollWidth)+"px";},10);
    };

  

  document.getElementById("teamSave").onclick = function() {
  	var id = teamForm.dataset.id;
    if (id)
    	for(var i = 0; i < teamForm.elements.length; ++i){
    		var name = teamForm.elements[i].name;
    		teamIcons[id][name] = teamForm.elements[i].value  || teamIcons[name];
    	}
    window.localStorage.setItem("teamData",JSON.stringify(teamIcons));
    
    
    //TODO: go back to other page
    //window.location.reload();
  };

  document.getElementById("teamCancel").onclick = function() {
    
    //TODO: go back to other page
    //window.location.reload();
  };
  
	
	
  (function () {
  	var i = 0;
    for (var key of Object.keys(teamIcons)) {
      var tr = teamsTable.tBodies[0].rows[teamsTable.tBodies[0].rows.length - 1];
      var td = (tr.cells.length >= 10) ? teamsTable.tBodies[0].insertRow().insertCell() : tr.insertCell();
      td.className = "team"+ (td.dataset.id = teamIcons[key].id);
      td.dataset.index = ++i + "";
      td.style.textAlign = "left";
      td.appendChild(getTeamIcon(key));
      td.appendChild(document.createElement("b")).innerHTML = getTeamName(teamIcons[key].id);
    }
   })();
};