function setup() {
  query = window.location.href.split('?')[1] || "";
  elts = document.getElementsByTagName("input");
  for (i = 0; i < elts.length; i++) {
    elt = elts[i];
    state = query[i];
    
    span = document.createElement("span");
    span.setAttribute("onclick", "doClick(this, event)");
    newElt = elt.cloneNode(true);
    newElt.checked = (state == 1);
    span.appendChild(newElt);
    doDisable(newElt, (state == 2));
    elt.parentNode.replaceChild(span, elt);
  }
}

function doClick(box, event) {
  check = box.firstChild;
  checkClick(check, event);
  coords = check.id.split(' ');
  boxCoords = coords[0].split('-'); checkCoords = coords[1].split('-');
  boxX = boxCoords[0]; boxY = boxCoords[1];
  checkX = checkCoords[0]; checkY = checkCoords[1];
  // flip coords
  boxCoords = boxY + "-" + boxX;
  checkCoords = checkY + "-" + checkX;
  coords = boxCoords + " " + checkCoords;
  elt = document.getElementById(coords);
  elt.checked = !elt.checked;
  checkClick(elt, event);
  updateURL();
}

function checkClick(check, event) {
  if (event.metaKey) {
    doDisable(check, ! check.disabled);
    check.checked = false;
  } else {
    coords = check.id.split(' ');
    boxCoords = coords[0];
    checkCoords = coords[1].split('-');
    x = Number(checkCoords[0]);
    y = Number(checkCoords[1]);
    function toggleChecks(elt) {
      if (check.checked) {
        if (elt.disabled == false) {
          doDisable(elt, true);
          elt.setAttribute("auto", "yes");
        }
      } else if (elt.getAttribute("auto") != "no") {
        doDisable(elt, false);
        elt.setAttribute("auto", "no");
      }
    }
    for (xx = 0; xx < 5; xx++) {
      if (xx != x) {
        elt = document.getElementById(boxCoords + " " + xx.toString() + "-" + y.toString());
        toggleChecks(elt);
      }
    }
    for (yy = 0; yy < 5; yy++) {
      if (yy != y) {
        elt = document.getElementById(boxCoords + " " + x.toString() + "-" + yy.toString());
        toggleChecks(elt);
      }
    }
  }
}

function updateURL() {
  elt = document.getElementById("url");
  elt.setAttribute("href", "?" + calculateQueryString());
}

function calculateQueryString() {
  query = "";
  elts = document.getElementsByTagName("input");
  for (i = 0; i < elts.length; i++) {
    elt = elts[i];
    query += (elt.disabled ? 2 : elt.checked ? 1 : 0);
  }
  return query;
}

function doDisable(elt, bool) {
  elt.disabled = bool;
  span = elt.parentNode;
  span.style["background-color"] = (bool ? "#333" : "");
}
