var player = {x: 0, y: 0};
var currentMaze = null;

function Maze(size)
{
    this.size = size;
    this.goal = {x: tc[size][0], y: tc[size][1]};
    var tablewall = tc[size][2];
    var table = document.createElement('table');
    this.cells = [];
    var wallIndex = 0;
    for (var y = 0; y <= size; y++) {
        var tr = document.createElement('tr');
        var row = [];
        for (var x = 0; x <= size; x++) {
            var wall = tablewall.substr(wallIndex, 1);
            var td = document.createElement('td');
            td.wallRight = wall == 6 || wall == 3;
            td.wallBottom = wall == 2 || wall == 3;
            td.style.borderRightStyle = td.wallRight ? 'solid' : 'none';
            td.style.borderBottomStyle = td.wallBottom ? 'solid' : 'none';
            if (x == this.goal.x && y == this.goal.y) td.className = 'goal';
            tr.appendChild(td);
            row.push(td);
            wallIndex++;
        }
        table.appendChild(tr);
        this.cells.push(row);
    }
    var bdy = document.getElementById('bdy');
    while (bdy.hasChildNodes()) bdy.removeChild(bdy.firstChild);
    var h1 = document.createElement('h1');
    var str = document.createTextNode('Labyrint - bane ' + size);
    h1.appendChild(str);
    bdy.appendChild(h1);
    bdy.appendChild(table);
    this.makePlayer();
}

Maze.prototype.move = function Maze_move(keyCode)
{
    this.cells[player.y][player.x].className = '';
    if (keyCode == 38 && player.y > 0 && !this.cells[player.y - 1][player.x].wallBottom) player.y--; //up
    if (keyCode == 37 && player.x > 0 && !this.cells[player.y][player.x - 1].wallRight) player.x--; //left
    if (keyCode == 40 && !this.cells[player.y][player.x].wallBottom) player.y++; //down
    if (keyCode == 39 && !this.cells[player.y][player.x].wallRight) player.x++; //right
    this.makePlayer();
}

Maze.prototype.makePlayer = function Maze_makePlayer()
{
    this.cells[player.y][player.x].className = 'player';
    if (player.x == this.goal.x && player.y == this.goal.y) {
        if (tc.length == this.size + 1)
            alert("D U   V A N D T   ! !\nT I L L Y K K E   ! ! !\nDu har fuldført alle baner!");
        else
            currentMaze = new Maze(this.size + 1);
    }
}

var hideWalls = false;
var hideGoal = false
function showHide(what)
{
    if (what == 'walls') hideWalls = !hideWalls;
    if (what == 'goal') hideGoal = !hideGoal;
    var classNames = [];
    if (hideWalls) classNames.push('hidewalls');
    if (hideGoal) classNames.push('hidegoal');
    document.getElementById('bdy').className=document.getElementById('bdy').className = classNames.join(' ');
}

window.onload = function () { currentMaze = new Maze(0); };
document.onkeydown = function (e) { if(!e) e = event; currentMaze.move(e.keyCode) };

