document.onkeyup = KeyCheck;

function KeyCheck(e){
   var KeyID = (window.event) ? event.keyCode : e.keyCode;

   switch(KeyID){

	  case 65: Left(); //Left arrow
      break;

      case 87: Up();//Arrow Up
      break;

      case 68: Right();//Right arrow
      break;

      case 83: Down();//Arrow Down
      break;
   }
}

function Up(){//look up
fx='up';
oldLoc=charLoc().split(",");
x=oldLoc[0];
y=oldLoc[1]-1;
boxY=y-1;
newLoc=x+','+y;
boxLoc=x+','+boxY;
testAndSet();
}

function Down(){//look down
fx='down';
oldLoc=charLoc().split(",");
x=oldLoc[0];
y=oldLoc[1]-0+1;
boxY=oldLoc[1]-0+2;
newLoc=x+','+y;
boxLoc=x+','+boxY;
testAndSet();
}

function Left(){//look left
fx='left';
oldLoc=charLoc().split(",");
x=oldLoc[0]-1;
y=oldLoc[1];
boxX=oldLoc[0]-2;
newLoc=x+','+y;
boxLoc=boxX+','+y;
testAndSet();
}

function Right(){//look right
fx='right';
oldLoc=charLoc().split(",");
x=oldLoc[0]-0+1;
y=oldLoc[1];
boxX=oldLoc[0]-0+2;
newLoc=x+','+y;
boxLoc=boxX+','+y;
testAndSet();
}

function setChar(){
if(fx=='up'){playerImg='images/pu.png';
if(isTarget(newLoc)){playerImg='images/puT.png';}
}

if(fx=='down'){playerImg='images/pd.png';
if(isTarget(newLoc)){playerImg='images/pdT.png';}
}

if(fx=='left'){playerImg='images/pl.png';
if(isTarget(newLoc)){playerImg='images/plT.png';}
}

if(fx=='right'){playerImg='images/pr.png';
if(isTarget(newLoc)){playerImg='images/prT.png';}
}
}

function set(){
moves++;
setChar();
document.getElementById(newLoc).src=playerImg;
document.getElementById(newLoc).alt="player";
document.getElementById(oldLoc).src=emptyImg;
document.getElementById(oldLoc).alt="empty";
addTargets();
document.getElementById('counter').innerHTML='Moves: ' + moves + '<br>Pushes: ' + pushes;
}

function testAndSet(){
if(document.getElementById(newLoc).alt=='box' && openSquare(boxLoc)){pushes++;set();moveTo(boxLoc);}
else if(openSquare(newLoc)){set();}
}