function checkSupported() {
  document.getElementById('pause_game').style.display='none';
  canvas = document.getElementById('canvas');
  if (canvas.getContext){
    ctx = canvas.getContext('2d');
    this.gridSize = 10;
    start();
  } else {
    alert("SNAKE! DOES NOT WORK ON YOUR BROWSER");
  }
}

function start(){
  document.getElementById('play_game').style.display='inline';
  document.getElementById('game_over').style.display='none';
  prePlayComplete = false;
  ctx.clearRect(0,0, canvas.width, canvas.height);
  this.currentPosition = {'x':50, 'y':50};
  snakeBody = [];
  snakeLength = 3;
  updateScore();
  clearInterval(interval);
}

function prePlay(){
  snakeBtnsGone();
  makeFoodItem();
  drawSnake();
  direction = 'right';
  prePlayComplete = true;
  play();
}

function startTwo(){
  document.getElementById('game_over').style.display='none';
  ctx.clearRect(0,0, canvas.width, canvas.height);
  this.currentPosition = {'x':50, 'y':50};
  snakeBody = [];
  snakeLength = 3;
  updateScore();
  makeFoodItem();
  drawSnake();
  direction = 'right';
  play();
}

function restart(){
  pause();
  startTwo();
}

function pause(){
  document.getElementById('pause_game').style.display='inline';
  playInProgress = false;
  clearInterval(interval);
  allowPressKeys = false;
  
}

function play(){
  document.getElementById('play_game').style.display='none';
  document.getElementById('pause_game').style.display='none';
  playInProgress = true;
  interval = setInterval(moveSnake,100);
  allowPressKeys = true;
  
}

function drawSnake() {
  if (snakeBody.some(hasEatenItself)) {
    gameOver();
    return false;
  }
  snakeBody.push([currentPosition['x'], currentPosition['y']]);
  ctx.fillStyle = "rgb(237,240,248)";
  ctx.fillRect(currentPosition['x'], currentPosition['y'], gridSize, gridSize);
  if (snakeBody.length > snakeLength) {
    var itemToRemove = snakeBody.shift();
    ctx.clearRect(itemToRemove[0], itemToRemove[1], gridSize, gridSize);
  }
  if (currentPosition['x'] == suggestedPoint[0] && currentPosition['y'] == suggestedPoint[1]) {
    makeFoodItem();
    snakeLength += 1;
    updateScore();
  }
}

function leftPosition(){
 return currentPosition['x'] - gridSize;
}

function rightPosition(){
  return currentPosition['x'] + gridSize;
}

function upPosition(){
  return currentPosition['y'] - gridSize;
}

function downPosition(){
  return currentPosition['y'] + gridSize;
}

function whichWayToGo(axisType){
  if (axisType=='x') {
    a = (currentPosition['x'] > canvas.width / 2) ? moveLeft() : moveRight();
  } else {
    a = (currentPosition['y'] > canvas.height / 2) ? moveUp() : moveDown();
  }
}

function moveUp(){
  if (upPosition() >= 0) {
    executeMove('up', 'y', upPosition());
  } else {
    whichWayToGo('x');
  }
}

function moveDown(){
  if (downPosition() < canvas.height) {
    executeMove('down', 'y', downPosition());
  } else {
    whichWayToGo('x');
  }
}

function moveLeft(){
  if (leftPosition() >= 0) {
    executeMove('left', 'x', leftPosition());
  } else {
    whichWayToGo('y');
  }
}

function moveRight(){
  if (rightPosition() < canvas.width) {
    executeMove('right', 'x', rightPosition());
  } else {
    whichWayToGo('y');
  }
}

function executeMove(dirValue, axisType, axisValue) {
  direction = dirValue;
  currentPosition[axisType] = axisValue;
  drawSnake();
}

function makeFoodItem(){
  suggestedPoint = [Math.floor(Math.random()*(canvas.width/gridSize))*gridSize, Math.floor(Math.random()*(canvas.height/gridSize))*gridSize];
  if (snakeBody.some(hasPoint)) {
    makeFoodItem();
  } else {
    ctx.fillStyle = "rgb(237,240,248)";
    ctx.fillRect(suggestedPoint[0], suggestedPoint[1], gridSize, gridSize);
  };
}

function hasPoint(element, index, array) {
  return (element[0] == suggestedPoint[0] && element[1] == suggestedPoint[1]);
}

function hasEatenItself(element, index, array) {
  return (element[0] == currentPosition['x'] && element[1] == currentPosition['y']);
}

function gameOver(){
  var score = (snakeLength - 3)*10;
  gameOverScore();
  ctx.clearRect(0,0, canvas.width, canvas.height);
  document.getElementById('play_menu').style.display='none';
  document.getElementById('restart_menu').style.display='block';
  document.getElementById('play_game').style.display='inline';
}

function gameOverScore(){
  document.getElementById('game_over').style.display='inline';
  playInProgress = false;
  clearInterval(interval);
  allowPressKeys = false;
  
}

function updateScore(){
  var score = (snakeLength - 3)*10
  document.getElementById('score').innerHTML = score;
  document.getElementById('final_score').innerHTML = score;
}

document.onkeydown = function(event) {
  var keyCode;
  if(event == null)
  {
    keyCode = window.event.keyCode;
  }
  else
  {
    keyCode = event.keyCode;
  }

  	switch(keyCode)
  {
	case 32:
		if (playInProgress == true){
			pause();
		}else{
			play();
		}
	break;
		
	case 13:
	    if (prePlayComplete != true){
	    	prePlay();
	    }else{
	    	restart();
	    }
    break;

	case 81:
	   	main();
		checkSupported();
    break;
  }

if (!allowPressKeys){
    return null;
  }
 
  switch(keyCode)
  {
    case 37:
      if (direction != "right"){
        moveLeft();
      }
      break;
     
    case 38:
      if (direction != "down"){
        moveUp();
      }
      break;
      
    case 39:
      if (direction != "left"){
        moveRight();
      }
      break;
    
    case 40:
      if (direction != "up"){
        moveDown();
      }
      break;
    
    default:
      break;
  }
}

function moveSnake(){
  switch(direction){
    case 'up':
      moveUp();
      break;

    case 'down':
      moveDown();
      break;
      
    case 'left':
      moveLeft();
      break;

    case 'right':
      moveRight();
      break;
  }
}

var http = false;
var loader

if(navigator.appName == "Microsoft Internet Explorer") {
  http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  http = new XMLHttpRequest();
}

function replaceTerminal(loader) {
  http.open("GET", loader, true);
	display = "";
	http.onreadystatechange=function() {
    if(http.readyState == 4) {
      document.getElementById('terminal_root').innerHTML = http.responseText;
			}
  }
  http.send(null);
}
