class SceneMain extends Phaser.Scene
{
    constructor ()
    {
        super({ key: "SceneMain", active: true });
    }
    
    create (data)
    {
        this.scene.sleep();

        this.lang =  data.lang;
        this.languages =  data.languages;
        this.globalTexts = data.globalTexts;
        this.localTexts =  data.localTexts;

        this.config = data.config;

        //load settings if any
        this.conf = {};

        this.conf.autoSpinLimit = AUTO_SPIN_UNLIMITED;

        this.bgrmain = this.add.image(540, 960, "bgrmain").setDepth(0);

        this.logoL = this.add.image(222, 600, "logol").setVisible(false).setDepth(97);

        this.logoP = this.add.image(314, 396, "logop").setVisible(false).setDepth(98);
        
        this.logoSymP = this.add.image(844, 396, "logosymbolp").setVisible(false).setDepth(98);

        let stopBtnEnabled = false;

        if (this.config.hasOwnProperty("stopBtnEnabled"))
        {
            let v = parseInt(this.config.stopBtnEnabled);

            if (Number.isInteger(v) && v)
            {
                stopBtnEnabled = true;
            }
        }

        let turboBtnEnabled = false;

        if (this.config.hasOwnProperty("turboBtnEnabled"))
        {
            let v = parseInt(this.config.turboBtnEnabled);

            if (Number.isInteger(v) && v)
            {
                turboBtnEnabled = true;
            }
        }

        let jackpotLockVisible = false;

        if (this.config.hasOwnProperty("jackpotLockVisible"))
        {
            let v = parseInt(this.config.jackpotLockVisible);

            if (Number.isInteger(v) && v)
            {
                jackpotLockVisible = true;
            }
        }

        this.barP = this.add.image(540, 1872, "barp").setDepth(100);
        this.bonusL = this.add.image(280, 1010, "bonusl").setDepth(100);
        this.bonusP = this.add.image(140, 1760, "bonusp").setDepth(100);

        this.txtInfo = this.add.text(120, 825, "", { fontFamily: "Arial", fontSize: 22, color: "#ffffff" }).setOrigin(0.5).setDepth(111);
        this.txtGame = this.add.text(120, 825, "", { fontFamily: "Arial", fontSize: 22, color: "#ffffff" }).setOrigin(0.5).setDepth(111);
        this.txtTime = this.add.text(120, 825, "", { fontFamily: "Arial", fontSize: 22, color: "#ffffff" }).setOrigin(0.5).setVisible(false).setDepth(111);
        
        this.txtBalance = this.add.text(120, 825, "", { fontFamily: "Arial", fontSize: 22, fontStyle: "bold", color: "#ffffff" }).setOrigin(0.5).setScale(1.1).setDepth(111);
        this.txtBonus = this.add.text(120, 825, "", { fontFamily: "Arial", fontSize: 22, fontStyle: "bold", color: "#c6e304" }).setOrigin(0.5).setScale(1.1).setDepth(111);

        this.balanceRealCounter = new AnimatedAmount2(this, 120, 867, { fontFamily: "Arial", fontSize: 50, fontStyle: "bold", color: "#ffffff" }, false, 250);
        this.balanceRealCounter.setOrigin(0.5);
        this.balanceRealCounter.setDepth(110);

        this.balanceBonusCounter = new AnimatedAmount2(this, 120, 867, { fontFamily: "Arial", fontSize: 50, fontStyle: "bold", color: "#c6e304" }, false, 250);
        this.balanceBonusCounter.setOrigin(0.5);
        this.balanceBonusCounter.setDepth(110);

        this.txtBet = this.add.text(1530, 825, "", { fontFamily: "Arial", fontSize: 22, fontStyle: "bold", color: "#ffffff" }).setOrigin(0.5).setScale(1.1).setDepth(111);

        this.animBet = this.add.text(1270, 700, "", { fontFamily: "Arial", fontSize: 50, fontStyle: "bold", color: "#ffffff" }).setOrigin(1.0).setDepth(111);
        
        this.txtWin = this.add.text(120, 725, "", { fontFamily: "Arial", fontSize: 22, color: "#ffffff" }).setOrigin(0).setVisible(false).setDepth(111);
        
        this.gameState = GAME_STATE_NOT_INITIALIZED;

        let spinBtnData = {
            "scene": this,
            "key":"spinBtn",
            "onClick": this.spin,
            "onPressed": null,
            "onHold": this.spinHold
        }

        this.spinBtn = this.scene.add("SpinBtn", SceneButton, true, spinBtnData);

        let stopBtnData = {
            "scene": this,
            "key":"stopBtn",
            "onClick": this.stop,
            "onPressed": null,
            "onHold": null
        }

        this.stopBtn = this.scene.add("StopBtn", SceneButton, true, stopBtnData);

        this.stopBtn.setCanWake(stopBtnEnabled);

        let autoSelBtnData = {
            "scene": this,
            "key":"autoPlayBtn",
            "onClick": this.autoSel,
            "onPressed": null,
            "onHold": null
        }

        this.autoSelBtn = this.scene.add("AutoSelBtn", SceneButton, true, autoSelBtnData);

        let autoStopBtnData = {
            "scene": this,
            "defaultBtnKey":"autoStopBtn",
            "extraBtnKey": "autoStopCounterBtn",
            "onClick": this.autoStop,
            "onPressed": null,
            "onHold": null,
            "cntfont": { fontFamily: "Arial", fontSize: 72, fontStyle: "bold", color: "#ffffff" },
            "txtfont": { fontFamily: "Arial", fontSize: 48, fontStyle: "bold", color: "#ffffff" },
        }

        this.autoStopBtn = this.scene.add("AutoStopBtn", SceneButtonCounter, true, autoStopBtnData);

        let connectBtnData = {
            "scene": this,
            "key":"connectBtn",
            "onClick": this.connect,
            "onPressed": null,
            "onHold": null
        }

        this.connectBtn = this.scene.add("ConnectBtn", SceneButton, true, connectBtnData);

        let betBtnData = {
            "scene": this,
            "key":"betBtn",
            "onClick": this.bet,
            "onPressed": null,
            "onHold": null
        }

        this.betBtn = this.scene.add("BetBtn", SceneButton, true, betBtnData);

        let collectBtnData = {
            "scene": this,
            "key":"collectBtn",
            "onClick": this.collect,
            "onPressed": null,
            "onHold": null
        }

        this.collectBtn = this.scene.add("CollectBtn", SceneButton, true, collectBtnData);

        let collectCashbackBtnData = {
            "scene": this,
            "key":"takeBtn",
            "onClick": this.collectCashback,
            "onPressed": null,
            "onHold": null
        };

        this.collectCashbackBtn = this.scene.add("TakeCashbackBtn", SceneButton, true, collectCashbackBtnData);
        
        let homeBtnData = {
            "scene": this,
            "key":"homeBtn",
            "onClick": this.home,
            "onPressed": null,
            "onHold": null
        };

        this.homeBtn = this.scene.add("HomeBtn", SceneButton, true, homeBtnData);

        this.homeBtn.setCanWake(homeBtnEnabled(this));
        
        let settingsBtnData = {
            "scene": this,
            "key":"settingsBtn",
            "onClick": this.gameSettings,
            "onPressed": null,
            "onHold": null
        };

        this.settingsBtn = this.scene.add("SettingsBtn", SceneButton, true, settingsBtnData);
        this.settingsBtn.setScale(0.56);

        let turboOnOffBtnData = {
            "scene": this,
            "key":"turboOnOffBtn",
            "onClick": this.spinMode,
            "onPressed": null,
            "onHold": null
        };

        this.turboOnOff = this.scene.add("TurboOnOffBtn", SceneButtonOnOff, true, turboOnOffBtnData);

        this.turboOnOff.setCanWake(turboBtnEnabled);

        let bonusBtnData = {
                "scene": this,
                "key":"bonusBtn",
                "over": 0,
                "down": 0,
                "onClick": this.bonusBuy,
                "onPressed": null,
                "onHold": null
            };

        this.bonusBtn = this.scene.add("BonusBtn", SceneButton, true, bonusBtnData);

        this.bonusBtn.setCanWake(false);

        this.autoWin = 0;//accumulated win during last auto spins
        this.autoLoss = 0;//accumulated loss during last auto spins

        this.autoWinLimitSelected = 0;//selected auto win limit, range (0 - autoWinLimit (from config))
        this.autoLossLimitSelected = 0;//selected auto loss limit, range (0 - autoWinLimit (from config))

        this.sndWin = this.sound.add("win");
        this.sndWin.setLoop(true);
        this.sndBonusWin = this.sound.add("bonusWin");
        this.sndWinToCredit = this.sound.add("winToCredit");
        this.sndWinToCreditEnd = this.sound.add("winToCreditEnd");
                
        this.sndBackground = new CustomSound(this, "spin", true, this.sound.mute, 1500);

        this.sndBreak = [];

        this.sndBreak.push(this.sound.add("special"));
        this.sndBreak.push(this.sound.add("special_end"));

        let bwrt = 0;

        if (this.config.hasOwnProperty("bigWinRatioThreshold"))
        {
            let v = parseInt(this.config.bigWinRatioThreshold);

            if (Number.isInteger(v))
            {
                bwrt = v;
            }
        }

        this.shatter = this.scene.add("SceneShatterImage", SceneShatterImage, true, {scene: this});
        
        //win
        this.tw = this.scene.add("TotalWin", TotalWin, true, { scene: this, bwrt: bwrt, sndWin: this.sndWin, sndWinToCredit: this.sndWinToCredit, sndWinToCreditEnd: this.sndWinToCreditEnd});
        
        //cashback win
        this.cw = this.scene.add("CashBackWin", CashBackWin, true, {scene: this, sndCashbackWin: this.sndBonusWin, sndWinToCredit: this.sndWinToCredit, sndWinToCreditEnd: this.sndWinToCreditEnd});
        
        //legal limit        
        this.ll = this.scene.add("SceneLegalLimit", SceneLegalLimit, true, {scene: this, lang: this.lang});

        //jackpot start//coinrain

        this.crintro = this.scene.add("SceneCoinrainIntro", SceneCoinrainIntro, true, {scene: this, lang: this.lang});
        this.crplay = this.scene.add("SceneCoinrainPlay", SceneCoinrainPlay, true, {scene: this, lang: this.lang, jackpotLockVisible: jackpotLockVisible});

        this.jackpots = this.scene.add("SceneJackpots", SceneJackpots, true, {scene: this, jackpotLockVisible: jackpotLockVisible});

        this.selbet = this.scene.add("SceneBet", SceneBet, true, {scene: this, betSelect: this.betSelect.bind(this), betChange: this.jackpots.betChange.bind(this.jackpots)});
        this.selauto = this.scene.add("SceneAuto", SceneAuto, true, {scene: this, lang: this.lang, autoSpinSelect: this.autoSelect.bind(this), config: this.config});
        this.selbonus = this.scene.add("SceneBonus", SceneBonus, true, {scene: this, selectBonus: this.bonusSel.bind(this), cancelBonus: this.bonusSelClose.bind(this)});

        this.error = this.scene.add("SceneError", SceneError, true, {scene: this });
        this.betlimit = this.scene.add("SceneBetLimit", SceneBetLimit, true, {scene: this, lang: this.lang, betLimitHandler: this.onReelsReady.bind(this), balanceRestoreHandler: this.balanceRestore.bind(this)});

        this.emitter = this.scene.add("SceneEmitter", SceneEmitter, true, { scene: this });

        this.balancePollTimer = BALANCE_POLL_TIME;

        this.jackpotPollTimer = 100;

        this.sessionExpireTimer = SESSION_TIMEOUT;

        this.gameSessionReady = false;

        this.balance = 0;
        this.balanceReal = 0;
        this.balanceBonus = 0;

        this.balancePrev = 0;
        this.balanceRealPrev = 0;
        this.balanceBonusPrev = 0;

        this.balanceRealCounter.reset(this.balanceReal);
        this.balanceBonusCounter.reset(this.balanceBonus);

        this.currencyPrecision = 2;//decimal points

        this.autoSpinEnabled = false;
        this.currentGame = null;
        
        this.spinHoldActive = false;//spin button is pressed and held
        this.spinFastMode = false;//when start is clicked, fast spin if true, normal spin if false 
        
//read auto start type
        
        this.autoState = AUTO_START_ENABLED_SELECT_SPINS;

        if (this.config.hasOwnProperty("autoStart"))
        {
            let v = parseInt(this.config.autoStart);

            if (Number.isInteger(v) && (v == AUTO_START_DISABLED || v == AUTO_START_ENABLED || v == AUTO_START_ENABLED_SELECT_SPINS))
            {
                this.autoState = v;

                if (this.autoState == AUTO_START_DISABLED)
                {
                    this.autoSelBtn.setCanEnable(false);
                    this.autoSelBtn.disable();
                }
            }
        }
        
        this.autoSpinLimit = this.conf.autoSpinLimit;

        this.errorPending = false;
        this.errorMessage = "";
        this.errorExtraMessage = "";
        this.errorWalletMessage = "";
        this.errorCode = 0;
        this.walletFailureCode = 0;
        this.walletAPIFailureCode = 0;
        this.criticalError = false;

        this.leftHandMode = false;
        this.swipeToSpin = true;

        this.swipeBoundsL = new Phaser.Geom.Rectangle(0, 220, 1920, 730);
        this.swipeBoundsP = new Phaser.Geom.Rectangle(0, 250, 1080, 1500);

        this.swipe = null;

        this.swipe = this.gestures.add.swipe(
        {
            threshold: 10,
            velocityThreshold: 250,
            dir: "up&down"
        });

        this.swipe.on("swipe", this.onSwipe.bind(this));

        this.sound.pauseOnBlur = false;//do not stop web audio if game loses focus
        this.input.keyboard.enabled = true;

        this.keyLayout = this.input.keyboard.addKey("P");
        this.keyLayout.on("down", this.onChangeLayout, this);

        this.keySpin = this.input.keyboard.addKey("SPACE");
        this.keySpin.on("down", this.kbdSpin, this);

        this.server = document.getElementById("Hostname").value;
        this.port = document.getElementById("Port").value;
        this.token = document.getElementById("WalletToken").value;
        this.gameid = document.getElementById("gameId").value;
        this.userid = document.getElementById("userId").value;
        this.casinoid = document.getElementById("casinoId").value;
        this.lobbyUrl = document.getElementById("lobbyUrl").value;

        this.currency = "";
        this.originid = "";
        this.bonusid = "";
        this.lobbyUrlTarget = "";
        this.enablePostMessages = "";

        if ( !!document.getElementById("currency") )
        {
            this.currency = document.getElementById("currency").value;
        }

        if ( !!document.getElementById("originId") )
        {
            this.originid = document.getElementById("originId").value;
        }

        if ( !!document.getElementById("bonusId") )
        {
            this.bonusid = document.getElementById("bonusId").value;
        }

        if ( !!document.getElementById("lobbyUrlTarget") )
        {
            this.lobbyUrlTarget = document.getElementById("lobbyUrlTarget").value;
        }

        if ( !!document.getElementById("enablePostMessages") )
        {
            this.enablePostMessages = document.getElementById("enablePostMessages").value;
        }

        if (this.hasOwnProperty("gameSocket") && this.gameSocket != null)
        {
            this.gameSocket.sendCmdChallenge();
        }
        else
        {
            this.gameSocket = null;

            if (this.server != "" && this.port != "" && this.token != "" && this.gameid != "" && this.userid != "" && this.casinoid != "")
            {
                this.gameSocket = new GameSocket(this, this.server, this.port, protocol_id, this.token, this.userid, this.gameid, this.casinoid, this.currency, this.originid, this.bonusid);
            }
        }

        if (screen.orientation && screen.orientation.addEventListener)
        {
            screen.orientation.addEventListener("change", this.onOrientationChange.bind(this), false);
        }
        else
        {
            window.addEventListener("orientationchange", this.onOrientationChange.bind(this), false);
        }

        this.game.canvas.addEventListener("webglcontextlost", this.onContextLost.bind(this), false);

        this.events.on("transitionwake", this.onTransitionWake, this);
        this.events.on("transitioncomplete", this.onTransitionComplete, this);//called after jackpot play is finished

        this.currentTime = null;

        this.wakelock = null;

        this.timerEvent = null;
    }

