var self = this;
var iterator = 0;
var PodCounter;
var DodCounter;
var variant1 = [];
var inDefinition;
var definition_text;
var krzak;
var SkyTable = [];
var cursors;
var playertween;
var bgtween;
var bgtween2;
var player;
var NPC;
var NPCtween;
var PytanieText;
var SelectedButton;
var picture;
var SpeakerButton;
var selectedbox1;
var selectedbox2;
var GameIsBusy = false;
var tmpbutton;
var definition_text1;
var start1;
var start2;

Game1.Game = function (game) 
{
    var buttonLeft;
    var buttonRight;
    var int = 0;
    var spriteList = new Array();
    var equationTable;
    var playedEquation;
    var isReadyToRead;
    var intro;
    var input = 0;
    var calc_value;
    var text;
    var SavedLocation;
    var item;
    var ZmiennaMieszajaca;
    var ButtonList = [];
    var info;
    var left = false;
    var right = false;
    var SelectionMenuItems = [];
    var selectedItem1 = -1;
    var selectedItem2 = -1;
    var start1;
    var definition_text1;
    var start2;
};
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.Game.prototype = {
    create: function () {
        var shift = this.game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);
        this.game.input.keyboard.addKeyCapture(Phaser.Keyboard.SHIFT);
        this.game.input.keyboard.addCallbacks(this, null, null, this.keyPress);
        shift.onDown.add(this.keyPress, this);
        shift.onUp.add(this.keyUp, this);    
        cursors = this.input.keyboard.createCursorKeys();
		sound = new Audio();
        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;
        equationTable = [];
        playedEquation = 0;
        isReadyToRead = false;
        intro = false;
        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;
        PytanieText = this.game.add.text(200, 850, '', {
            font: "56px Arial",
            fill: "#000000",
        });
        this.createSelectionMenu();
    },
    startGame:function(){
        if ( this.selectedItem1 != -1 && this.selectedItem2 != -1){
            
			for ( var i =0 ; i<this.SelectionMenuItems.length; i++)
            {
                this.SelectionMenuItems[i].visibility = false;
                this.SelectionMenuItems[i].inputEnabled = false;
                this.SelectionMenuItems[i].destroy();
            }
                
			this.createMemoselections(this.selectedItem1, this.selectedItem2);
            this.SpawnBlocks();
        }
    },
    createSelectionMenu : function(){
        this.SelectionMenuItems = [];
        
		for ( var i=0; i<6; i++)
        {
            if ( i<3){
                var button = this.game.add.sprite(88+(325+35)*i,175, 'button_'+(i+1), 0);
                button.inputEnabled = true;
				button.fixedToCamera = true;
				button.events.onInputDown.add(this.onUp, this);
                button.name = (i+1);
                button.isOn = false;
                this.SelectionMenuItems.push(button);
            }
            else
            {
                var button = this.game.add.sprite(88+(325+35)*(i-3),175+325+35, 'button_'+(i+1), 0);
                button.inputEnabled = true;
				button.fixedToCamera = true;
				button.events.onInputDown.add(this.onUp, this);
                button.name = (i+1);
                button.isOn = false;
                this.SelectionMenuItems.push(button);
            }
        }
            
		var start = this.game.add.sprite(864,905,'play',0);
        start.inputEnabled = true;
        start.fixedToCamera = true;
        start.events.onInputDown.add(this.startGame, this);
        this.SelectionMenuItems.push(start);    
        var start = this.game.add.sprite(1306,459,'NPC',0);
        start.inputEnabled = true;
        start.fixedToCamera = true;
        start.events.onInputDown.add(this.startGame, this);
        this.SelectionMenuItems.push(start);
        var start = this.game.add.sprite(1172,86,'dymek',0);
        start.inputEnabled = true;
        start.fixedToCamera = true;
        start.events.onInputDown.add(this.startGame, this);
        this.SelectionMenuItems.push(start);
        var definition_text;
        definition_text = this.game.add.text(1250, 230, '                  Memo\nWybierz dwie różne serie kart,\na następnie naciśnij start.', {
			font: "36px Arial",
            fill: "#000000",
        });
        definition_text.fixedToCamera = true;
        this.SelectionMenuItems.push(definition_text);    
		this.selectedItem1 = -1;
		this.selectedItem2 = -1;      
    },
    onUp: function (button, pointer) {
        var currOnButtons = 0;
        if (button.isOn) {
            button.frame = 0;
            button.isOn = false;
		} else {
            button.frame = 1;
            button.isOn = true;
                
			for (var i = 0; i < this.SelectionMenuItems.length; i++) {
                if (this.SelectionMenuItems[i].isOn)
                    currOnButtons++;
            }
			
            if (currOnButtons == 2) {
                var tmplist = [];
                
				for (var i = 0; i < this.SelectionMenuItems.length; i++) {
                    if (this.SelectionMenuItems[i].isOn) tmplist.push(this.SelectionMenuItems[i].name);
                }
                
				this.selectedItem1 = tmplist[0];
                this.selectedItem2 = tmplist[1];        
            }
            if (currOnButtons >2){
                
				for (var i = 0; i < this.SelectionMenuItems.length; i++) {
                    this.SelectionMenuItems[i].frame = 0;
                    this.SelectionMenuItems[i].isOn = false;
                }    
            }
        }
    },
    keyPress: function(e){
        console.log("show?");
          
		for ( var i =0 ; i< ButtonList.length; i++)
		{      
            var tmp = ButtonList[i].value.split("_");
            ButtonList[i].loadTexture(tmp[1] + '_' + tmp[0]);
        }
    },
    keyUp: function(e) {
        console.log("hide");     
            
		for ( var i =0 ; i< ButtonList.length; i++)
        {           
            ButtonList[i].loadTexture('memo_bg');
        }   
    },
    createMemoselections: function (memo1, memo2) { 
        
		for (var i = 1; i < 13; i++) {
            var str = memo1 + "_" + i;
            variant1.push(str);
            var str = memo2 + "_" + i;
            variant1.push(str);
        }
            
		console.log(variant1);
        shuffle(variant1);
    },
    over: function (button, pointer) {
        this.info.visible = false;
        playertween = this.game.add.tween(player);
        playertween.to({
            x: 360,
            y: 735
        }, 900);
        playertween.onComplete.add(UpTheHill, this);
        player.animations.play('right');
        playertween.start();
        bgtween.start();
    },
    FinnishIntro: function () {
    },
    showDefinition: function () {
        console.log('dfsd');
        inDefinition = 1;
        start1 = this.game.add.sprite(1306,459,'NPC',0);
        start1.inputEnabled = true;
        start1.fixedToCamera = true;
        start2 = this.game.add.sprite(1172,86,'dymek',0);
        start2.inputEnabled = true;
        start2.fixedToCamera = true;
        definition_text1;
        definition_text1 = this.game.add.text(1250, 230, '        Znajdź dwie karty\n        z tą samą wartością.', {
            font: "36px Arial",
            fill: "#000000",
        });
        definition_text1.fixedToCamera = true;
        this.game.time.events.add(Phaser.Timer.SECOND * 1, function () {
            try {
				start1.visible = false;
                start2.visible = false;
				definition_text1.visible = false;
            }
            catch (e) {
            }
        }, this);
    },
    hideDefinition: function () {
        inDefinition = 0;
        GameIsBusy = false;
        console.loge('dssd');
        start1.visible = false;
        start1.visible = false;
        definition_text1.visible = false;
    },
    SpawnBlocks: function () {
        var ver_anc = 40;
        var hor_anc = 180;
            
		for (var i = 0; i < 24; i++) {
            if (i < 6) {
                this.item = this.game.add.sprite(hor_anc + (245 * i), ver_anc, "memo_bg");
            }
            if (i >= 6 && i < 12) {
                this.item = this.game.add.sprite(hor_anc + (245 * (i - 6)), 245+ver_anc, "memo_bg");
            }
            if (i >= 12 && i < 18) {
                this.item = this.game.add.sprite(hor_anc + (245 * (i - 12)), 2*245+ver_anc, "memo_bg");
            }
            if (i >= 18 && i < 24) {
                this.item = this.game.add.sprite(hor_anc + (245 * (i - 18)), 3*245+ver_anc, "memo_bg");
            }
            this.item.inputEnabled = true;
            this.item.name = "odpowiedzi";
            this.item.value = variant1[i];
            this.item.soundName = variant1[i];
            ButtonList.push(this.item);
            this.item.events.onInputDown.add(this.down, this);
        }
		
        this.SpawnItem();
    },
    SpawnItem: function () {
    },
    SpawnButtons: function () {
    },
    SaveLocation: function (button, pointer) {
        if (GameIsBusy == false) {
            if (playedEquation < 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 == 'Speaker') {
            } else if (((button.name != 'guiBack') || (button.name != 'Speaker')) ) {
                this.showDefinition();
            }
        }
    },
    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;
            }
        };
    },
    playSound: function () {
        GameIsBusy = true;
        sound.pause();
        sound = new Audio("./sound/" + tmpbutton.soundName.slice(-1) + '_' + tmpbutton.soundName.slice(0, 1) + ".mp3");
        console.log("sound:" + sound);
        sound.load();
        sound.loop = false;
        sound.play();
    },
    playWrong: function () { 
        GameIsBusy = true;
        sound.pause();
        sound = new Audio("./sound/bad.mp3");
        sound.load();
        sound.loop = false;
        sound.play();
    },
    playGood: function () { 
        GameIsBusy = true;
        sound.pause();
        sound = new Audio("./sound/good.mp3");
        sound.load();
        sound.loop = false;
        sound.play();
    },
    showFinnish: function () {
        this.StopInput();
        start1 = this.game.add.sprite(1306,459,'NPC',0);
        start1.inputEnabled = true;
        start1.fixedToCamera = true;
        start2 = this.game.add.sprite(1172,86,'dymek',0);
        start2.inputEnabled = true;
        start2.fixedToCamera = true;
        definition_text1;
        definition_text1 = this.game.add.text(1250, 230, '                 Brawo!\n        Znalazłeś wszystkie.', {
            font: "36px Arial",
            fill: "#000000",
        });
        definition_text1.fixedToCamera = true;
        this.game.time.events.add(Phaser.Timer.SECOND * 1, function () {
            try {
				location.reload();
            }
            catch (e) {
            }
        }, this);
        playedEquation = 14;
    },
    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) {
        if (GameIsBusy == false) {
            if (button.name == 'definicjaButton') {
                this.showDefinition();
            }
            if (button.name == "odpowiedzi") {
                tmpbutton = button;
                if (selectedbox1 == null) {
                    selectedbox1 = button;
                    var tmp = selectedbox1.value.split("_");
                    selectedbox1.loadTexture(tmp[1] + '_' + tmp[0]);
                } else {
                    console.log("selectedbox1 !=tmpbutton =  "+selectedbox1 !=tmpbutton );
                    if (selectedbox1 != null && selectedbox1 !=tmpbutton ) {
                        selectedbox2 = button;
                        var tmp = selectedbox2.value.split("_");
                            selectedbox2.loadTexture(tmp[1] + '_' + tmp[0]);
                        }
                    }
                }
                if (selectedbox1 != null && selectedbox2 != null) {
                var tmp1 = selectedbox1.value.split("_");
                var tmp2 = selectedbox2.value.split("_");
                if ((tmp1[1] == tmp2[1] && tmp2[0] != tmp1[0])) {
					this.playGood();
                    GameIsBusy = true;
                    this.game.time.events.add(Phaser.Timer.SECOND * (1.5), function () {
                        try {
                            selectedbox1.visible = false;
                            selectedbox2.visible = false;
                            selectedbox1 = null;
                            selectedbox2 = null;
                            tmpbutton = null;
                            GameIsBusy = false;
                            playedEquation++ 
                        } catch (e) {}
                    }, this);
                } else if ((tmp1[1] != tmp2[1])) {
					this.playWrong();
                    GameIsBusy = true;
                    this.game.time.events.add(Phaser.Timer.SECOND * (1.5), function () {
                        try {
                            selectedbox1.loadTexture('memo_bg');
                            selectedbox2.loadTexture('memo_bg');
                            selectedbox1 = null;
                            selectedbox2 = null;
                            tmpbutton = null;
                            GameIsBusy = false;
                        } catch (e) {}
                    }, this);
                }
            }
        }
    },
    update: function () {
        if (playedEquation == 12) {
            this.showFinnish();
        }
    },
    render: function () {
    }
};