$(function() {
    $(document.body).addClass('js');

    // const.
    var IS_RTL = $(document.documentElement).attr('dir') == 'rtl';
    var IS_FLAT_STRUCTURE = $(document.body).hasClass('structure-flat');
    var IS_TOP = $(document.body).hasClass('top');

    function isLRegion() {
        return $('.main > .box-content > .content').css('float') != 'none';
    }


    // Detect PC User-Agent to Display 'Print' Link
    (function() {
        var userAgent = window.navigator.userAgent || '';
        if (userAgent.indexOf("Mobile") == -1) {
            $(document.body).addClass('pc');
        }
    })();


    // Build S-Region Header Menu
    (function() {
        var selector = '#menu > ul > li';
        var lastChildSelector = '#header-menu > :last-child';
        var $lastChild = $(lastChildSelector);
        $(selector).each(function() {
            // clone li without children
            var $li = $(this.cloneNode(false));
            $li.removeAttr('id');
            // clone link with children (text)
            var $a = $(this).children('a:first-child').clone();
            $li.append($a);
            $li.insertBefore($lastChild);
        });
    })();


    // S and M Region Header Toggle
    (function() {
        var selector = '.header-toggle-button';
        var cssClassOpened = 'toggle-opened';
        var duration = '';

        $(selector).each(function() {
            var $a = $(this);
            var $panel = $a.parent().next();
            // ARIA
            $a.attr({
                'role': 'button',
                'aria-controls': $panel.attr('id'),
                'aria-expanded': 'false'
            });

            // If user activate a link inside the panel,
            // close the panel and activate the link immediately
            $panel.find('a').click(function() {
                // close the panel
                close($a, 0);
                // activate the link
                return true;
            });
        }).click(function() {
            // if there is an animating panel, do nothing
            if (getContainer().children('[aria-busy=true]').length > 0) {
                return false;
            }
            var $a = $(this)
            var $panel = getPanel($a);
            if (!$panel.hasClass(cssClassOpened)) {
                // if there is an opened panel, close it
                var $opened = getOpened();
                close($opened, duration, function() {
                    // then open panel
                    open($a, duration);
                });
            } else {
                // close panel
                close($a, duration);
            }
            return false;
        });

        function getContainer() {
            return $('#header-items');
        }

        function getPanel($a) {
            return $('#' + $a.attr('aria-controls'));
        }

        // Return link
        function getOpened() {
            return getContainer().find('a[aria-expanded=true]');
        }

        function open($a, duration) {
            var $panel = getPanel($a);
            $panel.attr('aria-busy', 'true');
            $panel.slideDown(duration, function() {
                $a.attr('aria-expanded', 'true');
                $panel.addClass(cssClassOpened);

                // remove style attribute to hide the panel in the L Region
                // (adding cssClassOpen sets appropriate display property value)
                $panel.removeAttr('style');

                $panel.attr('aria-busy', 'false');
            });
        }

        function close($a, duration, callback) {
            var $panel = getPanel($a);
            if ($panel.length > 0) {
                $panel.attr('aria-busy', 'true');
                $panel.slideUp(duration, function() {
                    $a.attr('aria-expanded', 'false');
                    $panel.removeClass(cssClassOpened);

                    // remove style attribute to hide the panel in the L Region
                    // (removing cssClassOpen sets appropriate display property value)
                    $panel.removeAttr('style');

                    $panel.attr('aria-busy', 'false');
                    if (callback) {
                        callback();
                    }
                });
            } else {
                if (callback) {
                    callback();
                }
            }
        }
    })();


    function resolvePath(path) {
        var knownDirectories = ['cover', 'contents', 'search'];
        var pathname = window.location.pathname;
        var comp = pathname.split('/');
        var directory = pathname.match(/\.html$/) ? comp[comp.length - 2] : comp[comp.length - 1];
        if ($.inArray(directory, knownDirectories) > -1) {
            return '../' + path;
        }
        return path;
    }


    // L Region Menu Toggle
    (function() {
        if (IS_FLAT_STRUCTURE) {
            return;
        }
        var selector = '#menu > ul > li > a';
        var cssClassClosed = 'toggle-closed';
        var openedSrc = resolvePath('common/img/arrow_open.png');
        var closedSrc = resolvePath(IS_RTL ? 'common/img/arrow_close_rtl.png' : 'common/img/arrow_close.png');
        var openedAlt = RESOURCES['menuToggleOpened'];
        var closedAlt = RESOURCES['menuToggleClosed'];

        $(selector).each(function(index) {
            var $a = $(this);
            var $ul = $a.next('ul');

            // Needs from CSS
            var $span = $('<span>');
            $span.append($a.contents());
            $span.appendTo($a);

            // ARIA
            var id = 'menu-submenu' + index;
            $ul.attr('id', id);
            $a.attr({ 'role': 'button', 'aria-controls': id });

            // Close inactive menu
            if ($ul.find('.active').length == 0) {
                $ul.addClass(cssClassClosed);
            }

            // Setup Icon
            $('<img>').appendTo($a);

            // Update Icon
            updateIcon($a, $ul);
        }).click(function(event) {
            if (!isLRegion()) {
                return false;
            }
            var $a = $(this);
            var $ul = $a.next('ul');

            // Close or Open
            $ul.toggleClass(cssClassClosed);

            // Update Icon
            updateIcon($a, $ul);
            return false;
        });

        function updateIcon($a, $ul) {
            var $img = $a.children('img');
            if ($ul.hasClass(cssClassClosed)) {
                $img.attr('src', closedSrc);
                $img.attr('alt', closedAlt);
                $a.attr('aria-expanded', 'false');
            } else {
                $img.attr('src', openedSrc);
                $img.attr('alt', openedAlt);
                $a.attr('aria-expanded', 'true');
            }
            return $img;
        }
    })();
});