    onContextLost()
    {
        this.game.canvas.removeEventListener("webglcontextlost", this.onContextLost);
        reloadGame(this);
    }

    onFocus ()
    {
        this.lockWakeState();

        this.onOrientationChange();
    }

    onBlur ()
    {
       this.releaseWakeState();

       this.input.on("pointerup", this.onPointerUp, this);
    }

    onTransitionWake ()
    {
        this.gameSocket.jpwinindex = 0;//show jacpots after jackpot win
        this.jackpots.reset();
    }

    onTransitionComplete ()
    {
        if (this.crintro.fx != null)
        {
            this.crintro.cameras.main.postFX.remove(this.crintro.fx);
            this.crintro.fx = null;
        }

        if (this.crplay.fx != null)
        {
            this.crplay.cameras.main.postFX.remove(this.crplay.fx);
            this.crplay.fx = null;
        }

        this.scene.wake();
        this.scene.bringToTop();

        this.jackpots.wake();

        let jl = this.gameSocket.getJackpotLegalLimit();
        let jw = this.gameSocket.getJackpotWin() + this.gameSocket.getJackpotExtraWin();

        if (jl > 0 && jw >= jl)
        {
            this.ll.show(jw);
            this.time.delayedCall(LEGAL_LIMIT_DISPLAY_TIME, this.onJackpotComplete, [], this);
        }
        else
        {
            this.onJackpotComplete();
        }
    }

    onJackpotComplete ()
    {
        if (this.getTotalWin() > 0)
        {
            this.gameState = GAME_STATE_TOTAL_WIN;

            this.spinBtn.wake();
            this.collectBtn.wake();
            this.turboOnOff.wake(); 
            
            if (this.gameSocket.getBalance() >= this.gameSocket.getBet())
            {
                this.spinBtn.enable();
            }
            else
            {
                this.spinBtn.disable();
            }

            this.tw.wake();
            this.tw.setDisplayWinCombinations(true);

            this.rm.playTotalWin();
        }
        else if (this.gameSocket.getCashbackWin() > 0)
        {
            this.gameState = GAME_STATE_CASHBACK_WIN;
            this.cw.start();
        }
        else
        {
            this.gameState = GAME_STATE_READY;

            if (this.errorPending)
            {
                this.showError();
                return;
            }
        
            this.buttonsWake();

            if (this.gameSocket.getBalance() >= this.gameSocket.getBet())
            {
                this.spinBtn.enable();
                this.autoSelBtn.enable();
            }
            else
            {
                this.spinBtn.disable();
                this.autoSelBtn.disable();
            }
        }
    }

    onPointerUp ()
    {
        if (!this.sys.game.device.os.desktop && this.sys.game.device.fullscreen.available)
        {
            this.scale.startFullscreen();
            this.lockWakeState();
        }            

        this.input.off("pointerup", this.onPointerUp, this);
    }

