define(['jquery', 'underscore'], function ($, _) {
    return function () {
        var newMessageIcon = $('#infobar_new_imessage_icon');
        var mainContainer = $(".main_container");
        newMessageIcon.tooltip();
        $('#navClock').tooltip();
        $('.notification_options a').tooltip();

        $(window).scroll(function () {
            $('.tooltip').css('visibility', 'hidden');
        });

        $(window).scroll(_.debounce(function () {
            $('.tooltip').css('visibility', 'visible');
        }, 150));

        newMessageIcon.mouseleave(function () {
            $('.tooltip').css('display', 'none');
        });

        newMessageIcon.mouseenter(function () {
            $('.tooltip').css('display', 'block');
        });

        $(".navbar").hasClass("desktop-sideview") ? mainContainer.addClass("sideview") : mainContainer.removeClass("sideview");

        $(".js-bookmark-page").click(function (e) {
            e.preventDefault();

            var title = document.querySelector("meta[name='claromentis-page-title']").content;
            var domain = window.location.origin;
            var url = window.location.href;
            url = url.replace(domain, '');
            var hash = '';
            var path = '';

            if (window.location.hash) {
                hash = window.location.hash;
                path = window.location.pathname;
            }

            var options = {
                title:     title,
                url: encodeURIComponent(url),
                csrf_token: document.csrf_token
            };

            var request = $.ajax({
                url: '/intranet/people/add_bookmark.php',
                data: options,
                type: "POST"
            });

            request.done(function(response) {
                var params = $.param({
                    'message': response.message
                });
                url = appendParamsToUrl(url, params, hash);
                window.location.replace(url);
            });

            request.fail(function(response, status, error) {
                var params = $.param({
                    'message': response.responseJSON.message,
                    'is_error_message': 1
                });
                url = appendParamsToUrl(url, params, hash);
                window.location.replace(url);
            });

            function appendParamsToUrl(url, params, hash) {
                if (hash !== '')
                    url = path;

                var delimiter = url.indexOf('?') >= 0 ? '&' : '?';
                url = url + delimiter + params + hash;
                return url;
            }
        });

        var tabPressed = false;

        // handle keyboard tab on app menu search input
        var searchInput = $('.js-navbar-application-search-input');

        searchInput.on('keydown', function(e){
            var keyCode = e.keyCode || e.which;
            tabPressed = keyCode === 9;
        });

        searchInput.on('focusout', function(e) {
            if (tabPressed) {
                $('.js-application-toggle').data('can-close', false);
                $('.js-app-icon-link:visible').first().trigger('focus');
            } else if (!tabPressed){
                $('.js-application-toggle').data('can-close', true);
            }
        });
        
        // handle keyboard tab / shift+tab on app menu item
        $('.js-app-wrapper-list .js-app-icon-link').on('keydown', function(e){
            var keyCode = e.keyCode || e.which;
            tabPressed = keyCode === 9 && !e.shiftKey;
            var shiftTabPressed = keyCode === 9 && e.shiftKey;

            if (tabPressed) {
                e.preventDefault();
                if ($(this).parent().is('.js-navbar-application:visible:last')) {
                    return $('.js-navbar-application-search-input').trigger('focus');
                }
                var nextVisibleMenuItem = $(this).parent('li').nextAll("li:visible").first();

                //if next item is an app link focus on it, if it is divider then skip that item
                if (nextVisibleMenuItem.find('.js-app-icon-link:visible').length > 0) {
                    return nextVisibleMenuItem.find('.js-app-icon-link:visible').trigger('focus');
                } else {
                    return nextVisibleMenuItem.next().find('.js-app-icon-link:visible').trigger('focus');
                }
            }
            if (shiftTabPressed) {
                e.preventDefault();
                if ($(this).parent().is('.js-navbar-application:visible:first')) {
                    return $('.js-navbar-application-search-input').trigger('focus');
                }

                var prevVisibleMenuItem = $(this).parent('li').prevAll("li:visible").first()

                //if previous item is an app link focus on it, if it is divider then skip that item
                if (prevVisibleMenuItem.find('.js-app-icon-link:visible').length > 0) {
                    return prevVisibleMenuItem.find('.js-app-icon-link:visible').trigger('focus');
                } else {
                    return prevVisibleMenuItem.prev().find('.js-app-icon-link:visible').trigger('focus');
                }
            }
        })

        //stop Bootstrap hiding the app menu when it isn't supposed to
        $('.js-nav-item-applications').on('hide.bs.dropdown', function (event) {
            if($('.js-application-toggle').data('can-close') === false) {
                event.preventDefault();
                tabPressed = false;
                return false;
            }
        })

        //allow app menu to close when user clicks elsewhere on page
        $('body').on('click', function(){
            $('.js-application-toggle').data('can-close', true);
        })
    };
});
