Game1.Game1 = function (game) {
    var map;
    var tileset;
    var layer;
    var layer0;
    var layer1;
    var player;
    var facing = 'left';
    var jumpTimer = 0;
    var cursors;
    var jumpButton;
    var bg;
    var TotalScore;
    var lettersCollected;
    var str;
    var life;
    var arraySamogloski;
    var walking = Phaser.Sound;
    var GameState = 0;
    var lektor = Phaser.Sound;
    var applause = Phaser.Sound;
    var gameEnd = false;
};
function isPlaying(audelem) {
    return !audelem.paused; }
Game1.Game1.prototype = {
    create: function () {
    
      lektor = new Audio("./sound/MW_g_I_4.mp3");
    lektor.load();    
      walking = new Audio("./sound/walk.mp3");
        walking.load();
      applause = new Audio("./sound/applause.mp3");
        
        this.time.advancedTiming = true;
        var facing = 'left';
        var jumpTimer = 0;
        var cursors;
        var jumpButton;
        var bg;
        var ispaused = false;
        var left = false;
        var right = false;
        var jump = false;
        var ButtonDown = false;
        this.life = 3.0;

        arraySamogloski = ["A", "E", "I", "O", "Ó", "U", "Y", "Ą", "Ę"];
        gameEnd = false;
        lettersCollected = new Array();
        TotalScore = 0;
        str = new String();
        this.physics.startSystem(Phaser.Physics.ARCADE);

        this.stage.backgroundColor = '#ffffff';

        this.load.tilemap('level1', '', level1, Phaser.Tilemap.TILED_JSON);
        map = this.add.tilemap('level1');

        map.addTilesetImage('tiles-1');

        map.setCollisionByExclusion([]);

        layer = map.createLayer('BG1', 1920, 1080);
        layer0 = map.createLayer('BG2', 1920, 1080);
        layer1 = map.createLayer('BG3', 1920, 1080);
        layer2 = map.createLayer('kolizje', 1920,1080);

        map.setCollisionBetween(1, 100, true, 'kolizje', true);
        //  Un-comment this on to see the collision tiles
        layer.resizeWorld();
        layer0.resizeWorld();
        layer1.resizeWorld();
        layer2.resizeWorld();

        player = this.add.sprite(20, 20, 'gracz');
        this.physics.enable(player, Phaser.Physics.ARCADE);
        player.body.collideWorldBounds = true;
        player.body.setSize(32, 64, 16, 0);

        player.animations.add('left', [9, 10, 11], 10, true);
        player.animations.add('right', [8, 7, 6], 10, true);
        player.animations.add('down', [0, 1, 2], 10, true);
        player.animations.add('up', [3, 4, 5], 10, true);
        player.animations.add('turn', [1], 10, true)


       // layer1.debug = true;
        //player.debug = true;
       // this.game.camera.follow(player);
        this.createItems();
        //this.game.camera.unfollow();
        //this.game.camera.follow(player, Phaser.Camera.FOLLOW_PLATFORMER);
        this.cursors = this.input.keyboard.createCursorKeys();
        this.jumpButton = this.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        this.left = false;
        this.right = false;
        this.jump = false;
        this.ButtonDown = false;
        this.gui = this.game.add.sprite(8 / 2, 847 / 2, 'guiBg')
        this.gui.scale.setTo(0.5, 0.5);
        this.gui.fixedToCamera = true;
        this.guihelp = this.game.add.sprite(1686 / 2, 900 / 2, 'helpButton', 0);
        this.guihelp.scale.setTo(0.5, 0.5);
        this.guihelp.fixedToCamera = true;
        this.guihelp.inputEnabled = true;
        this.guihelp.name = "help";
        this.guihelp.events.onInputOver.add(this.over, this);
        this.guihelp.events.onInputOut.add(this.out, this);
        this.guihelp.events.onInputDown.add(this.down, this);
        this.guihelp.events.onInputUp.add(this.up, this);
        this.text = this.game.add.text(700 / 2, 917 / 2, "Znalezione liczby:", {
            font: "48px Arial",
            fill: "#ffffff",
            align: "center",

        });
        this.text.setShadow(3, 3, 'rgba(0,0,0,0.5)', 5);
        this.text.scale.setTo(0.5, 0.5);
        this.text.fixedToCamera = true;
        this.text.setShadow(3, 3, 'rgba(0,0,0,0.5)', 5);
        this.text = this.game.add.text(300 / 2, 970 / 2, "", {
            font: "48px Arial",
            fill: "#ffffff",
            align: "center",

        });
        this.text.setShadow(3, 3, 'rgba(0,0,0,0.5)', 5);
        this.text.scale.setTo(0.5, 0.5);
        this.text.fixedToCamera = true;
        //this.gui.fixedToCamera = true;
        //this.gui.anchor.setTo(0.5, 0.5);
       // this.gui.scale.setTo(0.5, 0.5);
        this.buttonUp = this.game.add.sprite(116 / 2, 871 / 2, 'cursor_up', 0); //game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame
        this.buttonUp.name = "up";
        this.buttonUp.fixedToCamera = true; //our buttons should stay on the same place
        this.buttonUp.inputEnabled = true;
        this.buttonUp.events.onInputOver.add(this.over, this);
        this.buttonUp.events.onInputOut.add(this.out, this);
        this.buttonUp.events.onInputDown.add(this.down, this);
        this.buttonUp.events.onInputUp.add(this.up, this);

        this.buttonDown = this.game.add.sprite(116 / 2, 996 / 2, 'cursor_down', 0); //game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame
        this.buttonDown.name = "down";
        this.buttonDown.fixedToCamera = true; //our buttons should stay on the same place
        this.buttonDown.inputEnabled = true;
        this.buttonDown.events.onInputOver.add(this.over, this);
        this.buttonDown.events.onInputOut.add(this.out, this);
        this.buttonDown.events.onInputDown.add(this.down, this);
        this.buttonDown.events.onInputUp.add(this.up, this);

        this.buttonLeft = this.game.add.sprite(52 / 2, 934 / 2, 'cursor_left', 0);
        this.buttonLeft.name = "left";
        this.buttonLeft.inputEnabled = true;
        this.buttonLeft.fixedToCamera = true;
        this.buttonLeft.events.onInputOver.add(this.over, this);
        this.buttonLeft.events.onInputOut.add(this.out, this);
        this.buttonLeft.events.onInputDown.add(this.down, this);
        this.buttonLeft.events.onInputUp.add(this.up, this);

        this.buttonRight = this.game.add.sprite(179 / 2, 934 / 2, 'cursor_right', 0);
        this.buttonRight.name = "right";
        this.buttonRight.inputEnabled = true;
        this.buttonRight.fixedToCamera = true;
        this.buttonRight.events.onInputOver.add(this.over, this);
        this.buttonRight.events.onInputOut.add(this.out, this);
        this.buttonRight.events.onInputDown.add(this.down, this);
        this.buttonRight.events.onInputUp.add(this.up, this);

        this.buttonUp.scale.setTo(0.5, 0.5);
        this.buttonDown.scale.setTo(0.5, 0.5);
        this.buttonLeft.scale.setTo(0.5, 0.5);
        this.buttonRight.scale.setTo(0.5, 0.5);

        
        this.showInstruction();
        player.animations.play('turn');
       // walking = this.game.add.audio('walk');
       // walking.volume = 0.05;
       // walking.allowMultiple = false;
       // lektor = this.game.add.audio('lektor');
       // applause = this.game.add.audio('applause');
        
        

    },
    over: function (button, pointer) {
        switch (button.name) {
        case 'up':
            this.buttonUp.frame = 1;
                this.jump = true
            break;
        case 'down':
            this.buttonDown.frame = 1;
                this.ButtonDown = true
            break;
        case 'left':
             this.buttonLeft.frame = 1;
                this.left = true
            break;
        case 'right':
           this.buttonRight.frame = 1;
                this.right = true
            break;
        case 'help':
                this.guihelp.frame = 1;
                break;
        }

    },
    out: function (button, pointer) {
        //console.log('button down: '+button.name); 
        switch (button.name) {
        case "up":
            this.buttonUp.frame = 0;
                this.jump = false
            break;
        case "down":
            this.buttonDown.frame = 0;
                this.ButtonDown = false
            break;
        case "left":
            this.buttonLeft.frame = 0;
                this.left = false
            break;
        case "right":
            this.buttonRight.frame =0;
                this.right = false
            break;
        case 'help':
                this.guihelp.frame = 0;
                break;        
        }
    },
    down: function (button, pointer) {
        console.log('button down: ' + button.name);
        switch (button.name) {
        case "up":
           this.buttonUp.frame = 2;
                this.jump = true
            break;
        case "down":
            this.buttonDown.frame = 2;
                this.ButtonDown = true
            break;
        case "left":
            this.buttonLeft.frame = 2;
                this.left = true
            break;
        case "right":
            this.buttonRight.frame = 2;
                this.right = true
            break;
        case 'help':
               this.guihelp.frame = 1;
                this.showInstruction();
                break;        
        }
    },
    up: function (button, pointer) {
        console.log('button down: ' + button.name);
        switch (button.name) {
        case "up":
            this.buttonUp.frame = 1;
                this.jump = false
            break;
        case "down":
            this.buttonDown.frame = 1;
                this.ButtonDown = false
            break;
        case "left":
            this.buttonLeft.frame = 1;
                this.left = false
            break;
        case "right":
            this.buttonRight.frame = 1;
                this.right = false
            break;
        case 'help':
                this.guihelp.frame = 0;
                break;                
        }
    },

    createFromTiledObject: function (element, group) {
        var sprite = group.create(element.x, element.y, element.properties.sprite, parseInt(element.properties.numer));

        //copy all properties to the sprite
        Object.keys(element.properties).forEach(function (key) {
            sprite[key] = element.properties[key];
        });
    },
    createItems: function () {
        //create items
        this.items = this.game.add.group();
        this.items.enableBody = true;
        var item;
        result = this.findObjectsByType('item', map, 'LITERKI');
        result.forEach(function (element) {
            this.createFromTiledObject(element, this.items);
        }, this);
    },
    //find objects in a Tiled layer that containt a property called "type" equal to a certain value
    findObjectsByType: function (type, map, layer) {
        var result = new Array();
        map.objects[layer].forEach(function (element) {
            if (element.properties.type === type) {
                //Phaser uses top left, Tiled bottom left so we have to adjust
                //also keep in mind that the cup images are a bit smaller than the tile which is 16x16
                //so they might not be placed in the exact position as in Tiled
                element.y -= map.tileHeight;
                result.push(element);
            }
        });
        return result;
    },

    collect: function (player, collectable) {
        var collected = false;
       // console.log('sprite: ' + collectable.sprite + ' litera: ' + collectable.name);
        for (index = 0; index < arraySamogloski.length; index++) {
            if (collectable.name != arraySamogloski[index]) {
                TotalScore += 1;
                lettersCollected.push(collectable.name);
               // var number = parseInt(collectable.name);                    
               this.playSounds(collectable.name);
                //remove sprite
                collectable.destroy();
                collected = true;
                console.log('TotalScore: ' + TotalScore + ' life: ' + this.life);
                break;
            }
        }
        if (!collected){
        this.life = this.life - 1;
        collectable.destroy();
      //  console.log('TotalScore: ' + TotalScore + ' life: ' + this.life);
            
        }
    },
    playSounds: function(sound1)
    {
    var counter = 0;    
    var isdone = false;
    sound = new Audio("./sound/"+sound1+"_PL.mp3");
    sound.load();
    sound.play();
    },
    
    showInstruction: function()
    {
    GameState = 1;
    this.guiHelp = this.game.add.sprite(1410/2,380/2,'guiPomocnik');
    this.guiHelp.scale.setTo(0.5,0.5);
    this.guiHelp.fixedToCamera = true;    
    this.guiBubble = this.game.add.sprite(135/2,96/2,'Finish');
    this.guiBubble.scale.setTo(0.5,0.5); 
    this.guiBubble.fixedToCamera = true;  
    this.titleText = this.game.add.text(300/2, 540/2, 'Znajdź wszystkie ukryte liczby.\n                       (1-20)');
    this.titleText.fixedToCamera = true;     
    // this.hideInstruction();
    },
    
    hideInstruction: function()
    {
    this.guiHelp.visible = false;    
    this.guiBubble.visible = false;
    this.titleText.visible = false;    
    //this.lektor.hide();
    },
    showFin: function()
    {
    walking.pause();
    GameState = 1;
    this.guiHelp = this.game.add.sprite(1410/2,380/2,'guiPomocnik');
    this.guiHelp.scale.setTo(0.5,0.5);
    this.guiHelp.fixedToCamera = true;
    this.guiWin = this.game.add.sprite(135/2,96/2,'Finish');
    this.guiWin.scale.setTo(0.5,0.5);
    this.guiWin.fixedToCamera = true;
    this.titleText = this.game.add.text(300/2, 540/2, 'Brawo! Znalazłeś je wszystkie!');
    this.titleText.fixedToCamera = true;     
    applause.play();    
    },
    hideFin: function()
    {
    this.guiHelp.kill();    
    this.guiBubble.kill();
    this.state.start('Menu');
    },
    
    
    update: function () {
       if (GameState == 1 && (!isPlaying(lektor) || !lektor.ended )){
           lektor.play();
           GameState= 0;
       }
        if (GameState ==0 && (!isPlaying(lektor)|| lektor.ended)){
            this.hideInstruction();
            GameState =2;
        }
       if(GameState ==3 && !isPlaying(applause)){
        this.showFin();
        walking.pause();
           GameState = 4;
       // this.state.start('Menu');   
       } 
        if (GameState ==4 && (!isPlaying(applause) || applause.ended)){
            this.hideFin();
            GameState =0;
        }
       // this.game.debug.text(' Score: ' + lektor.isPlaying + ' Letters: ' + str + ' Life: ' + this.life, 20, 20);
        if (lettersCollected.length >= 1) {
            for (i = 0; i < lettersCollected.length; i++) {
                str = lettersCollected + ', ';
                this.text.setText(str);
            }
        }
        if (life = 0) {
            // this.ispaused = false;
        }
        if (TotalScore == 20 && !gameEnd) { //Tutaj dodać ilosc liter do zbierania
            player.body.velocity.x = 0;
            player.body.velocity.y = 0;
            player.animations.play('turn');
            walking.pause();
           // this.showFin();
            //this.ispaused = true;
            gameEnd = true;
            GameState = 3;
            //this.state.start('Menu');
        }
       
        if (!gameEnd) {
            //this.physics.arcade.collide(player, layer0);
            this.physics.arcade.collide(player, layer2);
            this.game.physics.arcade.overlap(player, this.items, this.collect, null, this);

            player.body.velocity.x = 0;
            player.body.velocity.y = 0;

            if (this.left || this.cursors.left.isDown) {
                if (!(this.cursors.up.isDown || this.cursors.down.isDown)) {
                if (player.x < (this.game.camera.x+this.game.camera.width)-800)
                {
                this.game.camera.x = this.game.camera.x-740;
                }    

                   
                    if (this.facing != 'left') {
                        player.animations.play('left');
                        this.facing = 'left';
                    }
                    player.body.velocity.x = -150;
                    if (!isPlaying(walking)) {
                    walking.loop = true;
                    walking.play();
                }
                }
            }

            if (this.right || this.cursors.right.isDown) {
                if (!(this.cursors.up.isDown || this.cursors.down.isDown)) {
        
                    if (player.x >= (this.game.camera.x+this.game.camera.width)-160)
                    {
                            this.game.camera.x = this.game.camera.x+800;
                    }
                    
                    if (this.facing != 'right') {
                        player.animations.play('right');
                        this.facing = 'right';
                    }
                }

                player.body.velocity.x = 150;
                if (!isPlaying(walking)) {
                    walking.loop = true;
                    walking.play();
                }
            }
            if (this.ButtonDown || this.cursors.down.isDown) {
            if (player.y >= ((this.game.camera.y+this.game.camera.height)-200))
        {
            this.game.camera.y = this.game.camera.y+360;
        }
                if (this.facing != 'down') {
                    player.animations.play('down');
                    this.facing = 'down';
                }
                player.body.velocity.y = 150;
                if (!isPlaying(walking)) {
                    walking.loop = true;
                    walking.play();
                }
            }
            if (this.jump || this.cursors.up.isDown) {
        if (player.y < ((this.game.camera.y+this.game.camera.height)-500))
        {
            this.game.camera.y = this.game.camera.y-360;
        }
                if (this.facing != 'up') {
                    player.animations.play('up');
                    this.facing = 'up';
                }
                player.body.velocity.y = -150;
                if (!isPlaying(walking)) {
                    walking.loop = true;
                    walking.play();
                }
            } else if (!(this.cursors.up.isDown || this.jump) && !(this.cursors.down.isDown || this.ButtonDown) && !(this.cursors.right.isDown || this.right) && !(this.cursors.left.isDown || this.left)) {
                walking.pause();
                this.facing = null;
                player.animations.play('turn');
            }
        }
    },

    render: function () {

         //this.game.debug.text(this.time.fps || '--', 2, 14, "#00ff00");
        //this.game.debug.text(' GameState: ' +GameState+' !isPlaying(lektor): '+!isPlaying(lektor) , 20, 20);
        //this.game.debug.text('cam: '+this.game.camera.x+' '+this.game.camera.y+' player: '+player.x+' '+player.y+'world: '+this.game.camera.width+' '+this.game.camera.height,2,14);
        // game.debug.body(player);
        // game.debug.bodyInfo(player, 16, 24);

    }
};