    async lockWakeState ()
    {
        if(!canWakeLock())
        { 
            return;
        }

        if (!this.sys.game.device.os.desktop && this.sys.game.device.fullscreen.available)
        {
            try
            {
                this.wakelock = await navigator.wakeLock.request();

                this.wakelock.addEventListener("release", () => 
                {
                    console.log("Screen Wake State Locked: ", !this.wakelock.released);
                });

                console.log("Screen Wake State Locked: ", !this.wakelock.released);
            }
            catch(e)
            {
                console.error("Failed to lock wake state with reason: ", e.message);
            }
        }
    }

    releaseWakeState ()
    {
        if (this.wakelock) 
        {
            this.wakelock.release();
            this.wakelock = null;
        }
    }

    reloadGame ()
    {
        reloadGame(this);
    }

    isLandscapeMode ()
    {
        return (this.scale.orientation === "landscape" || this.scale.orientation === "landscape-primary" || this.scale.orientation === "landscape-secondary");
    }

    isPortraitMode ()
    {
        return (this.scale.orientation === "portrait" || this.scale.orientation === "portrait-primary" || this.scale.orientation === "portrait-secondary");
    }

    onOrientationChange (event)
    {
        if (this.gameState == GAME_STATE_NOT_INITIALIZED) 
        {
            return;
        }

        let orientation = 0;

        if (screen.orientation.hasOwnProperty("angle"))
        {
            orientation = screen.orientation.angle;
        }
        else if (window.hasOwnProperty("orientation"))
        {
            orientation = window.orientation;
        }
        else
        {
            return;
        }
        
        if (orientation == 0 || orientation == 180)
        {
            this.setPortraitLayout();
        }
        else if (orientation == 90 || orientation == -90 || orientation == 270)
        {
            this.setLandscapeLayout();
        }
    }

    setLandscapeLayout ()
    {
        this.scale.orientation = Phaser.Scale.LANDSCAPE;
        this.scale.setGameSize(GAME_LANDSCAPE_WIDTH, GAME_LANDSCAPE_HEIGHT);

        this.swipe.setDetectBounds(this.swipeBoundsL);

        this.bgrmain.setPosition(960, 540)
        this.bgrmain.setAngle(90);

        this.logoL.setVisible(true);

        this.logoP.setVisible(false);
        this.logoSymP.setVisible(false);

        this.bonusBtn.setPosition(1600, 1000);
        this.bonusBtn.setScale(0.7);

        this.barP.setPosition(960, 1032);

        this.bonusL.setVisible(this.balanceBonus > 0);

        this.bonusP.setVisible(false);

        this.txtInfo.setPosition(1380, 1064).setScale(1.0);

        this.txtGame.setPosition(GAME_LANDSCAPE_WIDTH / 2, 1064).setScale(1.0);
        this.txtTime.setPosition(550, 1064).setScale(1.0);

        this.txtBalance.setPosition(540, 971);

        this.txtBonus.setPosition(300, 971);

        this.balanceRealCounter.setPosition(550, 1013);
        this.balanceBonusCounter.setPosition(300, 1013);

        this.txtBet.setPosition(1380, 971);

        this.animBet.setPosition(1470, 1041);

        this.txtWin.setPosition(430, 925).setScale(1.0);

        if (this.rm != undefined)
        {
            this.rm.onOrientationChange();
        }

        this.error.onOrientationChange();
        this.betlimit.onOrientationChange();
        this.jackpots.onOrientationChange();
        this.settings.onOrientationChange();
        
        this.tw.onOrientationChange();
        this.cw.onOrientationChange();

        this.crintro.onOrientationChange();
        this.crplay.onOrientationChange();

        this.ll.onOrientationChange(0);

        if (this.ll.scene.isVisible())
        {
            this.ll.scene.bringToTop();
        }

        this.selbet.onOrientationChange();
        this.selauto.onOrientationChange();
        this.selbonus.onOrientationChange();

        this.emitter.onOrientationChange();

        this.spinBtn.setPosition(1746, 521);
        this.spinBtn.scene.bringToTop();

        this.autoSelBtn.setPosition(1757, 282);

        if (!this.turboOnOff.canWake)
        {
            this.betBtn.setPosition(1757, 760);
            this.homeBtn.setPosition(1768, 914);
        }
        else
        {
            this.betBtn.setPosition(1757, 860);
            this.homeBtn.setPosition(1768, 1014);
        }

        this.settingsBtn.setPosition(1768, 130);

        this.autoSelBtn.scene.bringToTop();

        this.betBtn.scene.bringToTop();

        this.stopBtn.setPosition(1746, 521);
        this.stopBtn.scene.bringToTop();

        this.autoStopBtn.setPosition(1746, 521);
        this.autoStopBtn.setScale(0.85);

        if (this.autoSpinEnabled)
        {
            this.autoStopBtn.scene.bringToTop();
        }

        this.connectBtn.setPosition(1746, 521);
        this.connectBtn.scene.bringToTop();

        this.collectBtn.setPosition(1757, 860);
        
        this.homeBtn.scene.bringToTop();

        this.settingsBtn.scene.bringToTop();

        this.turboOnOff.setPosition(1746, 719);
        this.turboOnOff.scene.bringToTop();

        this.collectCashbackBtn.setPosition(1746, 521);

        this.jackpots.scene.bringToTop();

        if (this.gameState == GAME_STATE_JACKPOT_WIN)
        {
            this.crintro.bringToTop();
            this.crplay.scene.bringToTop();
        }

        if (this.selbet.scene.isVisible())
        {
            let v = this.selbet.getBetIndex();

            this.buttonsWake(v);
        }
        else
        {
            if (!this.settings.scene.isVisible() && (this.gameState == GAME_STATE_READY || this.gameState == GAME_STATE_PLAY_WIN))
            {
                this.buttonsWake();
            }
        }

        if (this.selbonus.scene.isVisible())
        {
            this.selbonus.bringToTop();
        }

        if (this.emitter.scene.isVisible())
        {
            this.emitter.scene.bringToTop();
        }

        if (this.error.scene.isVisible())
        {
            this.error.scene.bringToTop();
        }

        this.betlimit.bringToTop();
    }
    
    setPortraitLayout ()
    {
        this.scale.orientation = Phaser.Scale.PORTRAIT;
        this.scale.setGameSize(GAME_PORTRAIT_WIDTH, GAME_PORTRAIT_HEIGHT);

        this.swipe.setDetectBounds(this.swipeBoundsP);

        this.logoL.setVisible(false);

        this.bgrmain.setPosition(540, 960);
        this.bgrmain.setAngle(0);

        if (!this.settings.scene.isVisible())
        {
            this.logoP.setVisible(true);
            this.logoSymP.setVisible(true);
        }

        if (!this.settings.scene.isVisible() && !this.selbet.scene.isVisible() && (this.gameState == GAME_STATE_READY || this.gameState == GAME_STATE_PLAY_WIN))
        {
            if (this.gameSocket.callForBonusBetAllowed())
            {
                this.bonusBtn.wake();
            }
            else
            {
                this.bonusBtn.sleep();
            }
        }
        else
        {
            this.bonusBtn.sleep();
        }

        this.bonusBtn.setPosition(875, 1679);
        this.bonusBtn.setScale(1.0);

        this.barP.setPosition(540, 1872);

        this.bonusL.setVisible(false);
        
        this.bonusP.setVisible(this.balanceBonus > 0);

        this.txtInfo.setPosition(945, 1900).setScale(1.30);
        this.txtGame.setPosition(GAME_PORTRAIT_WIDTH / 2, 1900).setScale(1.30);
        this.txtTime.setPosition(120, 1900).setScale(1.30);

        this.txtWin.setPosition(10, 1295).setScale(1.25);

        this.txtBalance.setPosition(115, 1809);

        this.txtBonus.setPosition(115, 1719);

        this.balanceRealCounter.setPosition(125, 1854);
        this.balanceBonusCounter.setPosition(125, 1760);

        this.txtBet.setPosition(960, 1809);

        this.animBet.setPosition(1050, 1880);

        this.tw.onOrientationChange();
        this.cw.onOrientationChange();

        this.crintro.onOrientationChange();
        this.crplay.onOrientationChange();

        this.ll.onOrientationChange(800);

        if (this.ll.scene.isVisible())
        {
            this.ll.scene.bringToTop();
        }

        this.error.onOrientationChange();
        this.betlimit.onOrientationChange();
        this.jackpots.onOrientationChange();
        this.settings.onOrientationChange();

        this.selbet.onOrientationChange();
        this.selauto.onOrientationChange();
        this.selbonus.onOrientationChange();

        this.emitter.onOrientationChange();

        this.spinBtn.setPosition(540, 1489);
        this.spinBtn.scene.bringToTop();

        if (this.leftHandMode)
        {
            this.autoSelBtn.setPosition(790, 1478);
            this.betBtn.setPosition(289, 1479);
            this.homeBtn.setPosition(123, 1468);
            this.settingsBtn.setPosition(955, 1468);
        }
        else
        {
            this.autoSelBtn.setPosition(289, 1479);
            this.betBtn.setPosition(790, 1478);
            this.homeBtn.setPosition(955, 1468);
            this.settingsBtn.setPosition(123, 1468);
        }

        this.autoSelBtn.scene.bringToTop();

        this.betBtn.scene.bringToTop();

        this.stopBtn.setPosition(540, 1489);
        this.stopBtn.scene.bringToTop();

        this.autoStopBtn.setPosition(540, 1489);
        this.autoStopBtn.setScale(1.0);

        this.connectBtn.setPosition(540, 1489);
        this.connectBtn.setScale(1.0);

        this.collectBtn.setPosition(790, 1478);

        this.homeBtn.scene.bringToTop();
  
        this.settingsBtn.scene.bringToTop();
        
        this.turboOnOff.setPosition(540, 1689);
        this.turboOnOff.scene.bringToTop();

        this.collectCashbackBtn.setPosition(540, 1489);
        this.collectCashbackBtn.setScale(1.0);
        
        if (this.rm != undefined)
        {
            this.rm.onOrientationChange();
        }

        this.error.scene.bringToTop();

        this.jackpots.scene.bringToTop();

        this.tw.scene.bringToTop();

        if (this.gameState == GAME_STATE_JACKPOT_WIN)
        {
            this.crintro.bringToTop();
            this.crplay.scene.bringToTop();
        }

        if (this.gameState == GAME_STATE_CASHBACK_WIN)
        {
            this.cw.scene.bringToTop();
        }

        if (this.selbet.scene.isVisible())
        {
            this.settingsBtn.sleep();
            this.autoSelBtn.sleep();
            this.spinBtn.sleep();
            this.betBtn.sleep();
            this.homeBtn.sleep();
            this.turboOnOff.sleep();
        }

        if (this.selbonus.scene.isVisible())
        {
            this.selbonus.bringToTop();
        }

        if (this.emitter.scene.isVisible())
        {
            this.emitter.scene.bringToTop();
        }

        this.betlimit.bringToTop();
    }

