enchant();
var stageHeight = 320;
var stageWidth = 320;
var moveSpeed = 5;
var player;

//Gem Class
Gem = Class.create(Sprite, {
    initialize: function() {
        Sprite.call(this, 16, 16);
        this.image = game.assets['diamond.png'];
        this.x = Math.random() * stageWidth;
        this.y = 0;
        if (this.y <= 50) {
            this.y = 50;
        }
        this.frame = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5];
    },

    onenterframe: function() {

        this.y += 5;
        if (this.within(player, 15)) {
            //09.3 Add Sound Effect
            
            game.score++;
            this.scene.removeChild(this);
        }

        if (this.x >= stageHeight) {
            this.scene.removeChild(this);
        }
    }
});

Player = Class.create(Sprite, {
    initialize: function() {
        Sprite.call(this, 32, 32);
        this.image = game.assets['space3.png'];
        this.x = stageWidth / 2;
        this.y = stageHeight / 2;
        this.frame = 15;
        this.countDown = 0;
        this.health = 5;
        this.tx = this.x;
        this.ty = this.y;
    },

    onenterframe: function() {

        if (this.countDown > 0) {
            this.frame = 18;
            this.countDown--;
            if (this.age % 2 === 0) {
                this.opacity = 0;
            } else {
                this.opacity = 1;
            }
        } else {
            this.opacity = 1;
            this.frame = 15;

            this.x += (this.tx - this.x) / 4;
            this.y += (this.ty - this.y) / 4;
        }
    }
});


window.onload = function() {
    game = new Game(stageHeight, stageWidth);
    //09.2 Preloader
    game.preload('icon0.png', 'bg.png', 'space3.png', 'diamond.png');
    game.onload = function() {

        //09.2 Play BGM
        
        var bg = new Sprite(stageHeight, stageWidth);
        bg.image = game.assets['bg.png'];
        game.rootScene.addChild(bg);
        game.score = 0;

        player = new Player();
        game.rootScene.addChild(player);

        var scoreLabel = new Label("Score: " + game.score);
        scoreLabel.color = "white";
        scoreLabel.addEventListener('enterframe', function() {
            this.text = "Score: " + game.score;
        });
        game.rootScene.addChild(scoreLabel);

        game.rootScene.addEventListener('enterframe', function() {
            if (bg.age % 15 === 0) {
                var p = new Gem();
                game.rootScene.addChild(p);
            }
        });

        game.rootScene.addEventListener('touchend', function(e) {
            player.tx = e.x - 16;
            player.ty = e.y - 16;
        });
    }
    game.start();
}