var self = this;
var iterator = 0;
var PodCounter;
var DodCounter;
var variant1 = [];
var inDefinition;
var definition_text;
var birdsound;

    Game1.Game1 = function (game) {
        iterator = 0;
        var buttonLeft;
        var buttonRight;
        var int = 0;
        var spriteList = new Array();
        var selectedbox1;
        var selectedbox2;
        var equationTable;
        var playedEquationGame1;
        var isReadyToRead;
        var intro;
        var input = 0;
        var calc_value;
        var text;
        var SavedLocation;
        var item;
        var ZmiennaMieszajaca;
        var ButtonList = [];
        var GameIsBusy = false;
    };

    function isPlaying(audelem) {
        return !audelem.paused;
    }

    function shuffle(array) {
        var currentIndex = array.length,
            temporaryValue, randomIndex;

        while (0 !== currentIndex) {
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }
        return array;
    }

    Game1.Game1.prototype = {
        create: function () {
            iterator = 0;
            PodCounter = 0;
            DodCounter = 0;
            tween = null;
            GameIsBusy = false;
            ButtonList = [];
            ItemInputList = [];
            PodItemList = [];
            DodItemList = [];
            ZmiennaMieszajaca = false;
            calc_value = "";
            input = 0;
            shoppinglist = "";
            shoppingcart = [];
            var SavedLocation = null;
            var LocationIsSet;
            this.LocationIsSet = false;
            lektor = new Audio("./sound/ZIP_g_I_2_4.mp3");
            lektor.load();
            finnish = new Audio("");
            finnish.load();
            sound = new Audio();
            equationTable = [4, 2, 1, 10, 3, 2, 5, 9, 9, 5, 0, 10];
            playedEquationGame1 = 0;
            isReadyToRead = false;
            intro = true;
            ItemList = "";
            this.bg = this.game.add.sprite(0, 0, 'bg_ingame');
            this.game.stage.backgroundColor = '#ffffff';
            this.game.physics.startSystem(Phaser.Physics.ARCADE);
            this.time.advancedTiming = true;
            this.buttonHelp = this.game.add.sprite(1768, 100 / 2, 'help', 0);
            this.buttonHelp.scale.setTo(0.8, 0.8);
            this.buttonHelp.name = "Help";
            this.buttonHelp.inputEnabled = true;
            this.buttonHelp.fixedToCamera = true;
            this.buttonHelp.events.onInputDown.add(this.down2, this);
            this.buttonHelp.events.onInputUp.add(this.up, this);
            inDefinition = 0;
            var item;
            var selectexbox1 = null;
            var selectexbox2 = null;
            var TotalPoints = 0;
            var equal;
            var j;
            this.SpawnBlocks();
            this.SpawnItem();
            this.showInstruction();
            lektor.play();
        },
        showDefinition: function () {
            inDefinition = 1;
            GameIsBusy = true;
            this.guiHelp = this.game.add.sprite(1210, 350, 'guiPomocnik_good');
            this.guiHelp.fixedToCamera = true;
            this.guiBubble = this.game.add.sprite(95, 96, 'Finish');
            this.guiBubble.scale.setTo(1.3, 1.3);
            this.guiBubble.fixedToCamera = true;
            definition_text = this.game.add.text(200, 330, '', {
                font: "36px Arial",
                fill: "#000000",
            });
            definition_text.fixedToCamera = true;
        },
        hideDefinition: function () {
            inDefinition = false;
            GameIsBusy = false;
            this.guiHelp.visible = false;
            this.guiBubble.visible = false;
            definition_text.visible = false;
        },
        SpawnBlocks: function () {
            if (ItemInputList.length > 0) {
                for (var index = 0; index < ItemInputList.length; ++index) {
                    ItemInputList[index].kill();
                }
            }
            this.item = this.game.add.sprite(415, 668, 'empty');
            this.item.name = "d_";
            this.item.isEmpty = true;
            PodItemList.push(this.item);
            this.item = this.game.add.sprite(1258, 668, 'empty');
            this.item.name = "p_";
            this.item.isEmpty = true;
            DodItemList.push(this.item);
        },  
		SpawnItem: function () {
            this.item = this.game.add.sprite(151, 301, "i_1");
            this.item.name = "i_1";
            ItemInputList.push(this.item);
            this.item = this.game.add.sprite(1322, 301, "i_3");
            this.item.name = "i_1";
            ItemInputList.push(this.item);
            console.log(ItemInputList);
            birdsound = new Audio('./sound/kos.mp3');
            birdsound.load();
            this.soundbutton = this.game.add.sprite(1222,400, 'voice');
            this.soundbutton.name = 'voice';
            this.soundbutton.inputEnabled = true;
            this.soundbutton.events.onInputDown.add(this.down2, this);
            this.SpawnButtons();
            iterator++;
        },
        SpawnItem2: function () {
            birdsound.pause();
			if (ItemInputList.length > 0) {
                for (var index = 0; index < ItemInputList.length; ++index) {
                    ItemInputList[index].kill();
                }
            }
			ItemInputList = [];
            this.item = this.game.add.sprite(101, 301, "i_2");
            this.item.name = "i_2";
            ItemInputList.push(this.item);
            this.item = this.game.add.sprite(1322, 301, "i_4");
            this.item.name = "i_2";
            ItemInputList.push(this.item);
            console.log(ItemInputList);
            birdsound = new Audio('./sound/sroka.mp3');
            birdsound.load();
            this.soundbutton = this.game.add.sprite(1222,400, 'voice');
            this.soundbutton.name = 'voice';
            this.soundbutton.inputEnabled = true;
            this.soundbutton.events.onInputDown.add(this.down2, this);
            this.SpawnButtons();
            iterator++;
        },
        SpawnButtons: function () {
            if (ButtonList.length > 0) {
                for (var index = 0; index < ButtonList.length; ++index) {
                    ButtonList[index].kill();
                }
            }
			
            for (var i = 1; i < 7; i++) {
                if (i < 4) {
                    this.item = this.game.add.sprite((150+((225 + 36) * (i - 1))), 851, "d_"+i);
                     this.item.value = "d_"+i;
                } else if (i >= 4) {
                    this.item = this.game.add.sprite(((225 + 36) * i - 1), 851, "p_"+(i-3));
                     this.item.value = "p_"+(i-3);
                }
                this.item.inputEnabled = true;
                this.item.name = "odpowiedzi";
                this.item.input.enableDrag(false, true);
                this.item.orginalPositionX = this.item.x;
                this.item.orginalPositionY = this.item.y;
                this.item.events.onDragStart.add(this.SaveLocation, this);
                ButtonList.push(this.item);
                this.item.events.onInputUp.add(this.stopDrag, this);
            }
        },
        SaveLocation: function (button, pointer) {
            if (GameIsBusy == false) {
                if (playedEquationGame1 < 10) {
                    button.bringToTop();
                }
            }
        },
        up: function (button, pointer) {
            button.frame = 0;
        },
        down2: function (button, pointer) {
            button.frame = 1;
            if (GameIsBusy == false) {
                if (button.name == 'guiBack' || button.name == 'NextButton') {
                    if (button.name == 'guiBack')
                        this.hideFinnish();
                    else if (button.name == 'NextButton')
                        this.showFinnish();
                } else if(button.name == 'voice')
                {
                  birdsound.loop = false;
				  birdsound.play();       
                } else if (((button.name != 'guiBack') || (button.name != 'Speaker')) && (!isPlaying(lektor) || lektor.ended)) {
                    intro = true;
                    this.showInstruction();
                    lektor.play();
                }
            }
        },
        StopInput: function () {
            if (ItemInputList.length > 0) {
                for (var index = 0; index < ItemInputList.length; ++index) {
                    ItemInputList[index].inputEnabled = false;
                }
            };
        },
        ReStartInput: function () {
            if (ItemInputList.length > 0) {
                for (var index = 0; index < ItemInputList.length; ++index) {
                    ItemInputList[index].inputEnabled = true;
                }
            };
        },
        showInstruction: function () {
            GameIsBusy = true;
            this.StopInput();
            this.guiHelp = this.game.add.sprite(1210, 350, 'guiPomocnik_good');
            this.guiHelp.fixedToCamera = true;
            this.guiBubble = this.game.add.sprite(135, 96, 'Finish');
            this.guiBubble.scale.setTo(1.2, 1.2);
            this.guiBubble.fixedToCamera = true;
            this.titleText = this.game.add.text(200, 330, 'Rozpoznaj co to za drzewo i jaki to ptak.', {
                font: "40px Arial",
                fill: "#000000",
            });
            this.titleText.fixedToCamera = true;
        },	
        hideInstruction: function () {
            GameIsBusy = false;
            this.ReStartInput();
            this.guiHelp.visible = false;
            this.guiBubble.visible = false;
            this.titleText.visible = false;
        },
        stopDrag: function (button, pointer) {
            var mover = button;
            var ToInsert = true;

            for (var i = 0; i < PodItemList.length; i++) {
                if (mover.overlap(PodItemList[i])) {
                    if (ItemInputList[0].name.slice(-1) == mover.value.slice(-1) ) {
                        for (var j = 0; j < PodItemList.length; j++) {
                            if (PodItemList[j].isEmpty && ToInsert) {
                                ToInsert = false;
                                mover.orginalPositionX = PodItemList[j].x;
                                mover.orginalPositionY = PodItemList[j].y;
                                PodItemList[j].isEmpty = false;
                                PodCounter++;
                                this.playGood();
                            }
                        }
                    } else {
                        this.playWrong();
                    }
                }
            }

            for (var i = 0; i < DodItemList.length; i++) {
                if (mover.overlap(DodItemList[i])) {
                    if (ItemInputList[1].name.slice(-1) == mover.value.slice(-1) ) {
                        for (var j = 0; j < DodItemList.length; j++) {
                            if (DodItemList[j].isEmpty && ToInsert) {
                                ToInsert = false;
                                mover.orginalPositionX = DodItemList[j].x;
                                mover.orginalPositionY = DodItemList[j].y;
                                DodItemList[j].isEmpty = false;
                                DodCounter++;
                                this.playGood();
                            }
                        }
                    } else {
                          this.playWrong();
                    }
                }
            }
			
            this.game.add.tween(mover).to({
                x: mover.orginalPositionX,
                y: mover.orginalPositionY
            }, 1000, Phaser.Easing.Back.Out, true);
        },      
		playWrong: function () {
            sound.pause();
            sound = new Audio("./sound/z_" + (Math.floor(Math.random() * 4) + 1) + ".mp3");
            sound.load();
            sound.loop = false;
            sound.play();
        },
        playGood: function () {
            playedEquationGame1++;
            sound.pause();
            sound = new Audio("./sound/d_" + (Math.floor(Math.random() * 4) + 1) + ".mp3");
            sound.load();
            sound.loop = false;
            sound.play();
        },
        showFinnish: function () {
            this.StopInput();
            if (ButtonList.length > 0) {
                for (var index = 0; index < ButtonList.length; ++index) {
                    ButtonList[index].kill();
                }
            }
            playedEquationGame1 = 13;
        },
        hideFinnish: function () {
            sound.pause();
            this.ReStartInput();
            this.guiBack.kill();
            this.guiBg.kill();
            this.guiBoo.kill();
            this.guiHelp.kill();
            this.guiBubble.kill();
            this.guiBasket.kill();
            this.guiCounter.kill();
            this.guiText.setText('');
            text.setText('');
        },
        down: function (button, pointer) {
            button.frame = 1;
            if (GameIsBusy == false) {
                if (button.name == 'definicjaButton') {
                    this.showDefinition();
                }
                if (button.name == "odpowiedzi") {
                    if (button.value == ItemInputList[0].value) {
                        ItemInputList[0].destroy();
                        ItemInputList.pop();
                        this.SpawnItem();
                        playedEquationGame1++;
                    } else if (button.value != ItemInputList[0].value) {
                        this.playWrong();
                    }
                }
            }
        },
        AddDigit: function (string) {
            {
                if (calc_value.length > 6) {} else {
                    if ((eval(calc_value) == 0) && (calc_value.indexOf(".") == -1)) {
                        calc_value = string;
                    } else {
                        calc_value = calc_value + string;
                    };
                };
            };
            input = calc_value;            
        },
        update: function () {
            if (inDefinition == 1) {
                definition_text.setText('');
                this.hideDefinition();
                inDefinition = 2;
            }
            if ((DodCounter == 1 && PodCounter == 1) && (!isPlaying(sound) || sound.ended))
            {
                if (ButtonList.length > 0) {
                    for (var index = 0; index < ButtonList.length; ++index) {
                        ButtonList[index].kill();
                    }
                }
                DodItemList = [];
                PodItemList = [];
                DodCounter = 0;
                PodCounter = 0;
                this.SpawnBlocks();
                this.SpawnItem2();
                console.log(playedEquationGame1);
                playedEquationGame1++;
            }
            if (tween != null)
                tween.onComplete.removeAll();
            if (ZmiennaMieszajaca) {
                playedEquationGame1 == 10;
            }
            if (playedEquationGame1 == 6 && (!isPlaying(sound) || sound.ended)) {
                sound.pause();
                playedEquationGame1 = 13;
                this.showFinnish();
            }
            if (playedEquationGame1 == 13 && (!isPlaying(sound) || sound.ended)) {
                this.state.start('Game2');
            }
            if (playedEquationGame1 < 12) {
                if ((!isPlaying(lektor) || lektor.ended) && intro) {
                    intro = false;
                    this.hideInstruction();
                    isReadyToRead = true;
                }
            }
            if (playedEquationGame1 == 14) {
                this.state.start('Game2');
            }
        },
        render: function () {
        }
    };