var connection,
    main = document.querySelector('main > div');


keyListener = function(){
	document.addEventListener('keydown',function(e){
	    switch(e.keyCode){
	        case 37:
	            connection.send("left");
	            break;
	        case 39:
	            connection.send("right");
	            break;
	        case 38:
	            connection.send("up");
	            break;
	        case 40:
	            connection.send("down");
	            break;
	    };
	});	
}

window.addEventListener("load", function () {
	var nickname = "Controller:";
	if (nickname) {
		// node || Tessel
		//_host = location.href.indexOf("localhost") === -1 ? location.href : "localhost";
		_host = "192.168.15.109";
		connection = new WebSocket("ws://" + _host + ":8081");
		connection.onopen = function () {
			console.log("Connection opened");	
			keyListener();
		}
		connection.onclose = function () {
			console.log("Connection closed")
		}
		connection.onerror = function () {
			console.error("Connection error")
		}
		connection.onmessage = function (event) {
			// var div = document.createElement("div")
			main.textContent = event.data
			// main.appendChild(div)
            console.log(main.textContent);
		}
	}
}) 