(function () {
    if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(searchString, position){
        position = position || 0;
        return this.substr(position, searchString.length) === searchString;
    };
}
/*
function getUrlQuery(queryString) {
    let param = queryString.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"),
            regexS = "[\\?&]" + param + "=([^&#]*)",
            regex = new RegExp(regexS),
            results = regex.exec(window.location.href);
    if (results == null) {
        return false;
    } else {
        return results[1];
    }
}
*/
function getUrlQuery(key) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");

	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] === key) {
			try {
				return decodeURIComponent( pair[1] );
			} catch( e ) {
				return pair[1];
			}
		}
	}

	return false;
};
var inIframe = function() {
    try {
            return window.self !== window.top;
    } catch (e) {
            return true;
    }
};

var GameFunctions = {}
GameFunctions.gameLoaded = function() {

}
GameFunctions.gameClose = function() {
    if (getUrlQuery('isGameBridge') === 'true') {
            window.parent.postMessage({ message: "close", param: null}, "*");
            window.top.postMessage({ wpgaction: "close" }, '*');
            window.parent.postMessage({ wpgaction: "close.parent" }, '*');
    } else if (getUrlQuery('lobbyUrl') !== false && getUrlQuery('lobbyUrl') != 'LOBBY_URL' && getUrlQuery('lobbyUrl') != 'DUMMY' && getUrlQuery('lobbyUrl') != 'OFF' && getUrlQuery('lobbyUrl') != 'WCLOSE') {
	if (getUrlQuery('lobbyUrlTarget')==='TOP') {
		window.top.location = getUrlQuery('lobbyUrl');
	} else {
        	window.location = getUrlQuery('lobbyUrl');
	}
    } else if (getUrlQuery('lobbyUrl') !== false && getUrlQuery('lobbyUrl') == 'WCLOSE') {
        window.close();
    } else if (inIframe()) {
        window.parent.postMessage({ message: "close", param: null}, "*");
        window.top.postMessage({ wpgaction: "close" }, '*');
        window.parent.postMessage({ wpgaction: "close.parent" }, '*');
    } else {
        window.history.back();
    }
}


GameFunctions.eventLoadStart = function() {
	window.top.postMessage({ wpgaction: "loadStart" }, '*');
	window.parent.postMessage({ wpgaction: "loadStart.parent" }, '*')
};
GameFunctions.eventLoadEnd = function() {
    window.top.postMessage({ wpgaction: "loadEnd", /*param: { gameTitle: gametitle} */ }, '*');
    window.parent.postMessage({ wpgaction: "loadEnd.parent", /*param: { gameTitle: gametitle} */ }, '*');
};
GameFunctions.eventGameSpinStart = function() {
    window.top.postMessage({ wpgaction: "gameSpinStart" }, '*');
    window.parent.postMessage({ wpgaction: "gameSpinStart.parent" }, '*');
};
GameFunctions.eventGameSpinEnd = function() {
    window.top.postMessage({ wpgaction: "gameSpinEnd" }, '*');
    window.parent.postMessage({ wpgaction: "gameSpinEnd.parent" }, '*');
};

GameFunctions.eventGameCashier = function() {
	window.parent.postMessage({ message: "cashier", param: null}, "*");
	window.top.postMessage({ wpgaction: "cashier" }, '*');
	window.parent.postMessage({ wpgaction: "cashier.parent" }, '*');
}
GameFunctions.eventHistory = function() {
    if (getUrlQuery('historyUrl') !== undefined && getUrlQuery('historyUrl')!==false) {
        if (getUrlQuery('historyUrl') == "EVENT" || getUrlQuery('historyUrl') == "GAMEBRIDGE") {
            window.top.postMessage({ wpgaction: "openGameHistory" }, '*');
            window.parent.postMessage({ wpgaction: "openGameHistory.parent" }, '*');
        } else {
            window.open(getUrlQuery('historyUrl'), "gamehistory", "scrollbars=1,height=600,width=760");
        }
    }
}

