<!-- 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/. -->
<br />
<div class="panel panel-blue">
    <div class="panel-heading">
        <h3 class="panel-title" id="setuptitle">Add Account</h3>
    </div>
    <div class="panel-body">
        <p>
            <span class="firstrun-only" style="display: none;">
                Welcome! There's a few things we need to do to get everything ready.
                <br /><br />
            </span>
            Open AccountHub on another device and go to Sync settings.  Generate a mobile sync code, then press the button below to scan it.
        </p>
        <span class="btn btn-primary" onclick="scanCode()" id="scancodebtn">
            <i class="fa fa-qrcode"></i> Scan Code
        </span>
        <span class="btn btn-link" onclick="manualshow()" id="manualsetupbtn">
            Manual Setup
        </span>
        <div id="manual_setup" class="well" style="display: none;">
            <input type="text" id="username" class="form-control" placeholder="Username" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" /> <br />
            <input type="text" id="key" class="form-control" placeholder="Sync key" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" /> <br />
            <div class="input-group" style="margin-left: -20px;">
                <span class="input-group-addon" id="protocol-select">https://</span>
                <input type="text" id="syncurl" class="form-control" placeholder="URL" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />
            </div> <br />
            <div class="checkbox">
                <label>
                    <input type="checkbox" id="use-security" checked > Use secure connection
                </label>
            </div>
            <br />
            <div class="btn btn-primary" onclick="manualsetup()">
                Continue
            </div>
        </div>
    </div>
</div>

<script>
    setupusername = "";
    setuppassword = "";
    setupsynckey = "";
    setupsyncurl = "";

    if (localStorage.getItem("firstrun") === null) {
        $("#setuptitle").text("Setup");
        $(".firstrun-only").css("display", "");
    }

    $('#use-security').click(function () {
        if (this.checked) {
            $('#protocol-select').text("https://");
        } else {
            $('#protocol-select').text("http://");
        }
    });

    /* Detect if the user typed "http[s]://" into the URL box and correct for it */
    $("#syncurl").blur(function () {
        if ($('#syncurl').val().toLowerCase().startsWith("https://")) {
            $('#syncurl').val($('#syncurl').val().replace(/https\:\/\//ig, ""));
            $('#protocol-select').text("https://");
            $('#use-security').prop('checked', true);
        } else if ($('#syncurl').val().toLowerCase().startsWith("http://")) {
            $('#syncurl').val($('#syncurl').val().replace(/http\:\/\//ig, ""));
            $('#protocol-select').text("http://");
            $('#use-security').prop('checked', false);
        }
    });

    $("#key").on("keyup", function () {
        if (window.getSelection().toString() !== '') {
            return;
        }
        var text = $('#key').val().replace(/\s+/g, '');
        var formatted = "";
        for (var i = 1; i <= text.length; i++) {
            formatted = formatted + text[i - 1];
            if (i % 5 == 0 && i > 1 && i < text.length) {
                // add a space every 5 characters,
                // unless it's the first character
                // or the last character
                formatted = formatted + " ";
            }
        }
        $('#key').val(formatted.toUpperCase());
    });

    $('#username').on("keyup", function () {
        $('#username').val($('#username').val().toLowerCase());
    });

    function manualsetup() {
        if ($('#syncurl').val().toLowerCase().startsWith("http")) {
            var syncurl = $('#syncurl').val();
        } else {
            var syncurl = $('#protocol-select').text() + $('#syncurl').val();
        }
        var username = $('#username').val();
        var key = $('#key').val().replace(/\s+/g, '');
        checkAndSave(syncurl, username, key);
    }

    function manualshow() {
        $('#manual_setup').css('display', 'block');
    }

    function checkAndSave(syncurl, username, key) {
        $.post(syncurl, {
            username: username,
            key: key,
            action: "check_key"
        }, function (data) {
            if (data.status === 'OK') {
                setupusername = username;
                setupsyncurl = syncurl;
                setupsynckey = key;
                openscreen("setup2");
            } else {
                navigator.notification.alert(data.msg, null, "Error", 'Dismiss');
            }
        }, "json").fail(function () {
            navigator.notification.alert("Could not connect to the server.  Try again.", null, "Error", 'Dismiss');
        });
    }


    function scanCode() {
        try {
            cordova.plugins.barcodeScanner.scan(
                    function (result) {
                        if (!result.cancelled) {
                            if (!result.text.startsWith("bizsync://")) {
                                navigator.notification.alert("Invalid sync code.  Try again.", null, "Error", 'Dismiss');
                                return;
                            }
                            var url = result.text.replace("bizsync://", "");
                            var parts = url.split("/");
                            var syncurl = parts[0].replace(/\\/g, "/");
                            var username = parts[1];
                            var key = parts[2];
                            checkAndSave(syncurl, username, key);
                        }
                    },
                    function (error) {
                        navigator.notification.alert("Scanning failed: " + error, null, "Error", 'Dismiss');
                    },
                    {
                        "showFlipCameraButton": false,
                        "prompt": "Scan mobile sync QR code."
                    }
            );
        } catch (ex) {
            navigator.notification.alert(ex.message, null, "Error", 'Dismiss');
        }
    }

    setnavbar("setup");
</script>