var STEP = 50;
var PLAYGROUND_HEIGHT = 8 * STEP;
var PLAYGROUND_WIDTH = 12 * STEP;
var LEFT = 65
var RIGHT = 68;
var UP = 87;
var DOWN = 83;

var Player = function (node) {
    this.node = node;

    this.moveFunction = function (axis, step, max) {
        return function () {
            var nextPos = parseInt(this.node.css(axis)) + step;
            if (nextPos >= 0 && nextPos < max) {
                this.node.css(axis, "" + nextPos + "px");
            }
        }
    }
    
    this.left = this.moveFunction("left", -STEP, PLAYGROUND_WIDTH);
    this.right = this.moveFunction("left", STEP, PLAYGROUND_WIDTH);
    this.up = this.moveFunction("top", -STEP, PLAYGROUND_HEIGHT);
    this.down = this.moveFunction("top", STEP, PLAYGROUND_HEIGHT);

    return true;
}
    
$(document).ready(function () {
    var floorAnimation = new Animation({imageURL: "sand.jpg"});
    var playerAnimation = new Animation({imageURL: "person.gif"});
        
    $().playground("#playground", {height: PLAYGROUND_HEIGHT, width: PLAYGROUND_WIDTH, keyTracker: true})
        .addGroup("background", {height: PLAYGROUND_HEIGHT, width: PLAYGROUND_WIDTH}).end()
        .addGroup("map", {height: PLAYGROUND_HEIGHT, width: PLAYGROUND_WIDTH}).end()
        .addGroup("characters", {height: PLAYGROUND_HEIGHT, width: PLAYGROUND_WIDTH});

    $("#background").addSprite("floor", {animation: floorAnimation, height: PLAYGROUND_HEIGHT, width: PLAYGROUND_WIDTH});
    $("#characters").addSprite("player", {animation: playerAnimation, posy: PLAYGROUND_HEIGHT / 2, posx: PLAYGROUND_WIDTH / 2, height: STEP, width: STEP});

    var player = new Player($("#player"));

    $(document).keydown(function (event) {
        switch (event.keyCode) {
        case LEFT:
            player.left();
            break;
        case RIGHT:
            player.right();
            break;
        case UP:
            player.up();
            break;
        case DOWN:
            player.down();
            break;
        }
    });
        
    $().playground().startGame();
});
