    var self = this;
var definicja_audio;
var definicja_audio2;
var inDefinition;
var definition_text;
var PlayNextSound = false;
Game1.Game = function (game) {
    var buttonLeft;
    var buttonRight;
    var int = 0;
    var spriteList = new Array();
    var selectedbox1;
    var selectedbox2;
    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 GameIsBusy = false;
    var definicja;

};

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

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

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

Game1.Game.prototype = {
    
    upList: function()
    {
        if( ButtonList.length>0)
        {
    for (var index = 0; index < ButtonList.length; ++index) {
    ButtonList[index].kill();
    }
    };
    
        ZmiennaMieszajaca = false;  
        //   if (this.ZmiennaMieszajaca){
       
     //  ItemList = "";
        if ( shoppingcart.length>1)
     for (var j =1; j< shoppingcart.length;j++){
    //   ItemList = ItemList+shoppingcart[j][0]+"    sztuk: "+shoppingcart[j][1]+"\n";
       //this.item = self.Game1.game.add.sprite(1424 + (152 * (i % 3)), 454 + (105 * (0)), 'calc_' + i, 0);
       
         
         this.button = this.game.add.sprite(1800, 275 + (42 * (j)), 'calc_', 0);
       this.button.scale.setTo(0.4, 0.4);
       this.button.inputEnabled = true;
       this.button.name = 'kalkulator';
       this.button.item = j; 
       this.button.events.onInputDown.add(this.down, this);
       ButtonList.push(this.button);
         // //console.log("timeout!");
     }
     // shoppinglist.setText(ItemList);
      
      // //console.log("timeout!");
           
   // }
    },
    create: function () {
           
    definicja_audio = new Audio('./sound/MW_g_I_10_2.mp3');
  //  definicja_audio2 = new Audio('./sound/OB_g_I_1_2.mp3'); 
        tween = null;
        //this.load.BitmapFont('font_0', 'font/font_0_0.png',font_json);
        GameIsBusy = false;
        ButtonList = [];
        ItemInputList = [];
        ZmiennaMieszajaca = false;
        calc_value ="";
        input = 0;
        shoppinglist = "";
        shoppingcart= [[]];
        var SavedLocation = null;
        var LocationIsSet;
        this.LocationIsSet = false;
       variant1= [1,2,3,4,5,6,7,8,9,10];
    variant2= [1,2,3,4,5,6,7,8,9,10];
        // //console.log(variant1);
    shuffle(variant1);
     shuffle(variant2);    
       // //console.log(variant1);
        //strona = new Audio("./sound/page.mp3");
        //strona.load();
        lektor = new Audio("./sound/MW_g_I_10_1.mp3");
        lektor.load();
       
        sound = new Audio();
        equationTable = [];
        playedEquation = 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.boo = this.game.add.sprite(0,0,"book");

        this.regal = this.game.add.sprite(194,30,'regal');
       
       /* this.definicja = this.game.add.sprite(1584,954,'definicja');
        this.definicja.name = 'definicjaButton';
        this.definicja.inputEnabled = true;
        this.definicja.fixedToCamera = true;
        this.definicja.events.onInputDown.add(this.down2, this);
        this.definicja.events.onInputUp.add(this.up, this);*/
       // this.listaZakupow = this.game.add.sprite((1342),171,'lista');
        calc = this.game.add.sprite(1346, 770, "koszyt1");
        //calc_2 = this.game.add.sprite(1071, 850, "koszyt2");
        //calc.scale.setTo(0.5, 0.5);
        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);
this.buttonLeft = this.game.add.sprite(150 / 2, 100 / 2, 'speaker', 0);
        this.buttonLeft.name = "Speaker";
        this.buttonLeft.inputEnabled = true;
        this.buttonLeft.fixedToCamera = true;
        this.buttonLeft.events.onInputDown.add(this.down2, this);
        this.buttonLeft.events.onInputUp.add(this.up, this);
                
        var item;
        var selectexbox1 = null;
        var selectexbox2 = null;
        var TotalPoints = 0;
        var equal;
        var j;
this.CreateBackgroundForItems();
this.CreateItems(); 
       this.showInstruction();
    definition_text = this.game.add.text(220, 350, '', {
            font: "80px Arial",
            fill: "#000000",
        });
        definition_text.fixedToCamera = true;
            inDefinition = 0;    
    lektor.play();
     
           
        
    },
    CreateBackgroundForItems: function(){
        for ( var i = 1; i<11;i++)
        {
            if (i<=4)
            {
            this.item = this.game.add.sprite(300+(340*(i%4)), 120, 'mw_'+variant1[i-1]);    
            }
            if(i>4 && i <=8 )
            {
            this.item = this.game.add.sprite(300+(340*(i%4)), 380, 'mw_'+variant1[i-1]);    
            }
            if (i>8)
            {
            this.item = this.game.add.sprite(300+(340*(i%4)), 630, 'mw_'+variant1[i-1]);    
            }
        }
    },
    CreateItems: function(){
        for ( var i = 1; i<11;i++)
        {
            if (i<=4)
            {
            this.item = this.game.add.sprite(300+(340*(i%4)), 120, 'mw_'+variant1[i-1]);    
            }
            if(i>4 && i <=8 )
            {
            this.item = this.game.add.sprite(300+(340*(i%4)), 380, 'mw_'+variant1[i-1]);    
            }
            if (i>8)
            {
            this.item = this.game.add.sprite(300+(340*(i%4)), 630, 'mw_'+variant1[i-1]);    
            }
        
        this.item.orginalPositionX = this.item.x; this.item.orginalPositionY = this.item.y;
        this.game.physics.arcade.enable(this.item);
        this.item.inputEnabled = true; 
        this.item.name = 'items';
        
        this.item.value = 'mw_'+variant1[i-1];
        ////console.log(this.item.value);    
        this.item.input.enableDrag(false, true);
        this.item.events.onDragStart.add(this.SaveLocation, this);
        this.item.events.onDragStop.add(this.stopDrag, this);
        this.item.events.onInputDown.add(this.down, this);
        ItemInputList.push(this.item);    
    }
        
    },
    SaveLocation: function(button, pointer){
       if(GameIsBusy == false){
        if(playedEquation < 10){
        button.bringToTop();
        }
       }
    },
    
    up: function (button, pointer) {
        button.frame = 0;
    },
    down2: function (button, pointer) {
       if (!GameIsBusy){
        button.frame = 1;
       if (button.name == 'definicjaButton')
       {
         this.showDefinition();
       }
        
        else if (button.name == 'Speaker') {
            if (!isPlaying(sound) || sound.ended)
                this.playSound();
        } else if (((button.name != 'guiBack')||(button.name != 'Speaker'))&&(!isPlaying(lektor) || lektor.ended)) {
            intro = true;
            this.showDefinition();
            //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 () {
        if (!GameIsBusy){
       // lektor.play();
            GameIsBusy = true;
       this.StopInput();
        this.guiHelp = this.game.add.sprite(1366, 477, 'guiPomocnik_good');
        this.guiHelp.scale.setTo(1.2,1.2);
        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(349, 460, 'Shopping list', {
            font: "90px Arial",
            fill: "#000000",
        });
        this.titleText.fixedToCamera = true;
        }
    },
    
    ReadItem : function()
    {
    if (!GameIsBusy && playedEquation<10) 
        this.playSound();
    },

    hideInstruction: function () {
        GameIsBusy = false;
      this.ReStartInput();
        this.guiHelp.visible = false;
        this.guiBubble.visible = false;
        this.titleText.visible = false;
        PlayNextSound = true;
        //this.lektor.hide();
    },
    
    showDefinition: function () {
       if (!GameIsBusy){
        inDefinition = 1;
        GameIsBusy = true;
        //definicja.inputEnabled = false;
       definicja_audio.play();
       this.StopInput();
        this.guiHelp = this.game.add.sprite(1366, 477, 'guiPomocnik_good');
        this.guiHelp.scale.setTo(1.2,1.2);
        this.guiHelp.fixedToCamera = true;
        this.guiBubble = this.game.add.sprite(135, 96, 'Finish');
        //this.guiBubble.scale.setTo(1.3,1.3); 
        this.guiBubble.fixedToCamera = true;
        definition_text.visible = true;
           definition_text.setText('\nPut the product you hear\nto the basket.');
        definition_text.parent.bringToTop(definition_text);
        definition_text.fixedToCamera = true;
       }
    },

    hideDefinition: function () {
       inDefinition = false;
        GameIsBusy = false;
        //play.inputEnabled = true;
        //definicja.inputEnabled = true;
      this.ReStartInput();
        this.guiHelp.visible = false;
        this.guiBubble.visible = false;
        definition_text.visible = false;
        definition_text.setText('');
        //this.lektor.hide();
    },    

    
    stopDrag: function (button, pointer) {
        
       if (GameIsBusy == false){
       // //console.log(button.name);
        ////console.log(button.value);   
       var  mover = button;   
        if (button.overlap(calc)) {
            if (button.value == 'mw_'+variant2[playedEquation])
            {
                // //console.log("its over 1!");
                button.destroy();
                isReadyToRead = true;
                this.playGood();
                playedEquation++;
            }
            else{
                this.playWrong(1);
            }


        }
/*        if (button.overlap(calc_2)) {
            if (button.value =='1')
            {
                 ////console.log("its over! 2");
                button.destroy();
                playedEquation++;
            }
            else{
                this.playWrong(0);
            }
           

        }  */ 
        //this.add.tween(button).to({button.orginalPositionX,button.orginalPositionY}, 2000, Phaser.Easing.Linear.None, true);
     // Game1.Game.Phaser.game.add.tween(button).to( {x:button.orginalPositionX, y:button.orginalPositionY }, 500, Phaser.Easing.Back.Out, true);
           this.game.add.tween(button).to( {x:button.orginalPositionX, y:button.orginalPositionY }, 1000, Phaser.Easing.Back.Out, true);
      
           // button.x = button.orginalPositionX;
       // button.y = button.orginalPositionY;
        ZmiennaMieszajaca = true;
        // And re-enable it upon release
       // this.sprite.body.moves = true;

    }
    },

    playSound: function () {
        sound = new Audio("./sound/mw_10_"+variant2[playedEquation] + ".mp3");
        sound.load();
        sound.loop = false;
        sound.play();
        

    },
    playWrong: function (int) {
       // if (!isPlaying(sound)) {
        sound.pause();
        
        sound = new Audio("./sound/bad_" + (Math.floor(Math.random() * 2) + 1) + ".mp3");    
        
            sound.load();
            sound.loop = false;
            sound.play();

     //   }
    },
    playGood: function () {
        sound.pause();
        sound = new Audio("./sound/good_" + (Math.floor(Math.random() * 2) + 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();
        
    }
        }
        
       this.guiBg = this.game.add.sprite(0, 0, 'bg_ingame');
      // this.guiBoo = this.game.add.sprite(0, 0, "book");
       this.guiBubble = this.game.add.sprite(174, 85, 'Finish');
      //  this.guiBubble.scale.setto(0.8,0.8);
    //Ustalenie poprawności wykonania zadania
       
       this.guiHelp = this.game.add.sprite(1366, 407, 'guiPomocnik_good');
       this.guiText = this.game.add.text(349, 460, 'Well done!', {
            font: "90px Arial",
            fill: "#000000",
        });
        sound.pause();
        sound = new Audio("./sound/good_1.mp3");
        sound.load();
        sound.loop = false;
        sound.play();
        this.titleText.fixedToCamera = true;
        playedEquation = 13;

    },
    hideFinnish: function () {
     sound.pause();
     this.ReStartInput();
     //   this.guiHelp.kill();
     //   this.guiBubble.kill();
     this.upList();    
     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){
        //console.log(button.value);
           if (button.name == "kalkulator")
        {
            ////console.log("klakulator nr:"+button.item);
            if(shoppingcart[button.item][1]>1){
                shoppingcart[button.item][1] = shoppingcart[button.item][1]-1;
            input = input - shoppingcart[button.item][2];
            }
            else if ( shoppingcart[button.item][1]==1){
              button.destroy();
                this.upList();
                
               
               // button.update();
                input = input -shoppingcart[button.item][2];
              shoppingcart.splice(button.item,1);
             
            }
            // text.setText(input.toString());   
             ZmiennaMieszajaca = true;
        }


   }
    },

    update: function () {
       if( tween !=null)
        tween.onComplete.removeAll();
       if (ZmiennaMieszajaca){
       //this.showFinnish();
           playedEquation == 10;
      // //console.log("timeout!");
          this.upList(); 
  
                   
        }
        if (!GameIsBusy && PlayNextSound)
        {
            PlayNextSound = false;
         this.ReadItem();   
        }
        if ((!isPlaying(definicja_audio) || definicja_audio.ended) && inDefinition== 1) {
               // definicja_audio2.play();
               //definition_text.setText('Produkty potrzeb dalszych to produkty,\nktóre zaspokajają dodatkowe potrzeby człowieka,\nsprawiająprzyjemność, ale nie są nam niezbędne do życia.\nPrzykładem mogą być słodycze, ozdoby,\nzabawki,nietypowe produkty spożywcze, książki,\ntelewizor, gry, komputer, itp.');
                this.hideDefinition();
                inDefinition = 2;
            }
          /*  if ((!isPlaying(definicja_audio2) || definicja_audio.ended2) && inDefinition == 2) {
                inDefinition= 3;

               definition_text.setText('Produkty potrzeb dalszych to produkty,\nktóre zaspokajają dodatkowe potrzeby człowieka,\nsprawiają przyjemność, ale nie są nam niezbędne do życia.\nPrzykładem mogą być słodycze, ozdoby,\nzabawki,nietypowe produkty spożywcze, książki,\ntelewizor, gry, komputer, itp.');
                this.hideDefinition();
               // isReadyToRead = true;
            }*/
        
        if ((playedEquation >= 10 && playedEquation<13) && (!isPlaying(sound) || sound.ended)) {
            sound.pause();
            playedEquation = 13;
            this.showFinnish();
        }
        if (playedEquation == 13 && (!isPlaying(sound) || sound.ended)) {
           // //strona.play();
            this.state.start('Menu');
            //this.hideFinnish();
        }
        if (playedEquation <= 10) {
            if ((!isPlaying(lektor) || lektor.ended) && intro) {
                intro = false;
                this.hideInstruction();
                this.showDefinition();
                isReadyToRead = true;
            }
          if (isReadyToRead && (!isPlaying(sound) || sound.ended)) {
                isReadyToRead = false;
                this.ReadItem();  
             // this.playSound();
            }
        }
        if (playedEquation ==14)
        {
           this.state.start('Menu');  
        }
    },

    render: function () {

         //this.game.debug.text(this.time.fps || '--', 2, 14, "#00ff00");
       // this.game.debug.text( playedEquation, 80, 80);
        // game.debug.body(player);
        // game.debug.bodyInfo(player, 16, 24);

    }
};