    update (time, delta) 
    {
        if (this.gameState == GAME_STATE_NOT_INITIALIZED)
        {
            return;
        }

        if (this.hasOwnProperty("rm"))
        {
            this.rm.update(time, delta);
        }

        if (this.gameState == GAME_STATE_ERROR)
        {
            return;
        }

        this.updateSessionTimeout(delta);
        this.updateBalance(delta);
        this.updateJackpots(delta);
    }

    updateSessionTimeout (delta)
    {
        if ((this.gameState == GAME_STATE_READY || this.gameState == GAME_STATE_PLAY_WIN) && !this.autoSpinEnabled)
        {
            if (this.sessionExpireTimer >= 0)
            {
                this.sessionExpireTimer -= delta;

                if (this.sessionExpireTimer < 0)
                {
                    this.gameSocket.disconnect();
                    this.gameState = GAME_STATE_NOT_INITIALIZED;
                }
            }
        }
    }

    updateBalance (delta)
    {
        if ((this.gameState == GAME_STATE_READY || this.gameState == GAME_STATE_PLAY_WIN) && !this.autoSpinEnabled)
        {
            if (this.balancePollTimer >= 0)
            {
                this.balancePollTimer -= delta;
    
                if (this.balancePollTimer < 0)
                {
                    this.gameSocket.queryBalance();
                    this.balancePollTimer = BALANCE_POLL_TIME;
                }
            }

            if (!this.errorPending)
            {
                if (this.balance < this.gameSocket.getBet())
                {
                    if (this.error.scene.isSleeping())
                    {
                        this.error.setBlinkingMessage(this.getText(GLOBAL_TXT_GAMESOCKET_NOT_ENOUGH_CREDIT_ERROR));
                    }
                    else if (!this.error.scene.isVisible())
                    {
                        this.error.scene.setVisible(true);
                        this.error.scene.bringToTop();
                    }
                }
                else if (this.error.scene.isVisible())
                {
                    this.error.clearMessage();
                }
            }                
        }
    }

    updateJackpots (delta)
    {
        if (this.gameState == GAME_STATE_NOT_INITIALIZED || this.gameState == GAME_STATE_ERROR)
        {
            return;
        }

        if (!this.gameSocket.isJackpotEnable())
        {
            return;
        }

        if (this.jackpotPollTimer >= 0)
        {
            this.jackpotPollTimer -= delta;

            if (this.jackpotPollTimer < 0)
            {
                this.gameSocket.queryJackpots();
                this.jackpotPollTimer = JACKPOT_POLL_TIME;
            }
        }
    }

    spin (bt)
    {
        if (bt == undefined)
        {
            bt = BET_TYPE_NORMAL;
        }
        
        if (this.selauto.scene.isVisible())
        {
            this.autoSelClose();
        }

        if (this.selbet.scene.isVisible())
        {
            this.betSelClose();
        }

        if (this.balance < this.gameSocket.getBet(bt))
        {
            this.buttonsWake();

            this.spinBtn.disable();
            this.autoSelBtn.disable();

            if (this.error.scene.isVisible())
            {
                this.error.scene.bringToTop();
            }

            return;
        }

        if (this.currentGame != null && this.currentGame.legalLimitApplied && this.ll.scene.isSleeping())
        {
            this.ll.show(this.getTotalWin());
            this.tw.sleep();
        }
        else if (this.gameState == GAME_STATE_TOTAL_WIN)
        {
            this.tw.wake();

            if (this.balance < this.gameSocket.getBalance())//spin button pressed while displaying win
            {
                this.balance = this.gameSocket.getBalance();
            }
        }
            
        this.tw.forceSleep(this.getTotalWin());
        
        this.betWithdraw(this.gameSocket.getBet(bt));

        this.balanceUpdate();

        if (this.spinHoldActive)
        {
            this.spinBtn.scene.bringToTop();
        }
        else
        {
            this.spinBtn.sleep();
        }

        this.homeBtn.sleep();
        this.settingsBtn.sleep();
        this.betBtn.sleep();
        this.autoSelBtn.sleep();
        this.turboOnOff.sleep();
        this.bonusBtn.sleep();
        
        if (!this.selauto.scene.isSleeping())
        {
            this.settingsBtn.enable();
            this.betBtn.enable();
        }

        if (this.gameState == GAME_STATE_TOTAL_WIN)
        {
            this.collectBtn.sleep(true);
        }

        this.rm.beginSpinReels();

        this.sentPacketTime = new Date();

        this.gameState = GAME_STATE_SERVER_RESPONSE_PENDING;

        this.gameSocket.spin(bt);
    }
    
    kbdSpin ()
    {
        if (this.autoSpinEnabled)
        {
            return;
        }

        if (this.spinHoldActive)
        {
            return;
        }

        if (this.selbonus.scene.isVisible())
        {
            return;
        }

        if (this.gameState == GAME_STATE_TOTAL_WIN && this.spinBtn.scene.isVisible())
        {
            this.spin();
        }
        else if (this.gameState == GAME_STATE_READY || this.gameState == GAME_STATE_PLAY_WIN)
        {
            this.spin();
        }
    }

    autoSel ()
    {
        if (this.selauto.scene.isVisible())
        {
            this.autoSelClose();
            return;
        }
        
        if (this.autoState == AUTO_START_DISABLED)
        {
            this.spin();
            
            return;
        }
        else if (this.autoState == AUTO_START_ENABLED)
        {
            this.autoSpinEnabled = true;
            this.autoSpinLimit = AUTO_SPIN_UNLIMITED;

            this.autoStopBtn.wake();
        
            if (this.autoSpinLimit > 0)
            {
                this.autoStopBtn.startCountdown();
                this.autoStopBtn.setCounter(this.autoSpinLimit);
            }            
        
            this.spin();
        }
        else if (this.autoState == AUTO_START_ENABLED_SELECT_SPINS)
        {
            this.tw.sleep();
    
            this.txtWin.setVisible(false);

            if (this.selbet.scene.isVisible())
            {
                this.betSelClose();
            }

            this.input.on("pointerdown", this.autoSelClose, this);

            this.selauto.wake();
        }
    }

    autoSelect (v)
    {
        this.autoSelClose();

        this.autoSpinEnabled = true;
        this.autoSpinLimit = v;

        this.settingsBtn.sleep();
        this.autoSelBtn.sleep();
        this.spinBtn.sleep();
        this.betBtn.sleep();
        this.homeBtn.sleep();
        this.turboOnOff.sleep();
        this.bonusBtn.sleep();

        this.tw.sleep();

        this.autoStopBtn.wake();

        if (this.autoSpinLimit > 0)
        {
            this.autoStopBtn.setValue(this.autoSpinLimit);
            this.autoStopBtn.startCountdown();
        }

        this.autoWin = 0;
        this.autoLoss = 0;

        this.startAutoSpin();
    }

    autoSelClose ()
    {
        if (this.selauto.scene.isVisible())
        {
            this.selauto.sleep();

            this.input.off("pointerdown", this.autoSelClose, this);
        }

        if (this.getTotalWin() > 0)
        {
            this.tw.wake();
        }

        if (this.gameState == GAME_STATE_PLAY_WIN)
        {
            this.txtWin.setVisible(true);
        }
    }

    spinHold ()
    {
        this.spinHoldActive = !this.spinHoldActive;

        if (this.spinHoldActive)
        {
            this.spin();
        }
        else
        {
            if (this.gameState == GAME_STATE_SERVER_RESPONSE_PENDING ||
                this.gameState == GAME_STATE_SPIN ||
                this.gameState == GAME_STATE_JACKPOT_WIN ||
                this.gameState == GAME_STATE_TOTAL_WIN ||
                this.gameState == GAME_STATE_CASHBACK_WIN)
            {
                this.homeBtn.sleep();
                this.settingsBtn.sleep();
                this.betBtn.sleep();
                this.autoSelBtn.sleep();

                if (this.gameState == GAME_STATE_TOTAL_WIN)
                {
                    this.collectBtn.wake();
                    this.turboOnOff.wake();
                }

                if (this.gameState == GAME_STATE_SERVER_RESPONSE_PENDING || this.gameState == GAME_STATE_SPIN)
                {
                    this.spinBtn.sleep();
                }
                else if (this.gameSocket.getJackpotWin() > 0 || this.gameSocket.getCashbackWin() > 0)
                {
                    this.spinBtn.sleep();
                }
            }
            else
            {
                this.homeBtn.wake();
                this.settingsBtn.wake();
                this.betBtn.wake();
                this.autoSelBtn.wake();
                this.turboOnOff.wake();
            }
        }
    }

