window.addEvent("domready", function () {
    "use strict";
    // load QUI
    require(['qui/QUI', 'utils/Controls'], function (QUI, Controls) {
        QUI.addEvent("onError", function (msg, url, linenumber) {
            console.error(msg);
            console.error(url);
            console.error('LineNo: ' + linenumber);
        });

        /**
         * toTop button
         */
        if (document.getElements('[href=#top]')) {
            var toTop         = document.getElements('[href=#top]'),
                buttonVisible = false;

            // show on load
            if (QUI.getScroll().y > 300) {
                toTop.addClass('toTop__show');
                buttonVisible = true;
            }

            // show button toTop after scrolling down
            QUI.addEvent('scroll', function () {
                if (QUI.getScroll().y > 300) {
                    if (!buttonVisible) {
                        toTop.addClass('toTop__show');
                        buttonVisible = true;
                    }
                    return;
                }

                if (!buttonVisible) {
                    return;
                }
                toTop.removeClass('toTop__show');
                buttonVisible = false;
            });

            // scroll to top
            toTop.addEvent('click', function (event) {
                event.stop();
                new Fx.Scroll(window).toTop();
            });
            3
        }

        /**
         * set extra class after page is scrolled
         */
        var menuBar          = document.getElement('.menu-bar'),
            menuBackground   = false,
            pageScrollOffset = QUIQQER_PAGE_SCROLL_OFFSET.toInt() >= 0 ? QUIQQER_PAGE_SCROLL_OFFSET.toInt() : 0;

        // background on load
        if (QUI.getScroll().y > pageScrollOffset) {
            menuBar.addClass('page-scrolled');
            menuBackground = true;
        }

        QUI.addEvent('scroll', function () {
            if (QUI.getScroll().y > pageScrollOffset) {
                if (!menuBackground) {
                    menuBar.addClass('page-scrolled');
                    menuBackground = true;
                }
                return;
            }
            menuBar.removeClass('page-scrolled');
            menuBackground = false;

        });

        initMobileMenu();


        if (QUIQQER_IS_START_PAGE) {
            initNavigation();
            checkActiveMenuElm();
        }
    });
});

/**
 * Click on menu entry scrolls to section
 * Works only on the start page
 */
function initNavigation () {
    var navEntries = document.getElements('#navigation li a');

    navEntries.each(function (Entry) {
        Entry.addEvent('click', function (event) {
            event.stop();

            var target = event.target;

            if (target.nodeName !== 'A') {
                target = target.getParent('a');
            }

            var urlTarget    = target.getAttribute('href'),
                scrollTarget = document.getElement(urlTarget);

            if (scrollTarget) {
                new Fx.Scroll(window, {
                    offset: {
                        y: -QUIQQER_MENU_HEIGHT_AFTER_SCROLL
                    }
                }).toElement(scrollTarget);
            }
        })
    });

    // click on logo scrolls to top
    if (!document.getElement('.menu-bar-inner-logo a')) {
        return;
    }
    
    document.getElement('.menu-bar-inner-logo a').addEvent('click', function (event) {
        event.stop();
        new Fx.Scroll(window).toTop();
    });
}


/**
 * Check scroll position and mark active element in the menu
 */
function checkActiveMenuElm () {
    var navEntriesContainer = document.getElements('#navigation li'),
        navEntries          = document.getElements('#navigation li a'),
        sections            = [],
        breakPoints         = [],
        scrollOffset        = QUIQQER_SCROLL_OFFSET.toInt() >= 0 ? QUIQQER_SCROLL_OFFSET.toInt() : 0;

    navEntries.each(function (Entry) {
        if (document.getElement(Entry.getAttribute('href'))) {
            sections.push(document.getElement(Entry.getAttribute('href')));
        }
    });

    sections.each(function (Section) {
        breakPoints.push({
            start: Section.getPosition().y,
            end  : false,
            id   : Section.getAttribute('id')
        });
    });

    var i, len = breakPoints.length;

    for (i = 0; i < len; i++) {
        if (i === len - 1) {
            breakPoints[i].start = breakPoints[i].start - scrollOffset;
            breakPoints[i].end   = QUI.getBodyScrollSize().y;
            continue;
        }

        breakPoints[i].start = breakPoints[i].start - scrollOffset;
        breakPoints[i].end   = breakPoints[i + 1].start - scrollOffset;
    }

    var activeId = 0;

    // set active menu entry on page load
    breakPoints.each(function (Point) {
        if (QUI.getScroll().y >= Point.start && QUI.getScroll().y < Point.end) {
            activeId = Point.id;

            // set new active entry
            navEntriesContainer.removeClass('active');
            document.getElement('[data-qui-url="' + Point.id + '"]').addClass('active');
        }
    });

    QUI.addEvent('scroll', function () {
        var id        = false,
            scrollPos = QUI.getScroll().y;

        breakPoints.each(function (Point) {
            if (scrollPos >= Point.start && scrollPos < Point.end) {
                id = Point.id
            }
        });

        if (activeId === id) {
            return;
        }

        activeId = id;

        navEntriesContainer.removeClass('active');
        document.getElement('[data-qui-url="' + id + '"]').addClass('active');
    });
}

/**
 * Initialize mobile menu and handle click actions (open / close)
 */
function initMobileMenu () {
    var OpenMenu  = document.getElement('.open-mobile-menu-button'),
        CloseMenu = document.getElement('.menu-bar-inner-nav-closeBtn'),
        Nav       = document.getElement('.menu-bar-inner-nav'),
        BG        = null; //page background

    if (!OpenMenu || !CloseMenu) {
        return;
    }

    require(['qui/controls/utils/Background'], function (QUIBackground) {
        var closeMenu = function () {
            if (!Nav.hasClass('open')) {
                return;
            }

            Nav.removeClass('open');
            BG.hide();
            document.getElement('body').removeClass('menu-opened');
        };

        var openMenu = function () {
            if (!BG) {
                BG = new QUIBackground();
                BG.create().inject(document.getElement('.menu-bar'));
                BG.addEvent('click', closeMenu);
            }

            if (Nav.hasClass('open')) {
                return;
            }

            BG.show();
            Nav.addClass('open');
            document.getElement('body').addClass('menu-opened');
        };

        var navEntries = document.getElements('#navigation li a');
        navEntries.addEvent('click', closeMenu)
        OpenMenu.addEvent('click', openMenu);
        CloseMenu.addEvent('click', closeMenu);
    });
}
