/// <reference path="references.js" />
(function () {
    "use strict";

    var rerenderOnNavdrawerOrientationChanged = false;

    window.addEventListener('orientationchange', function () {

        if (rwthapp.platformInfo.isTablet()) {

            rwthapp.util.changeOrientationState();

            rwthapp.util.changeOrientationOnTablet();
        }
    });

    document.addEventListener('deviceready', onDeviceReady.bind(this), false);

    function onDeviceReady() {

        $('body').addClass('platform-' + rwthapp.platformInfo.getPlatformName());
        $('body').addClass('version-' + rwthapp.platformInfo.getPlatformVersion());
        $('body').addClass('major-version-' + rwthapp.platformInfo.getPlatformVersion().split(".")[0]);

        rwthapp.templateRenderer.render($('header'), 'navbar', { navbarData: { needsBackButton: rwthapp.platformInfo.needsBackButton() } });

        rwthapp.util.showLoadingScreen();

        rwthapp.logging.logger.debug("onDeviceReady triggered");

        rwthapp.util.initAppOrientationBehavior();

        /***********************
        * Bind event handlers
        ************************/
        // Register backbutton handlers
        if (rwthapp.platformInfo.isWindowsUniversal() && WinJS.Application) {
            // Backbutton handler for Windows (Universal)
            WinJS.Application.onbackclick = function (e) {
                // Backbutton logic
                rwthapp.util.backButtonClicked();

                // Prevent default behaviour (yes, needs to return true)
                return true;
            };
        } else {
            // Register default backbutton handler
        document.addEventListener('backbutton', function (e) {
            // android and wp back button logic
            rwthapp.util.backButtonClicked();
            // cancel event so that no default behavior is done
                e.preventDefault();
        }, false);
        }

        // iOS back button logic
        $('#rwthapp-back-button').click(function () {
            rwthapp.util.backButtonClicked();
        });

        // Replace window.open for Ubuntu Phone
        if (rwthapp.platformInfo.isUbuntu()) {
            window.open = cordova.InAppBrowser.open;
        }

        // Handle the Cordova pause and resume events
        document.addEventListener('pause', onPause.bind(this), false);
        document.addEventListener('resume', onResume.bind(this), false);

        // Navigation initialisation
        $('#rwthapp-nav-toggle').click(function () {
            rwthapp.templates.menu.initMainMenu();
            $('.my-slide-nav').navdrawer('open');
            return false;
        });

        $('.my-slide-nav').on('drawerVisibilityStateChange', function () {

            var menuPinnedState = $('.my-slide-nav').navdrawer('isAlwaysVisible');
            
            $('#pinMenu').prop("checked", menuPinnedState);

            rwthapp.templates.menu.setMenuPinned(menuPinnedState);
            rwthapp.templates.menu.changeBackbuttonVisibility();

            if (menuPinnedState) {

                // remove transition to render not right
                $('#slide-menu-content').removeAttr("style");
            }
        });

        
        /***********************
        * UI initialization
        ************************/
        // Perform postprocessing (fixing icons, removing waves effect) if necessary
        rwthapp.templateRenderer.performPostprocessing();

        $('.my-slide-nav').navdrawer('init', {
            closeOnClick: true,
            //swipeTarget: '#container'
        });

        // iOS specific initialization
        if (rwthapp.platformInfo.needsBackButton()) {

            $('#rwthapp-back-button').css("display", "");
            StatusBar.overlaysWebView(false);
            StatusBar.backgroundColorByHexString(rwthapp.colors.blue());
        }

        if (!rwthapp.platformInfo.hasCorrectButtonLineHeight()) {
            $("main").addClass("correct-line-height");
        }

        // Register handlebars helpers
        Handlebars.registerHelper('langString', rwthapp.localization.handlebarsLangStringHelper);
        Handlebars.registerHelper('encodeURIComponent', function (s) { return encodeURIComponent(s); });
        Handlebars.registerHelper('replaceAllSpacesWithNonBreakingSpaces', function (s) { return new Handlebars.SafeString(Handlebars.escapeExpression(s).replace(/ /g, "&nbsp;")); });
        Handlebars.registerHelper('gn', function (val, options) { return val > 0; });
        Handlebars.registerHelper('or', function (a, b, options) { if (a != "" || b != "") { return true; } else { return false; } });

        if (rwthapp.platformInfo.isFirefoxOS()) {
            $.ajaxSetup({
                xhr: function () {
                    return new window.XMLHttpRequest({
                        mozSystem: true
                    });
                }
            });
        }

        /***********************
        * Asynchronous initialization
        ************************/
        // Helper function to create a promise that always resolves successfully
        var createFailsafePromise = function (promise) {
            return Promise.resolve(promise).catch(function (error) {
                rwthapp.logging.logger.error("Error in initialization.", error);
            });
        };

        Promise.resolve().then(function () {
            /***********************
            * Version upgrade if necessary
            ************************/
            return rwthapp.updater.performUpdates();
        }).then(function () {
            /***********************
            * Initialization of helpers that use localStorage
            ************************/
            var promises = [];

            // Use short timeouts for requests during initialization
            rwthapp.connection.requestHelper.activateShortTimeouts();

            // Load language files
            rwthapp.localization.loadPreferredLanguage();

            // Load favorites
            rwthapp.favorites.initFromLocalStorage();

            // Check if app version is still supported
            promises.push(createFailsafePromise(rwthapp.versionCheck.initialize()));

            // Initialize login state
            promises.push(createFailsafePromise(rwthapp.tokenManager.initialize()));

            return Promise.all(promises);
        }).then(function () {
            /***********************
            * Initialization of helpers that need an oauth token
            ************************/
            var promises = [];

            // getUserData for displaying it in menu (firstname, lastname), needs to be done after tokenManager initialization
            promises.push(createFailsafePromise(rwthapp.templates.menu.getUserData()));

            promises.push(createFailsafePromise(rwthapp.templates.menu.initMenuLang()));

            return Promise.all(promises);
        }).catch(function (error) {
            // Catch all potential errors and continue anyway, should not happen
            rwthapp.logging.logger.error("Error in initialization.", error);
        }).then(function () {
            // Reactivate normal timeouts
            rwthapp.connection.requestHelper.deactivateShortTimeouts();

            // Check if app version is supported or not
            if (rwthapp.versionCheck.isNotSupported()) {
                // Load update template, which also disables all navigation in app
                rwthapp.navigator.gotoPage("update");
            } else {
                if (rwthapp.versionCheck.isDeprecated()) {
                    // Display warning
                    rwthapp.notifications.showDialog(rwthapp.templateRenderer.fetch("update.modal.deprecated", {
                        storeURL: rwthapp.options.getStoreUrl(),
                        imageURL: rwthapp.options.getStoreImageUrl()
                    }));

                    // Perform postprocessing (fixing icons, removing waves effect) if necessary
                    rwthapp.templateRenderer.performPostprocessing();
                }

                // Display changelog if necessary
                rwthapp.updater.showChangelogIfUpdated();

                // Trigger initial page load
                $(window).trigger('hashchange');
            }
        });
    }

    function onPause() {
        rwthapp.logging.logger.debug("paused");
        rwthapp.navigator.onPause();
    }

    function onResume() {

        // onResume we have to reload the menu complete to merge server menu
        // changes into current runtime
        rwthapp.templates.menu.initMenuLang();

        rwthapp.logging.logger.debug("resumed");
        rwthapp.navigator.onResume();
    }
} )();