/* 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/. */

var $$ = Dom7;

var shown_notifications = [];

var app = new Framework7({
    root: "#app",
    name: "Netsyms",
    id: "com.netsyms.BusinessMobile",
    routes: routes,
    dialog: {
        buttonOK: "Dismiss"
    }
});

var mainView = app.views.create('.view-main', {
    url: "/"
});

var router = mainView.router;

var loadingProgressDialog;

/**
 * Thanks to https://stackoverflow.com/a/13542669
 * @param {type} color
 * @param {type} percent
 * @returns {String}
 */
function shadeColor2(color, percent) {
    var f = parseInt(color.slice(1), 16), t = percent < 0 ? 0 : 255, p = percent < 0 ? percent * -1 : percent, R = f >> 16, G = f >> 8 & 0x00FF, B = f & 0x0000FF;
    return "#" + (0x1000000 + (Math.round((t - R) * p) + R) * 0x10000 + (Math.round((t - G) * p) + G) * 0x100 + (Math.round((t - B) * p) + B)).toString(16).slice(1);
}

/**
 * Load the app.html view and open an app with nativeish 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 openapp(id, api, url, icon, title, injectcode, shownavbar) {
    $('#content-zone').fadeOut(300, function () {
        $('#content-zone').load("views/app.html", function () {
            $('#content-zone').fadeIn(300, function () {
                launchapp(id, api, url, icon, title, injectcode, shownavbar);
            });
        });
    });
}

function restartApplication() {
    navigator.splashscreen.show();
    // We're doing the timeout so we don't run afoul of server-side rate limiting
    setTimeout(function () {
        window.location = "index.html";
    }, 3000);
}

// Handle back button to close things
document.addEventListener("backbutton", function (event) {
    if (isconfigvalid()) {
        if ($("#appframe").length && historyctr > 0) {
            console.log("going back");
            var iframe = document.getElementById("appframe");
            iframe.contentWindow.postMessage("goback", "*");
            historyctr--;
        } else {
            if (cordova.platformId == 'android') {
                StatusBar.backgroundColorByHexString("#1976d2");
            } else {
                StatusBar.backgroundColorByHexString("#2196f3");
            }
            router.back();
        }
    } else {
        router.back();
    }
}, false);

document.addEventListener("deviceready", function () {

    if (cordova.platformId == 'android') {
        StatusBar.backgroundColorByHexString("#1976d2");
        StatusBar.styleLightContent();
    }

    if (isconfigvalid()) {
        loadingProgressDialog = app.dialog.progress('Loading...', 0);
        loadingProgressDialog.setText('');
        loadingProgressDialog.setProgress(20);
        loadingProgressDialog.setText('Account');
        getuserinfo(function () {
            loadingProgressDialog.setProgress(50);
            loadingProgressDialog.setText('Notifications');

            // Setup notification sync
            initNotifications();
            loadingProgressDialog.setProgress(60);
            // Load homepage/dashboard
            loadingProgressDialog.setText('Apps');
            loadHomePage(false);
        });
    } else {
        // Try to recover data from NativeStorage back to localStorage
        recoveraccounts(function (ok) {
            if (ok) {
                // Success, restart app to reload from localStorage
                restartApplication();
            } else {
                // No account data found, open setup
                router.navigate({
                    name: 'setup0'
                });
            }
        })
    }
    setTimeout(navigator.splashscreen.hide, 500);
}, false);

router.on("pageBeforeIn", function (pagedata) {
    app.progressbar.hide();
});

router.on("pageInit", function (pagedata) {
    pagedata.$el.find('script').each(function (el) {
        if ($$(this).attr('src')) {
            var s = document.createElement('script');
            s.src = $$(this).attr('src');
            $$('head').append(s);
        } else {
            eval($$(this).text());
        }
    });
    app.progressbar.hide();
    switch (pagedata.name) {
        case "settings":
            updateSettingsData();
            break;
    }
});