    spinMode ()
    {
        this.spinFastMode = !this.spinFastMode;

        if (this.spinFastMode)
        {
            this.turboOnOff.setFrame("ON");
        }
        else
        {
            this.turboOnOff.setFrame("OFF");
        }
    }

    connect ()
    {
        this.errorPending = false;
        this.criticalError = false;

        this.error.clearMessage();
        
        this.connectBtn.disable();

        this.gameSocket.connect();
    }

    startAutoSpin ()
    {
        if (this.balance < this.gameSocket.getBet() || this.autoSpinLimit == 0 ||
           (this.autoWinLimitSelected > 0 && this.autoWin > this.autoWinLimitSelected) || 
           (this.autoLossLimitSelected > 0 && this.autoLoss > this.autoLossLimitSelected) )
        {
            this.autoSpinEnabled = false;

            this.autoStopBtn.sleep();

            this.buttonsWake();

            if (this.balance < this.gameSocket.getBet())
            {
                this.spinBtn.disable();
                this.autoSelBtn.disable();

                if (this.error.scene.isVisible())
                {
                    this.error.scene.bringToTop();
                }
            }
            else
            {
                this.spinBtn.enable();
                this.autoSelBtn.enable();
            }                
            
            return;
        }
        else
        {
            this.betWithdraw(this.gameSocket.getBet());
            
            this.autoLoss += this.gameSocket.getBet();
        }

        if (this.currentGame != null && this.currentGame.legalLimitApplied && this.ll.scene.isSleeping())
        {
            this.ll.show(this.gameSocket.getTotalWin());
            this.tw.sleep();

            this.time.delayedCall(AUTO_SPIN_LEGAL_LIMIT_DELAY, this.beginAutoSpin, [], this);
            return;
        }
        else 
        {
            this.tw.forceSleep(this.getTotalWin());
        }

        this.beginAutoSpin();
    }

    beginAutoSpin ()
    {
        this.rm.beginSpinReels();

        this.sentPacketTime = new Date();

        this.gameState = GAME_STATE_SERVER_RESPONSE_PENDING;

        this.gameSocket.spin(BET_TYPE_NORMAL);
    }

    autoStop ()
    {
        this.autoSpinEnabled = false;
        this.autoStopBtn.sleep();
        
        if (this.gameState == GAME_STATE_SPIN)
        {
            if (this.rm.canShowStopBtn)
            {
                this.stopBtn.wake();
            }
        }
        else if (this.gameState == GAME_STATE_TOTAL_WIN)
        {
            if (this.gameSocket.getBalance() >= this.gameSocket.getBet())
            {
                this.spinBtn.wake();
                this.turboOnOff.wake(); 
                this.collectBtn.wake();
            }
        }
    }

    bet ()
    {
        this.autoSelClose();

        if (this.selbet.scene.isVisible())
        {
            this.betSelClose();
            return;
        }

        if (this.isPortraitMode())
        {
            this.settingsBtn.sleep();
            this.autoSelBtn.sleep();
            this.spinBtn.sleep();
            this.betBtn.sleep();
            this.homeBtn.sleep();
            this.turboOnOff.sleep();
            this.bonusBtn.sleep();
        }

        this.rm.setVisible(false);

        this.tw.sleep();

        this.txtWin.setVisible(false);

        this.input.on("pointerdown", this.betSelClose, this);

        this.selbet.wake();

        if (this.error.scene.isVisible())
        {
            this.error.scene.bringToTop();
        }
    }

    betSelect (index)
    {
        this.input.off("pointerdown", this.betSelClose, this);

        if (index == this.gameSocket.getBetSel() && this.gameState == GAME_STATE_PLAY_WIN)
        {
            this.txtWin.setVisible(true);
        }
        
        this.gameSocket.setBet(index);

        this.buttonsWake();

        this.rm.setVisible(true);

        if (this.getTotalWin() > 0)
        {
            this.tw.wake();
        }

        this.settings.updatePayInfo(this.gameSocket.getBetPerLine());

        if (this.balance >= this.gameSocket.getBet())
        {
            this.spinBtn.enable();
            this.autoSelBtn.enable();
        }
        else
        {
            this.spinBtn.disable();
            this.autoSelBtn.disable();

            if (this.error.scene.isVisible())
            {
                this.error.scene.bringToTop();
            }
        }

        this.betChange();

        if (this.gameState == GAME_STATE_ERROR)
        {
            this.error.scene.bringToTop();
        }
    }

    betSelClose ()
    {
        if (this.selbet.scene.isVisible())
        {
            this.selbet.sleep();
            
            this.input.off("pointerdown", this.betSelClose, this);
        }

        if (this.gameState != GAME_STATE_ERROR)
        {
            this.betBtn.enable();

            this.buttonsWake();

            if (this.gameSocket.getBalance() >= this.gameSocket.getBet())
            {
                this.spinBtn.enable();
                this.autoSelBtn.enable();
            }
            else
            {
                this.spinBtn.disable();
                this.autoSelBtn.disable();
            }
        }

        if (this.rm != undefined)
        {
            this.rm.setVisible(true);
        }

        if (this.getTotalWin() > 0)
        {
            this.tw.wake();
        }

        if (this.gameState == GAME_STATE_PLAY_WIN)
        {
            this.txtWin.setVisible(true);
        }

        this.jackpots.betChange(this.gameSocket.getBetSel());
    }

    bonusBuy ()
    {
        if (this.gameState != GAME_STATE_READY && this.gameState != GAME_STATE_PLAY_WIN)
        {
            return;
        }

        if (!this.gameSocket.callForBonusBetAllowed())
        {
            return;
        }

        if (this.settings.scene.isVisible() || this.selbet.scene.isVisible() || this.selauto.scene.isVisible() )
        {
            return;//to do close each above scene instead
        }

        if (this.selbonus.scene.isVisible())
        {
            this.bonusSelClose();
            return;
        }
        else
        {
            this.tw.sleep();

            this.buttonsDisable();

            this.input.on("pointerdown", this.bonusSelClose, this);

            this.selbonus.wake();
        }
    }

    bonusSel (bt)
    {
        this.selbonus.sleep();

        this.buttonsEnable();
        
        if (this.balance < this.gameSocket.getBet(bt))
        {
            return;
        }

        this.spin(bt);
    }

    bonusSelClose ()
    {
        if (this.selbonus.scene.isVisible())
        {
            this.selbonus.sleep();

            if (this.getTotalWin() > 0)
            {
                this.tw.wake();
            }

            this.buttonsEnable();

            this.input.off("pointerdown", this.bonusSelClose, this);
        }
    }

    bonusBetChange (v)
    {
        if (this.gameSocket.callForBonusBetAllowed(v))
        {
            if (this.isLandscapeMode())
            {
                this.bonusBtn.wake();
            }
        }
        else
        {
            this.bonusBtn.sleep();
        }
    }

    collect ()
    {
        this.tw.setWinCounter(this.getTotalWin());
        this.tw.forceClose(false);
        
        this.balanceUpdate2 (this.getTotalWin());

        this.sndWinToCreditEnd.play();

        if (this.errorPending)
        {
            this.showError();
            return;
        }

        this.homeBtn.wake();
        this.betBtn.wake();
        this.settingsBtn.wake();
        this.autoSelBtn.wake();
        this.turboOnOff.wake();

        if (this.gameSocket.getBalance() >= this.gameSocket.getBet() && !this.autoSpinEnabled)
        {
            this.spinBtn.wake();

            if (this.gameSocket.callForBonusBetAllowed())
            {
                this.bonusBtn.wake();
            }
            else
            {
                this.bonusBtn.sleep();
            }
        }
        
        if (this.currentGame.legalLimitApplied && this.ll.scene.isSleeping())
        {
            this.ll.show(this.getTotalWin());
        }
        
        this.rm.showWins();

        this.gameState = GAME_STATE_PLAY_WIN;
    }

    gameSettings ()
    {
        if (this.selauto.scene.isVisible())
        {
            this.autoSelClose();
        }

        if (this.selbet.scene.isVisible())
        {
            this.betSelClose();
        }

        this.settings.wake();

        if (this.isPortraitMode())
        {
            this.logoP.setVisible(false);
            this.logoSymP.setVisible(false);
        }

        this.rm.setVisible(false);

        this.tw.sleep();

        this.txtWin.setVisible(false);

        this.settingsBtn.sleep();
        this.spinBtn.sleep();
        this.autoSelBtn.sleep();
        this.betBtn.sleep();
        this.homeBtn.sleep();
        this.turboOnOff.sleep();
        this.bonusBtn.sleep();

        this.jackpots.sleep();

        if (this.error.scene.isVisible())
        {
            this.error.scene.bringToTop();
        }
    }

    settingsClose ()
    {
        if (!this.settings.scene.isSleeping())
        {
            let status = this.scene.getStatus(this.settings.scene.key);

            if (status < Phaser.Scenes.RUNNING)
            {
                return;
            }

            this.settings.sleep();
        }

        if (this.gameState != GAME_STATE_ERROR)
        {
            this.buttonsWake();
        }

        this.jackpots.wake();

        if (this.isPortraitMode())
        {
            this.logoP.setVisible(true);
            this.logoSymP.setVisible(true);
        }

        this.rm.setVisible(true);

        if (this.getTotalWin() > 0)
        {
            this.tw.wake();
        }

        if (this.gameState == GAME_STATE_PLAY_WIN)
        {
            this.txtWin.setVisible(true);
        }

        if (this.error.scene.isVisible())
        {
            this.error.scene.bringToTop();
        }
    }

