var square = -204;
var cheat = 0;

function check() {
  var r = 0;
  for (i=0; i<81; i++) {
    if (grid[i]==guess[i]) r++;
  }
  if (r==81) {
    if (cheat==0) alert("Correct!");
    else alert("Cheat!");
  }
  else alert("Sorry, you have some numbers wrong");
}

function wipe() {
  if (confirm("Clear all squares?")) {
    cheat = 0;
    var n = 0;
    var p;
    for (i=0; i<81; i++) {
      if (i!=clues[n]) {
        p = "p"+i;
        document.getElementById(p).firstChild.nodeValue = " ";
        guess[i] = 0;
      }
      else {
        if (n<(clues.length-1)) {
          n++;
        }
      }
    }
  }
}

function select(x) {
  var d;
  if (square!=-204) {
    d = "d"+square;
    document.getElementById(d).style.backgroundColor = "transparent";
  }
  if (x==-204) x = 0;
  d = "d"+x;
  document.getElementById(d).style.backgroundColor = "#FAEDD3";
  square = x;
}

function getKey(e) {
  var p = "p"+square;
  if (e.keyCode) keycode=e.keyCode;
  else keycode=e.which;
  if (keycode==47 && square!=-204) {
    document.getElementById(p).firstChild.nodeValue = " ";
    guess[square] = 0;
  }
  if (keycode>48 && keycode<58 && square!=-204) {
    document.getElementById(p).firstChild.nodeValue = keycode-48;
    guess[square] = keycode-48;
  }
}

function save() {
  var c = "su" + su + "=";
  var n = 0;
  for (i=0; i<81; i++) {
    if (i!=clues[n]) {
      c += guess[i];
    }
    else {
      if (n<(clues.length-1)) {
        n++;
      }
    }
  }
  var expires = new Date();
  expires.setTime(expires.getTime() + 30 * 24 * 60 * 60 * 1000);
  c += ";expires="+expires+";path=/";
  document.cookie = c;
  alert("Grid Saved");
}
function load() {
  if (document.cookie != "") {
    var c = unescape(document.cookie);
    var cArray = c.split("; ");
    var sun = "su"+su+"=";
    var spos = -1;
    for (i=0; i<cArray.length; i++) {
      if (cArray[i].indexOf(sun)==0) spos = i;
    }
    if (spos != -1) {
      c = cArray[spos].split("=")[1];
      var p;
      var j = 0;
      var n = 0;
      for (i=0; i<81; i++) {
        if (i!=clues[n]) {
          guess[i] = c.charAt(j);
          p = "p"+i;
          document.getElementById(p).firstChild.nodeValue = (c.charAt(j)==0) ? " " : c.charAt(j);
          j++;
        }
        else {
          if (n<(clues.length-1)) {
            n++;
          }
        }
      }
      alert("Grid Loaded");
    }
  }
}
function answer() {
  cheat = 1;
  document.location = document.location.protocol + "//" + document.location.hostname + document.location.pathname + "#answer";
  var p;
  var n = 0;
  for (i=0; i<81; i++) {
    if (i!=clues[n]) {
      p = "p"+i;
      document.getElementById(p).firstChild.nodeValue = grid[i];
      guess[i] = grid[i];
    }
    else {
      if (n<(clues.length-1)) {
        n++;
      }
    }
  }
}