// Copyright Robin Harvey.
$(document).ready(function () {
    Grid.init();
});


var Grid = {
    cells : [],

    cellNo : 0,

    numCells : 0,

    scoreboard: null,

    snakeClass: 'rbg-wapl',

    init: function () {
        this.X = 0;
        this.Y = 0;
        $('#gameboard tr').each(function () {
            Grid.Y += 1;
            Grid.X = 0;
            var tds = (Grid.Y % 2) == 0
                ? $($('td', this).get().reverse())
                : $('td', this);
            tds.each(Grid.addCell);
        });
        $('#playbtn').click(this.play);
        this.scoreboard = $("#scoreboard");
        this.numCells = this.cells.length;
        this.showArticle();
    },

    addCell: function (td) {
        Grid.X += 1;
        Grid.cells.push([Grid.X, Grid.Y, $(this), $(this).attr('class')]);
    },

    play: function () {
        var dice = Math.floor(Math.random() * 6) + 1;
        var score = 'Move ' + dice.toString() + ' places';

        if (Math.random() > 0.5) {
            dice = dice * -1;
            score = score + ' backwards';
        }

        if (dice + Grid.cellNo >= Grid.numCells || dice + Grid.cellNo < 0) {
            Grid.writeScore("You threw a " + dice.toString() + " - please try again.");
            return;
        }
        var newPosn = Grid.cellNo + dice;
        if (Grid.cellNo != 0) {
            Grid.cells[Grid.cellNo][2].addClass(Grid.cells[Grid.cellNo][3]);
        }
        Grid.cells[newPosn][2].removeClass(Grid.cells[newPosn][3]);

        if (newPosn == Grid.numCells - 1) {
            Grid.writeScore("You win!!");
        } else {
            Grid.writeScore(score);
        }
        Grid.cellNo = newPosn;
        Grid.showArticle();

        if (Grid.cells[newPosn][3] == Grid.snakeClass) {
            setTimeout(Grid.returnToHome, 2000);
        }
    },

    writeScore: function (score) {
        this.scoreboard.text(score);
    },

    showArticle: function () {
        var toShow = Grid.cellNo + 1;
        $('#cell-content div').css('z-index', 0);
        $('#cell-content div').hide();
        $('#cell-' + toShow.toString() + '-content').css('z-index', 1);
        $('#cell-' + toShow.toString() + '-content').show("slow");
    },

    returnToHome: function () {
        if (Grid.cellNo != 0) {
            Grid.cells[Grid.cellNo][2].addClass(Grid.cells[Grid.cellNo][3]);
        }
        Grid.cellNo = 0;
        Grid.showArticle();
    }
}
