<!-- This Source Code Form is subject to the terms of the Mozilla Public
   - License, v. 2.0. If a copy of the MPL was not distributed with this
   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<iframe id="appframe" src="" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0px;"></iframe>
<iframe id="loadframe" src="views/appspinner.html" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0px; z-index: 999999;"></iframe>

<script src="js/material-palette.js"></script>
<script>
    var historyctr = -1;
    /**
     * Open an app with native Android UI elements
     * @param String id Application ID
     * @param String api Path to the mobile API
     * @param String url Base URL of the app
     * @param String icon URL to the app icon
     * @param String title Friendly app name
     * @param boolean injectcode (optional, default true) Whether or not to inject UI modification code into the app
     * @param boolean shownavbar (optional, default false) Whether or not to show the navbar at the top of the screen.
     * @returns {undefined}
     */
    function launchapp(id, api, url, icon, title, injectcode, shownavbar) {
        if (typeof shownavbar === 'undefined' || shownavbar === false) {
            setnavbar(false);
        } else {
            setnavbar("app", title);
            $('#appframe').css('top', '75px');
        }
        $.post(url + api, {
            username: localStorage.getItem("username"),
            key: localStorage.getItem("key"),
            password: localStorage.getItem("password"),
            action: "start_session"
        }, function (data) {
            if (data.status === 'OK') {
                document.getElementById("loadframe").contentWindow.postMessage("loginok", "*");
                if (typeof injectcode === 'undefined' || injectcode === true) {
                    $('#appframe').on("load", function () {
                        $("#loadframe").fadeOut(300);
                        historyctr++;
                        // Do this right away so it's a bit harder to glitch
                        $('#appframe').contents().find('.navbar-right').html("<li><a onclick='quitapp()'><i class='fa fa-sign-out fa-fw'></i> Back to Menu</a></li>");
                        // Moved BS4 code to sidemenu.js
                        $.get("css/sidemenu.css", function (style) {
                            $('#appframe').contents().find('head').append("<style>" + style + "</style>");
                            $.get("js/polyfills.js", function (script) {
                                $('#appframe').contents().find('body').append("<script>" + script + "<\/script>");
                                $.get("js/jquery-ui.min.js", function (script) {
                                    $('#appframe').contents().find('body').append("<script>" + script + "<\/script>");
                                    $.get("js/hammer.min.js", function (script) {
                                        $('#appframe').contents().find('body').append("<script>" + script + "<\/script>");
                                        $.get("js/sidemenu.js", function (script) {
                                            script = script.replace("__JQUERYFXOFF__", !(localStorage.getItem("animations") === null || localStorage.getItem("animations") === "true"));
                                            script = script.replace("__USERNAME__", userinfo.realname);
                                            script = script.replace("__LOGO__", icon);
                                            $('#appframe').contents().find('body').append("<script>" + script + "<\/script>");
                                        });
                                    });
                                });
                            });
                        });
                    });
                } else {
                    // Only inject minimal CSS
                    $('#appframe').on("load", function () {
                        $.get("css/inject_mini.css", function (style) {
                            $('#appframe').contents().find('head').append("<style>" + style + "</style>");
                        });
                    });
                }
                $('#appframe').attr('src', url);
            } else {
                navigator.notification.alert(data.msg, null, "Error", 'Dismiss');
                openscreen("home");
            }
        }, "json").fail(function () {
            navigator.notification.alert("Could not connect to the server.  Try again later.", null, "Error", 'Dismiss');
            openscreen("home");
        });
    }

    var scanningactive = false;
    var dedup = [];
    window.addEventListener('message', function (event) {
        console.log("app event: " + event.data);
        setTimeout(function () {
            dedup = [];
        }, 500);
        if (dedup.includes(event.data)) {
            return;
        }
        dedup.push(event.data);
        if (event.data == "quit") {
            openscreen("home");
        } else if (event.data == "goneback") {
            historyctr -= 1;
        } else if (event.data.startsWith("load_bs_version ")) {
            var bootstrap_version = event.data.split(" ")[1];
            var nav_breakpoint = event.data.split(" ")[2];
            var bs_file = "bs3";
            if (bootstrap_version.startsWith("4")) {
                bs_file = "bs4";
            }
            $.get("css/sidemenu-" + bs_file + ".css", function (style) {
                if (bs_file == "bs4") {
                    var break_px = "767";
                    switch (nav_breakpoint) {
                        case "sm":
                            break_px = "575";
                            break;
                        case "md":
                            break_px = "767";
                            break;
                        case "lg":
                            break_px = "991";
                            break;
                        case "xl":
                            break_px = "1199";
                            break;
                    }
                    style = style.replace("max-width: 767px", "max-width: " + break_px + "px");
                }
                $('#appframe').contents().find('head').append("<style>" + style + "</style>");
            });
        } else if (event.data.startsWith("setcolor ")) {
            var color = event.data.split(" ", 2)[1];
            if (cordova.platformId == 'android') {
                window.plugins.headerColor.tint(color);
                for (var swatch in _PALETTE) {
                    if (color == _PALETTE[swatch]["shade_500"]) {
                        StatusBar.backgroundColorByHexString(_PALETTE[swatch]["shade_700"]);
                        return;
                    }
                }
                StatusBar.backgroundColorByHexString(shadeColor2(color, -0.1));
            } else {
                StatusBar.backgroundColorByHexString(color);
            }
        } else if (event.data.startsWith("scancode ")) {
            var callbackcode = event.data.split(" ").slice(1).join(" ");
            console.log("got scancode " + callbackcode);
            try {
                if (scanningactive) {
                    console.log("Scanner already active, ignoring request.");
                    return;
                }
                scanningactive = true;
                cordova.plugins.barcodeScanner.scan(
                        function (result) {
                            scanningactive = false;
                            if (!result.cancelled) {
                                var iframe = document.getElementById("appframe");
                                iframe.contentWindow.postMessage("coderesult~|~" + callbackcode + "~|~" + result.text, "*");
                            }
                        },
                        function (error) {
                            scanningactive = false;
                            navigator.notification.alert("Scanning failed: " + error, null, "Error", 'Dismiss');
                        },
                        {
                            "showFlipCameraButton": true,
                            "prompt": "Scan Code"
                        }
                );
            } catch (ex) {
                scanningactive = false;
                navigator.notification.alert(ex.message, null, "Error", 'Dismiss');
            }
        }
    }, false);

    if (userinfo == null) {
        getuserinfo();
    }
</script>