function addWordToList() {
  var new_word = $("#new_word").val().toLowerCase();

  if (new_word.length < 3) {
    $.jGrowl("Words should be at least 3 characters!",
             {life: 2000});
    $("#new_word").css("border", "thin solid red");
    $("#new_word").val("");
    return;
  }

  // make sure word has not already been entered
  if (words.indexOf(new_word) != -1) {
    $.jGrowl("You have already entered this word. Try again!",
             {life: 2000});
    $("#new_word").css("border", "thin solid red");
    $("#new_word").val("");
    return;
  }

  if (!existsOnBoard(new_word)) {
    $.jGrowl("This word is not on the board!",
             {life: 2000});
    $("#new_word").css("border", "thin solid red");
    $("#new_word").val("");
    return;
  }

  words.push(new_word);
  $("#input_words p").append(new_word + ", ");
  $("#new_word").val("");
}

function initialize() {
  // initially the board should have *s till the user starts the timer.
  showBoard = false;
  renderBoard();
  $("#game_counter").countdown({until: 180, format: 'S', onExpiry: gameOver});
  $("#game_counter").countdown('pause');
}

function startGame() {
  $("#startgame").remove();
  $("#add_word").css("display", "block");
  $("#input_words").css("display", "block");

  // we can show the board now.
  showBoard = true;
  renderBoard();
  $.hotkeys.add('Ctrl+Right', rotateClockWise);
  $.hotkeys.add('Ctrl+Left', rotateCounterClockWise);
  $.hotkeys.add('Ctrl+f', function(){$("#new_word").focus();});

  $("#game_counter").countdown('resume');
  $("#new_word").focus();
  $("#new_word").keypress(function(e) {
    if(e.which == 13) {
      addWordToList();
    }
  });
}

function setMeaning(link, word) {
  if (link.title == '') {
    // This is the only case where we need to do something!
    $.ajax({url: "/meaning?word=" + word,
            cache: false,
            success: function(html) {
              link.title = html;
            }
        });
  }
}

function getWordHtml(r) {
    return '<span><a title="" rel="external" href="http://www.google.com/search?q=define%3A' + r[0] + '" class="' + r[1] + '" onMouseOver="setMeaning(this, \'' + r[0] + '\');setWordHighlight(\'' + r[0] + '\');" onMouseOut="unsetWordHighlight();">' + r[0] + '</a></span> ';
}

function showResults(results) {
  var score = 0;
  $("#results").empty();
  $("#results").append("<h2>Results</h2>");
  for(i = 0; i < results.length; i++) {
      $("#results").append(getWordHtml(results[i]));
    score += results[i][2];
  }
  $("#game_counter").countdown('destroy');
  $("#add_word").remove();
  $("#score").append("<h3>Your final score was " + score + "</h3>");
  $("a[rel='external']").attr("target", "_blank");
}

function gameOver() {
  $("#results").html('<img src="/static/images/spinner.gif"/>');
  $.post("/getscore", 
         {'words': words,
           'user_email': user_email, 
           'board': lower_case_board
         }, 
         showResults, "json");
}

function renderBoard() {
  $("#board").empty();
  for(var i = 0; i < ROWS; i++) {
    var row = "<tr>";
    for(var j = 0; j < COLS; j++) {
        idx = currRotationMatrix[i * COLS + j];
        var cell;
        if (showBoard)
          cell = board[idx];
        else
          cell = "x";
        td = '<td class="regular" id="board_id_' + idx + '">' + cell + '</td>';
        row = row + td;
    }
    row = row + "</tr>";
    $("#board").append(row);
  }
}

function rotateClockWise() {
    newMat = currRotationMatrix.slice();
    for (var i = 0; i < ROWS * COLS; i++) {
        var col = i % COLS;
        var row = (i - col) / COLS;
        newMat[i] = currRotationMatrix[(COLS - col - 1) * COLS + row];
    }
    currRotationMatrix = newMat.slice();
    renderBoard();
}

function rotateCounterClockWise() {
    newMat = currRotationMatrix.slice();
    for (var i = 0; i < ROWS * COLS; i++) {
        var col = i % COLS;
        var row = (i - col) / COLS;
        newMat[i] = currRotationMatrix[col * COLS + COLS - row - 1];
    }
    currRotationMatrix = newMat.slice();
    renderBoard();
}

function updateHighlights() {
  for(var i = 0; i < ROWS; i++) {
    for(var j = 0; j < COLS; j++) {
      var idx = currRotationMatrix[i * COLS + j];
      if(highlights[idx] == 1)
        $('#board_id_' + idx).attr("class", "highlighted");
      else
        $('#board_id_' + idx).attr("class", "regular");
    }
  }
}

function setWordHighlight(word) {
    initHighlights();
    var path = findWord(word);
    for (var i = 0; i < path.length; i++) {
        highlights[path[i]] = 1;
    }
    updateHighlights();
}

function unsetWordHighlight() {
    initHighlights();
    updateHighlights();
}