    onLeftHandMode (v)
    {
        this.leftHandMode = v;

        let x = this.autoSelBtn.getX();
        let y = this.autoSelBtn.getY();

        this.autoSelBtn.setPosition(this.betBtn.getX(), this.betBtn.getY());
        this.autoSelBtn.scene.bringToTop();

        this.betBtn.setPosition(x, y);
        this.betBtn.scene.bringToTop();

        x = this.settingsBtn.getX();
        y = this.settingsBtn.getY();

        this.settingsBtn.setPosition(this.homeBtn.getX(), this.homeBtn.getY());
        this.settingsBtn.scene.bringToTop();

        this.homeBtn.setPosition(x, y);
        this.homeBtn.scene.bringToTop();
    }

    onSwipeToSpin (v)
    {
        this.swipeToSpin = v;

        this.swipe.setEnable(v);
    }

    onSwipe ()
    {
        if (this.cw.scene.isVisible() ||
            this.crintro.scene.isVisible() ||
            this.crplay.scene.isVisible() ||
            this.settings.scene.isVisible() ||
            this.selbet.scene.isVisible() ||
            this.selauto.scene.isVisible())
        {
            return;
        }

      
        if (this.spinBtn.sleeping)
        {
            return;
        }

        this.spin();
    }

    onChangeLayout ()
    {
        if (this.isLandscapeMode())
        {
            this.setPortraitLayout();
        }
        else
        {
            this.setLandscapeLayout();
        }
    }

    home ()
    {
        let lobbyEnabled = !!+this.config.lobbyEnabled;
        
        if (lobbyEnabled != null && !lobbyEnabled)//game lobby is disabled, go to casino id url instead
        {
            if (this.lobbyUrl != null && this.lobbyUrl != "")//if casino provided dynamic home url, use it
            {
                if (this.enablePostMessages == OPERATOR_EGT)
                {
                    postWindowMessage (this.enablePostMessages, MESSAGE_ACTION_EXIT);
                }
                
                if (this.lobbyUrlTarget !== "top")
                {
                    parent.location.href = this.lobbyUrl;
                }
                else
                {
                    top.location.href = this.lobbyUrl;
                }

                return;
            }
            
            let homeUrl = "";

            if (this.config.casinoUrls != null)
            {
                for (let i = 0; i < this.config.casinoUrls.length; ++i)
                {
                    if (parseInt(this.config.casinoUrls[i].casinoId) === parseInt(this.casinoid))
                    {
                        if (this.enablePostMessages == OPERATOR_EGT)
                        {
                            postWindowMessage (this.enablePostMessages, MESSAGE_ACTION_EXIT);
                        }

                        homeUrl = this.config.casinoUrls[i].url;
                        break;
                    }
                }
            }
            
            if (homeUrl != "")
            {
                if (this.lobbyUrlTarget !== "top")
                {
                    parent.location.href = homeUrl;
                }
                else
                {
                    top.location.href = homeUrl;
                }
            }

            return;
        }

        this.spinBtn.scene.remove();
        this.autoSelBtn.scene.remove();
        this.stopBtn.scene.remove();
        this.autoStopBtn.scene.remove();
        this.betBtn.scene.remove();
        this.settingsBtn.scene.remove();

        this.homeBtn.button.removeAllListeners();
        this.homeBtn.scene.stop();

        this.collectBtn.scene.remove();
        this.collectCashbackBtn.scene.remove();
        this.turboOnOff.scene.remove();
        this.bonusBtn.scene.remove();

        this.error.scene.remove();
        this.jackpots.scene.remove();
        this.settings.scene.remove();

        this.tw.scene.remove();
        this.crintro.scene.remove();
        this.crplay.scene.remove();
        this.cw.scene.remove();

        this.ll.scene.remove();

        this.selbet.scene.remove();
        this.betlimit.scene.remove();
        this.selauto.scene.remove();

        this.emitter.scene.remove();

        this.sound.stopAll();

        if (screen.orientation && screen.orientation.addEventListener)
        {
            screen.orientation.removeEventListener("change", this.onOrientationChange, false);
        }
        else
        {
            window.removeEventListener("orientationchange", this.onOrientationChange, false);
        }


        this.game.events.removeListener(Phaser.Core.Events.FOCUS, this.onFocus, this);
        
        this.scale.off("leavefullscreen", this.onBlur, this);

        this.keyLayout.off("down", this.onChangeLayout, this);
        this.keySpin.off("down", this.kbdSpin, this);

        this.gameState = GAME_STATE_NOT_INITIALIZED;

        if (this.enablePostMessages == OPERATOR_EGT)
        {
            postWindowMessage (this.enablePostMessages, MESSAGE_ACTION_LOBBY_OPEN);
        }

        this.lobby = this.scene.add("Lobby", SceneLobby, true, {scene: this, gameSocket: this.gameSocket, title: this.getText(GLOBAL_TXT_LOBBY_TITLE)});

        this.gameSocket.onclose = null;
        this.gameSocket.onerror = null;

        this.scene.sleep();
    }

    stop ()
    {
        this.stopBtn.sleep(true);

        this.rm.stopReels();
    }

    balanceChange (ab, abold, br, brold, bb, bbold)
    {
        if (this.gameState == GAME_STATE_READY || this.gameState == GAME_STATE_PLAY_WIN) 
        {
            this.balance = ab;
            this.balanceReal = br;
            this.balanceBonus = bb;

            if (this.balance >= this.gameSocket.getBet())
            {
                this.spinBtn.wake();
                this.spinBtn.enable();
                this.autoSelBtn.enable();
            }
            else if (this.balance < this.gameSocket.getBet() && !this.spinBtn.scene.isSleeping())
            {
                this.spinBtn.disable();
                this.autoSelBtn.disable();

                if (this.error.scene.isVisible())
                {
                    this.error.scene.bringToTop();
                }
            }
        }
        else
        {
            this.balance = ab - (abold - this.balance);
            this.balanceReal = br - (brold - this.balanceReal);
            this.balanceBonus = bb - (bbold - this.balanceBonus);
        }

        this.balanceUpdate(brold - br, bbold - bb);

        if (this.gameSocket.callForBonusBetAllowed())
        {
            this.bonusBtn.wake();
        }
        else
        {
            this.bonusBtn.sleep();
        }

        if (this.gameState != GAME_STATE_NOT_INITIALIZED)
        {
            this.sound.play("credit");
        }
    }

    balanceBonusVisibleUpdate ()
    {
        let v = this.balanceBonus > 0;

        if (v)
        {
            this.txtBonus.setVisible(v);
            this.balanceBonusCounter.setVisible(v);
        }
        else
        {
            if (this.txtBonus.visible)
            {
                this.txtBonus.setVisible(v);
                this.balanceBonusCounter.setVisible(v);
                this.balanceBonusCounter.reset(this.balanceBonus);
            }
        }

        if (this.isLandscapeMode())
        {
            this.bonusL.setVisible(v);
        }
        else
        {
            this.bonusP.setVisible(v);
        }
    }

    balanceUpdate (dr, db)
    {
        this.balanceBonusVisibleUpdate();
        
        if (this.balanceReal == this.balanceRealCounter.value() &&
            this.balanceBonus == this.balanceBonusCounter.value())
        {
            return;
        }

        if (dr == undefined || dr != 0)
        {
            this.balanceRealCounter.reset(this.balanceReal);
            this.balanceRealCounter.setScale(0.95);
        }

        if (db !== undefined && db != 0)
        {
            this.balanceBonusCounter.reset(this.balanceBonus);
            this.balanceBonusCounter.setScale(0.95);
        }
        
        this.time.delayedCall(100, this.balanceRestoreScale, [], this);
    }

    balanceUpdate2 (amount)
    {
        this.collectBtn.sleep(true);

        this.balance += amount;
        this.balanceReal += amount;
        
        this.balanceRealCounter.reset(this.balanceReal);

        this.tweens.add({

            targets: this.balanceRealCounter.bmText,
            ease: 'Linear',
            duration: 1000,
    
            scaleX: 1.1,
            scaleY: 1.1,

            callbackScope: this,
            onComplete: function() 
            {
                this.balanceRealCounter.setScale (1.0);
            },
        });
    }

    balanceRestoreScale ()
    {
        this.balanceRealCounter.setScale(1.0);
        this.balanceBonusCounter.setScale(1.0);
    }

    balanceRestore ()
    {
        this.balance = this.balancePrev;
        this.balanceReal = this.balanceRealPrev;
        this.balanceBonus = this.balanceBonusPrev;

        this.balanceBonusVisibleUpdate();
        
        this.balanceRealCounter.reset(this.balanceReal).setScale(0.95);

        this.balanceBonusCounter.reset(this.balanceBonus).setScale(0.95);
        
        this.time.delayedCall(100, this.balanceRestoreScale, [], this);
    }

    betChange ()
    {
        this.animBet.setText(formatValue(this.gameSocket.getBet(), this.currencyPrecision));
        this.betScale(1.2);
        
        this.time.delayedCall(100, this.betRestoreScale, [], this);
    }

    betRestoreScale ()
    {
        this.betScale(1.0);
    }

    betScale (v = 1)
    {
        let s = 1;

        if (this.animBet.width > ANIM_BET_MAX_SIZE)
        {
            s = ANIM_BET_MAX_SIZE / this.animBet.width;
        }

        this.animBet.setScale(v * s);
    }

