// Contains functions related to story voting.

// Dispatches a request to vote for a story in the specified manner.
function vote(storyID, voteType)
{
  request = getRequest();
  if (request != null)
  {
    request.onreadystatechange = handleVoteResponse;
    request.open("GET", "/vote?id=" + storyID + "&type=" + voteType, true);
    request.send(null);
  }
  else
  {
    alert('Your browser is really old or doesn\'t support javascript.');
  }
}

// Handles the response to a story vote request.
function handleVoteResponse()
{
  if (request.readyState == 4)
  {
    response = request.responseText;

    // proceed only if the request didn't return an error
    if (response.search(/error/i) == -1)
    {
      // get the response parameters
      responseData = response.split(",")
      storyID = responseData[0]
      voteTypeDisplayText = responseData[1]
      newScore = responseData[2]

      // set the story's new score
      scoreText = document.getElementById(storyID + "-score");
      scoreText.innerHTML = newScore;

      // hide the vote buttons
      voteUpButton = document.getElementById(storyID + "-voteup");
      voteUpButton.setAttribute("class", "hidden");
      voteUpButton.setAttribute("className", "hidden");
      voteDownButton = document.getElementById(storyID + "-votedown");
      voteDownButton.setAttribute("class", "hidden");
      voteDownButton.setAttribute("className", "hidden");

      // show the score box's top and bottom lines
      scoreBoxTop = document.getElementById(storyID + "-scoreboxtop");
      scoreBoxTop.setAttribute("class", "score-box-top")
      scoreBoxTop.setAttribute("className", "score-box-top")
      scoreBoxBottom = document.getElementById(storyID + "-scoreboxbottom");
      scoreBoxBottom.setAttribute("class", "score-box-bottom")
      scoreBoxBottom.setAttribute("className", "score-box-bottom")

      // show the vote indicator
      voteIndicatorBlock = document.getElementById(storyID + "-voteindicatorblock");
      voteIndicatorBlock.setAttribute("class", "vote-ind-block");
      voteIndicatorBlock.setAttribute("className", "vote-ind-block");
      voteIndicatorLabel = document.getElementById(storyID + "-voteindicatortext");
      voteIndicatorLabel.innerHTML = voteTypeDisplayText;
    }
    else
    {
      // TODO: this is an error. log it?
    }
  }
}