GameFunctions.eventErrorOutOfMoney = function() {
    window.top.postMessage({ wpgaction: "errorOutOfMoney" }, '*');
    window.parent.postMessage({ wpgaction: "errorOutOfMoney.parent" }, '*');
}



    var loadScripts = function (scripts, index, callback) {
        if (index < scripts.length) {
            var el = document.createElement('script');
            el.async = scripts[index].async;
            el.src = scripts[index].src;
            document.body.appendChild(el);
            el.addEventListener('load', function () {
                loadScripts(scripts, index + 1, callback);
            }, false);
            el.addEventListener('error', function () {
                loadScripts(scripts, index + 1, callback);
            }, false)
        } else if (callback) {
            callback();
        }
    }

    // these parematers are read from URL (GET)
    var gameCode = getUrlQuery('gameCode');
    var token = getUrlQuery('token');
    var username = getUrlQuery('username');
    var languageCode = getUrlQuery('languageCode');
    var playMode = (getUrlQuery('playMode') === 'REAL' ? 1 : 2);

    // some hardcoded values, generated at time of badge generation.
    var provider = 'oryx';
    var gameVersion = '2021-P06.02';
    var environment = 'prod';
    var mediaUrl = "https://cdn.oryxgaming.com/games/PSO/{CLIENT_VERSION}/{GAME_BY_CODE}/";

    var assetGameCode = gameCode;
    if( assetGameCode.substr(-3) === "_91" || assetGameCode.substr(-3) === "_96" ) {
	assetGameCode = assetGameCode.substr( 0, assetGameCode.length-3 );
    }
    var gameBaseURL = mediaUrl.replace(/{GAME_BY_CODE}/, assetGameCode).replace(/{CLIENT_VERSION}/, gameVersion);
    var arrs = [
                'wss://clients-prodcopy.oryxgaming.com/ws'
            ];
    var wloc = window.location;
    for(var s=0; s<arrs.length; s++) {
        if (arrs[s].startsWith("_SAMEHOST_")) {
            var newUrl = wloc.host.split('.');
            newUrl[0] = 'client';
            newUrl = newUrl.join('.');
            arrs[s] = arrs[s].replace("_SAMEHOST_", newUrl);
            arrs[s] = 'wss://' + arrs[s];
        }
    }
    
    // prepare object with game parameters
    var launchParams = {
        gameVersion: gameVersion,
        gameBaseURL: gameBaseURL,
        provider: provider,
        environment: environment,
        servers: arrs,
        gameCode: gameCode,
        token: token,
        languageCode: languageCode,
        username: username,
        playMode: playMode,
        cageCode: 'OD1',
	history: true,
        /*
         * Min spin duration in millis.
         */
        minSpinDuration: 0,
        /*
         * Slow connection threshold in millis.
         */
        slowConnection: 0,
        /*
         * Inactivity timeout threshold in seconds.
         */
        inactivityTimeout: 1200,
        /*
         * Supported values: 'DESKTOP','MOBILE' and 'NATIVE'.
         */
        clientType: 'MOBILE',
        /*
         * Unfinished game rounds resolution method (supported values: 'NONE', 'MANUAL', 'AUTO')
         */
        unfinishedResolutionType: 'NONE',
        /*
         * Unfinished game rounds period in days.
         */
        unfinishedCancellationDays: 90,
        /*
         * Elapsed player session in millis for jurisdictions like SGA.
         */
        sessionTime: 10000,
        /*
         * Show advanced autoplay flag.
         */
        advancedAutoplay: false,
        /*
         * Show clock flag.
         */
        clock: true,
	closeButton: (true && (getUrlQuery('lobbyUrl') === "OFF" ? false : true)),
        /*
         * Show fan bunner flag.
         */
        funBanner: true,
         /*
          * Disable autoplay.
          */
         disableAutoplay: false,
         /*
          * Show RTP and max win.
          */
         showRtpAndMaxWin: false,
        /*
         * Url for redirections after a game closure.
         */
        //lobbyUrl: 'https://clients.peterandsons.org/lobby/index.html',
        /*
         * Currency overrides
         */
        currencyOverrides: {
            PTS: {
                /*
                 * Controls whether the subunit (decimal) part is shown when
                 * the value is exact, e.g. exactly $8 and 0¢
                 */
                showDecimalIfWhole: true,
                /*
                 * Subunits per unit.
                 */
                subunitsPerUnit: 100,
                /*
                 * Effective locale means the exact locale that will be used
                 * when formatting numbers. It doesn't necessarily match the
                 * locale passed to `formattingForLocale()` call because
                 * of the fallback logic.
                 */
                effectiveLocale: 'es',
                /*
                 * Currency code is not used directly and is provided here
                 * for reference or custom logic for the clients of the lib.
                 */
                currencyCode: 'PTS',
                /*
                 * Symbol passed in to `currencyFormatter` function.
                 */
                currencySymbol: 'Pesetas',
                /*
                 * Separator used to format thousands.
                 */
                thousandSeparator: ',',
                /*
                 * Separator between whole and decimal part of the amount.
                 */
                decimalSeparator: '.',
                /*
                 * Function that correctly positions symbol, formattedAmount
                 * and a minus relative to each other.
                 */
                currencyFormatter: function (symbol, formattedAmount, minus) {
                    return minus + formattedAmount + symbol;
                }
            }
        }
    };

    var splash = document.getElementById('splash');
    var logoContainer = document.createElement("div");
    logoContainer.id = "logo-container";

    var img = new Image();
    img.addEventListener('load', function () {
        logoContainer.appendChild(img);
        splash.style.display = 'flex';
        splash.appendChild(logoContainer);
        img.style.display = 'block';
    });
    img.id = "frame0";
    img.src = launchParams.gameBaseURL + 'splash.svg';

    var scripts = [
        {src: gameBaseURL + 'engine-wrapper/' + provider + '/engine.js', async: false},
        {src: gameBaseURL + 'engine-wrapper/' + provider + '/engine-extensions.js', async: false},
        {src: gameBaseURL + 'src/settings.js', async: false},
        {src: gameBaseURL + 'launcher.js', async: false},
        {src: gameBaseURL + 'cocos2d-js-min.js', async: true},
    ];

    var engineLoaded = function () {
        window.PSGames.boot(launchParams, 'game');
        window.PSGames.events = window.PSGames.events || {};
        // Handle game events.
        window.PSGames.events.registerHandler(function (op, data) {
            console.log("Event:", op);
            switch (op) {
                case 'loadStart':
                    GameFunctions.eventLoadStart();
                    break;
                case 'loadEnd':
                    GameFunctions.eventLoadEnd();
                    break;
                case 'balance':
                    // TODO will be handled by Oryx.
                    break;
                case 'gameSpinStart':
                    GameFunctions.eventGameSpinStart();
                    break;
                case 'gameSpinEnd':
                    GameFunctions.eventGameSpinEnd();
                    break;
                case 'history':
                    GameFunctions.eventHistory();
                    break;
                case 'help':
                    // TODO will be handled by Oryx.
                    break;
                case 'close':
                    GameFunctions.gameClose();
                    break;
                case 'errorOutOfMoney':
                    GameFunctions.eventErrorOutOfMoney();
                    break;
                default:
                // TODO will be handled by Oryx.
            }
        });

        window.addEventListener('message', function (event) {
            try {
                if (!window.PSGames.events.externalHandler || event === undefined || event.data === undefined || event.data.wpgaction === undefined) {
                    return;
                }

                switch (event.data.wpgaction) {
                    case 'doGameSuspend':
                        /*
                         * Stops autoplay.
                         */
                        window.PSGames.events.externalHandler('doGameSuspend');
                        break;
                    case 'doGamePause':
                        /*
                         * Puts the game in pause (player can not trigger any action).
                         */
                        window.PSGames.events.externalHandler('doGamePause');
                        break;
                    case 'doGameResume':
                        /*
                         * Resumes the game.
                         */
                        window.PSGames.events.externalHandler('doGameResume');
                        break;
                }
            } catch (e) {
                console.error(e);
            }
        });
    };

    loadScripts(scripts, 0, engineLoaded);

})();