    betWithdraw (bet)
    {
        this.balancePrev = this.balance;
        this.balanceRealPrev = this.balanceReal;
        this.balanceBonusPrev = this.balanceBonus;
        
        this.balance -= bet;

        let ab = this.gameSocket.getRealCash();
	    let pmc = this.gameSocket.getPrmCashable();//expected to be 0 server add it to realCash
	    let pmp = this.gameSocket.getPrmPlayable();
	    let pmr = this.gameSocket.getPrmResidual();

       	let m2 = bet;

        let dpmp = Math.min( m2, pmp );
        m2 -= dpmp;

        let dpmc = Math.min( m2, pmc );
        m2 -= dpmc;

        let dab = Math.min( m2, ab );
        m2 -= dab;

        let dpmr = Math.min( m2, pmr );
        m2 -= dpmr;

		ab = ab - dab;
        
        pmc = pmc - dpmc;

        pmp = pmp - dpmp;
        
        pmr = pmr - dpmr;

        this.balanceReal = ab + pmc;
        this.balanceBonus = pmp + pmr;

        this.balanceUpdate(dab + dpmc, dpmp + dpmr);
    }

    collectCashbackWait ()
    {
        this.autoStopBtn.scene.sleep();
        this.autoSpinEnabled = false;
        
        this.collectCashbackBtn.wake();
        
        this.timerEvent = this.time.delayedCall(CASHBACK_COLLECT_WAIT_TIME, this.collectCashback, [], this);
    }

    collectCashback ()
    {
        this.time.removeEvent(this.timerEvent);

        this.collectCashbackBtn.sleep();
        this.cw.collectCashback();
    }

    collectCashbackComplete ()
    {
        if (this.getTotalWin() > 0)
        {
            this.gameState = GAME_STATE_PLAY_WIN;
        }
        else
        {
            this.gameState = GAME_STATE_READY;
        }            
                
        if (this.errorPending)
        {
            this.showError();
            return;
        }

        this.buttonsWake();

        if (this.gameSocket.getBalance() >= this.gameSocket.getBet())
        {
            this.spinBtn.enable();
            this.autoSelBtn.enable();
        }
        else
        {
            this.spinBtn.disable();
            this.autoSelBtn.disable();

            if (this.error.scene.isVisible())
            {
                this.error.scene.bringToTop();
            }
        }
                
        if (this.gameSocket.getBalance() >= this.gameSocket.getBet())
        {
            this.spinBtn.wake();
            this.turboOnOff.wake(); 
        }

        if (this.gameState == GAME_STATE_PLAY_WIN)
        {
            this.rm.showWins();
        }
    }

    onSocketOpen ()
    {
        this.gameSocket.sendCmdChallenge();
    }
    
    start (startScene)
    {
        this.startScene = startScene;

        this.error.onOrientationChange();
        
        if (this.gameSocket != null)
        {
            this.gameSocket.connect();
        }
        else
        {
            this.errorMessage = this.getText(GLOBAL_TXT_INVALID_STARTING_PARAMETERS);

            this.onError (this.errorMessage, "", "", ERR_CONNECTION_ERROR_ON_START);
        }
    }

    onGameSessionReady ()
    {
        this.gameSessionReady = true;

        this.jackpots.enableJackpots(this.gameSocket.isJackpotEnable());

        if (this.startScene.scene.isVisible())//notify start scene that connection with game server is established
        {
            this.settings = this.scene.add("SceneSettings", SceneSettings, true, { scene: this, buyBonusEnable: this.gameSocket.canBuyBonus(), jackpotEnable: this.gameSocket.isJackpotEnable(), lang: this.lang, onLeftHandMode: this.onLeftHandMode.bind(this), onSwipeToSpin: this.onSwipeToSpin.bind(this), onBack: this.settingsClose.bind(this)});
            
            this.startScene.waitScenesToLoad();
        }
        else if (this.errorCode == ERR_CONNECTION_CLOSED || this.errorCode == ERR_CONNECTION_ERROR)
        {
            this.errorCode = 0;
            this.errorPending = false;
            this.criticalError = false;

            this.error.clearMessage();

            this.connectBtn.sleep();

            this.reconnectComplete();
        }
    }

    startSceneComplete ()
    {
        this.game.events.addListener(Phaser.Core.Events.FOCUS, this.onFocus, this);

        this.scale.on("leavefullscreen", this.onBlur, this);

        this.timer = this.time.addEvent({
            delay: 20000,
            callback: this.setTime,
            callbackScope: this,
            loop: true
        });

        this.lockWakeState();

        this.txtInfo.setText(this.getText(GLOBAL_TXT_COMPANY_NAME));
        this.txtGame.setText(this.getText(LOCAL_TXT_GAMENAME));
        this.txtBalance.setText(this.getText(GLOBAL_TXT_BALANCE) + " (" + this.gameSocket.getCurrency() + ")");
        this.txtBonus.setText(this.getText(GLOBAL_TXT_BONUS));
        this.txtBet.setText(this.getText(GLOBAL_TXT_BET) + " (" + this.gameSocket.getCurrency() + ")");

        this.txtTime.setVisible(true);
        
        setTime(this.txtTime);

        this.currencyPrecision = this.gameSocket.getCurrencyPrecision();
        
        this.balanceRealCounter.setPrecision(this.currencyPrecision);
        this.balanceBonusCounter.setPrecision(this.currencyPrecision);

        this.animBet.setText(formatValue(this.gameSocket.getBet(), this.currencyPrecision));
        this.betScale(1.0);

        this.selbet.setBets(this.gameSocket.getBets());

        this.settings.setPayInfo(this.gameSocket.getPaytable(),
                                 this.gameSocket.getUnits(),
                                 this.gameSocket.getBetPerLine(),
                                 this.gameSocket.getNumberOfLines(),
                                 this.gameSocket.getMinBet(),
                                 this.gameSocket.getMaxBet(),
                                 this.currencyPrecision)

        this.jackpots.setPrecision(this.currencyPrecision);
        this.jackpots.betChange(this.gameSocket.getBetSel());

        this.tw.setPrecision(this.currencyPrecision);
        this.ll.setPrecision(this.currencyPrecision);
        this.cw.setPrecision(this.currencyPrecision);
        this.crplay.setPrecision(this.currencyPrecision);
        this.crplay.setJackpotLegalLimit(this.gameSocket.getJackpotLegalLimit());

        if (this.gameSocket.canBuyBonus())
        {
            this.bonusBtn.setCanWake(true);
        }

        let rmconf = 
        {
            scene: this,
            lines: this.gameSocket.getLines(),
            reels: this.gameSocket.getReels()
        }

        if (!this.errorPending)
        {
            this.rm = new ReelManager(rmconf);
//          this.rm.setVisible(false);
        }

        if (this.isLandscapeMode())
        {
            this.setLandscapeLayout();
        }
        else
        {
            this.setPortraitLayout();
        }

        this.scene.wake();
        this.scene.bringToTop();

        this.startScene.scene.stop();

        this.showReelsComplete();
    }

    reconnectComplete ()
    {
        this.animBet.setText(formatValue(this.gameSocket.getBet(), this.currencyPrecision));
        this.betScale(1.0);

        this.selbet.setBets(this.gameSocket.getBets());

        this.settings.updatePayInfo(this.gameSocket.getBetPerLine());

        this.autoSelBtn.enable();

        if (this.isLandscapeMode())
        {
            this.setLandscapeLayout();
        }
        else
        {
            this.setPortraitLayout();
        }
        
        this.rm.setVisible(true);

        this.showReelsComplete ();
    }

    showReelsComplete ()
    {
        if (this.criticalError)
        {
            this.error.scene.bringToTop();
            return;
        }

        this.gameState = GAME_STATE_READY;

        this.buttonsWake();

        if (this.balance >= this.gameSocket.getBet())
        {
            this.spinBtn.enable();
        }
        else
        {
            this.spinBtn.disable();
            this.autoSelBtn.disable();
        }
        
        this.jackpots.wake();
    }

    onSpinReceived ()
    {
        let receivedTime = new Date();

        this.responseTime = receivedTime.getTime() - this.sentPacketTime.getTime();

        if (this.responseTime < DEFAULT_MAX_SERVER_RESPONSE_TIME + this.gameSocket.getExtraStartSpinTime())
        {
            this.responseTime = REEL_SPIN_DURATION + this.gameSocket.getExtraStartSpinTime() - this.responseTime;
        }
        else
        {
            this.responseTime = 100;
        }

        this.jackpotPollTimer = JACKPOT_POLL_TIME;

        this.gameState = GAME_STATE_SPIN;
        
        this.sessionExpireTimer = SESSION_TIMEOUT;

        this.currentGame = this.gameSocket.getGame();

        this.balance = this.gameSocket.getBalanceBeforeWin();

        this.balanceReal = this.gameSocket.getBalanceRealBeforeWin();

        this.balanceBonus = this.gameSocket.getBalanceBonus();

        this.balanceUpdate();

        this.autoWin += this.getTotalWin();

        this.settings.addSpin(this.currentGame);

        if (this.gameSocket.getJackpotWin())
        {
            this.crplay.updateData();
        }

        this.txtInfo.setText("ID: " + this.currentGame.combinationId);

        if (!this.ll.scene.isSleeping())
        {
            this.ll.sleep();
        }

        this.rm.playGame(this.currentGame.spinResult);

        if (!this.autoSpinEnabled)
        {
            if (this.isFastSpin())
            {
                this.onFastStop();
            }
            else
            {
                this.ll.reset();

                if (!this.spinHoldActive)
                {
                    this.stopBtn.wake();
                }
            }
        }
        else
        {
            if (this.autoSpinLimit > 0)
            {
                if (--this.autoSpinLimit == 0)
                {
                    this.autoSpinEnabled = false;
                    
                    this.autoStopBtn.sleep();
                    this.stopBtn.wake();
                }
                else
                {
                    this.autoStopBtn.setValue(this.autoSpinLimit);
                }                    
            }
    
            this.ll.reset();
        }
    }

    getTotalWin ()
    {
        return this.gameSocket.getTotalWin();
    }

    getBetPerLine ()
    {
        return this.gameSocket.getBetPerLine();
    }

    reelStopped ()
    {
        if (this.tw.resetPending)
        {
            if (this.tw.scene.isActive())
            {
                this.tw.forceClose(true);
            }

            this.tw.reset();
        }
    }

    onFastStop ()
    {
        if (this.tw.scene.isActive())
        {
            this.tw.forceClose(true);
        }
        
        this.tw.reset();
    }

    isFastSpin()
    {
        if (this.spinFastMode)
        {
            return true;
        }
        else if (this.spinHoldActive && this.turboOnOff.canWake)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    onReelsReady ()
    {
        if (this.gameSocket.getJackpotWin() > 0 || this.gameSocket.getCashbackWin() > 0)
        {
            this.autoSpinEnabled = false;

            this.autoStopBtn.sleep();

            if (this.spinHoldActive)
            {
                this.spinBtn.clearHold();
            }
        }

        if (this.gameSocket.getJackpotWin() > 0)
        {
            this.gameState = GAME_STATE_JACKPOT_WIN;
            
            this.crintro.wake();

            return;
        }
        else if (this.gameSocket.getCashbackWin() > 0)
        {
            this.gameState = GAME_STATE_CASHBACK_WIN;

            this.cw.start();

            return;
        }
        
        this.gameState = GAME_STATE_READY;

        if (this.errorPending)
        {
            this.showError();
            return;
        }
        
        if (this.autoSpinEnabled)
        {
            this.time.delayedCall(150, this.startAutoSpin, [], this);
            return;
        }

        if (this.spinHoldActive)
        {
            this.spin();
            return;
        }

        this.buttonsWake();

        if (this.gameSocket.getBalance() >= this.gameSocket.getBet())
        {
            this.spinBtn.enable();
            this.autoSelBtn.enable();
        }
        else
        {
            this.spinBtn.disable();
            this.autoSelBtn.disable();

            if (this.error.scene.isVisible())
            {
                this.error.scene.bringToTop();
            }
        }
    }

    onTotalWin ()
    {
        if (this.gameSocket.getJackpotWin() > 0 || this.gameSocket.getCashbackWin() > 0)
        {
            this.autoSpinEnabled = false;

            this.autoStopBtn.sleep();
        }

        if (this.gameSocket.getJackpotWin() > 0)
        {
            this.gameState = GAME_STATE_JACKPOT_WIN;
            
            if (this.spinHoldActive)
            {
                this.spinBtn.clearHold();
                this.spinBtn.sleep();
            }
            
            this.crintro.wake();

            return;
        }

        this.gameState = GAME_STATE_TOTAL_WIN;

        if (this.gameSocket.getCashbackWin() == 0 && this.gameSocket.getBalance() >= this.gameSocket.getBet() && !this.autoSpinEnabled && !this.spinHoldActive)
        {
            this.spinBtn.wake();
            this.turboOnOff.wake(); 
        }

        if (!this.spinHoldActive && !this.autoSpinEnabled && this.gameSocket.getCashbackWin() == 0)
        {
            this.collectBtn.wake();
        }

        this.tw.wake();
        this.tw.setDisplayWinCombinations(true);

        this.rm.playTotalWin();
    }

    showWins ()
    {
        if (this.gameSocket.getCashbackWin() > 0)
        {
            this.gameState = GAME_STATE_CASHBACK_WIN;

            if (this.spinHoldActive)
            {
                this.spinBtn.clearHold();
            }
            
            this.cw.start();

            return;
        }

        this.gameState = GAME_STATE_PLAY_WIN;

        if (this.errorPending)
        {
            this.showError();
            return;
        }

        if (this.autoSpinEnabled)
        {
            this.gameState = GAME_STATE_READY;
            
            this.time.delayedCall(150, this.startAutoSpin, [], this);
            
            return;
        }
        
        if (this.spinHoldActive)
        {
            this.spin();
            return;
        }

        this.buttonsWake();

        if (this.gameSocket.getBalance() >= this.gameSocket.getBet())
        {
            this.spinBtn.enable();
            this.autoSelBtn.enable();
        }
        else
        {
            this.spinBtn.disable();
            this.autoSelBtn.disable();

            if (this.error.scene.isVisible())
            {
                this.error.scene.bringToTop();
            }
        }

        this.collectBtn.sleep(true);

        if (this.gameSocket.getBalance() >= this.gameSocket.getBet() && !this.autoSpinEnabled)
        {
            this.spinBtn.wake();
        }
        
        if (this.currentGame.legalLimitApplied && this.ll.scene.isSleeping())
        {
            this.ll.show(this.getTotalWin());
        }

        this.rm.showWins();
    }
    
    onError (message, walletMessage, extraMessage, errorCode, walletFailureCode = -1, walletAPIFailureCode = -1)
    {
        if (this.errorPending)
        {
            return;
        }

        this.errorCode = errorCode;
        this.walletFailureCode = walletFailureCode;
        this.walletAPIFailureCode = walletAPIFailureCode;
        this.errorMessage = message;
        this.errorExtraMessage = extraMessage;
        this.errorWalletMessage = walletMessage;

        if (this.gameState == GAME_STATE_NOT_INITIALIZED ||
            this.gameState == GAME_STATE_SPIN ||
            this.gameState == GAME_STATE_JACKPOT_WIN ||
            this.gameState == GAME_STATE_TOTAL_WIN ||
            this.gameState == GAME_STATE_CASHBACK_WIN)
        {
            this.errorPending = true;

            if (this.gameState == GAME_STATE_NOT_INITIALIZED)
            {
                this.startScene.waitScenesToLoad();
            }

            return;
        }
        else
        {
            this.showError();
        }
    }

    showError ()
    {
        this.gameState = GAME_STATE_ERROR;
        
        if (this.rm != undefined)
        {
            if (this.rm.getState() == RM_STATE_SPIN)
            {
                this.rm.errStopReels();
            }

            this.rm.state = RM_STATE_READY;
        }

        if (this.walletAPIFailureCode == 6 && this.walletFailureCode == 11)
        {
            if (this.spinHoldActive)
            {
                this.spinHoldActive = false;
                this.spinBtn.sleep();
                this.spinBtn.clearStates();
            }

            this.betlimit.wake();
            
            this.errorPending = false;

            return;
        }

        this.errorPending = true;//do not show next errors if any
        this.criticalError = true;

        if (this.startScene.scene.isVisible())
        {
            this.errorCode = ERR_CONNECTION_ERROR_ON_START;
        }

        this.startScene.clear();
        
        this.gameState = GAME_STATE_ERROR;

        this.txtWin.setVisible(false);

        if (this.settings != undefined && this.scene.getStatus(this.settings.scene.key) >= Phaser.Scenes.RUNNING && this.settings.scene.isVisible())
        {
            this.settingsClose();
        }

        if (this.selbet.scene.isVisible())
        {
            this.betSelClose();
        }

        if (this.selauto.scene.isVisible())
        {
            this.autoSelClose();
        }

        if (this.selbonus.scene.isVisible())
        {
            this.bonusSelClose();
        }

        this.error.setMessage(this.errorMessage, this.errorWalletMessage, this.errorExtraMessage);

        this.spinBtn.sleep();
        this.autoSelBtn.sleep();
        this.stopBtn.sleep(true);
        this.autoStopBtn.sleep();
        this.betBtn.sleep();
        this.settingsBtn.sleep();
        this.collectBtn.sleep(true);
        this.collectCashbackBtn.sleep();
        this.homeBtn.sleep();
        this.turboOnOff.sleep();
        this.bonusBtn.sleep();
        
        this.tw.sleep();

        this.emitter.sleep();
        
        this.autoSpinEnabled = false;

        if (this.errorCode == ERR_CONNECTION_CLOSED || this.errorCode == ERR_CONNECTION_ERROR)
        {
            this.connectBtn.enable();
            this.connectBtn.wake();

            this.balance = 0;
            this.balanceReal = 0;
            this.balanceBonus = 0;

            this.balanceRealCounter.reset(this.balanceReal);

            this.balanceBonusVisibleUpdate();

            return;
        }

        this.sound.stopAll();

        this.game.events.removeListener(Phaser.Core.Events.FOCUS, this.onFocus, this);
        this.scale.on("leavefullscreen", this.onBlur, this);

        this.keyLayout.off("down", this.onChangeLayout, this);
        this.keySpin.off("down", this.kbdSpin, this);
    }

    buttonsWake (index)
    {
        this.spinBtn.wake();
        this.homeBtn.wake();
        this.betBtn.wake();
        this.settingsBtn.wake();
        this.autoSelBtn.wake();
        this.turboOnOff.wake();

        if (index == undefined)
        {
            if (this.gameSocket.callForBonusBetAllowed())
            {
                this.bonusBtn.wake();
            }
            else
            {
                this.bonusBtn.sleep();
            }
        }
        else
        {
            if (this.gameSocket.callForBonusBetAllowed(index))
            {
                this.bonusBtn.wake();
            }
            else
            {
                this.bonusBtn.sleep();
            }
        }
    }

    buttonsEnable ()
    {
        this.spinBtn.enable();
        this.homeBtn.enable();
        this.betBtn.enable();
        this.settingsBtn.enable();
        this.autoSelBtn.enable();
        this.turboOnOff.enable();
    }

    buttonsDisable ()
    {
        this.spinBtn.disable();
        this.homeBtn.disable();
        this.betBtn.disable();
        this.settingsBtn.disable();
        this.autoSelBtn.disable();
        this.turboOnOff.disable();
    }

    getText (textId)
    {
        let text = this.globalTexts.get(textId);

        if (text !== undefined) return text;

        text = this.localTexts.get(textId);

        if (text !== undefined) 
        {
            return text;
        }
        else 
        {
            return "";
        }
    }

    setTime ()
    {
        setTime(this.txtTime);
    }
}
