$(function() {

    // toc
    var generate_toc = function(level) {
        var get_tocs = function() {
            // get tocs
            var heading_selector = 'h1'
            for (var i=2; i<=level; i++) {
                heading_selector += ', h' + i
            }
            /** tocs:
             *  { parents = [], nodes = []}
             **/
            var tocs = {parents: [], me: null, children: [], level: 0};
            var parent = tocs;
            $(heading_selector).each(function(index, heading) {
                heading = $(heading);
                if (heading.attr('data-toc')
                        && heading.attr('data-toc') == 'false') {
                    return;
                }
                var lvl = parseInt(heading.prop('tagName')[1]);
                if (parent.level != lvl - 1) {
                    try {
                        parent = parent.parents[lvl-1];
                    } catch (e) {
                        console.error(e);
                    }
                }
                var me = {parents: [].concat(parent.parents, [parent]),
                        me: heading,
                        level: lvl,
                        children: []};
                parent.children.push(me);
                parent = me;

            });
            return (tocs)
        };

        var tocs = get_tocs();

        var tocroot = $('<nav id="pyppl-report-toc" class="navbar navbar-light bg-light bd-toc" />')
            .append('<nav class="nav nav-pills flex-column" />');

        var add_toc = function(node, dom) {
            var menode = $('<a href="#'+ node.me.prop('id') +
                '" class="nav-link nav-'+ node.level +'">' +
                node.me.text() + '</a>').appendTo(dom);
            if (node.children.length > 0) {
                var dnode = $('<nav />').addClass('nav nav-pills flex-column');
                menode.after(dnode);
                for (var i in node.children) {
                    add_toc(node.children[i], dnode);
                }
            }
        };
        for (var i in tocs.children) {
            add_toc(tocs.children[i], tocroot.children('nav:first'));
        }

        $('#pyppl-report-main').before(tocroot);
    };

    // sidebar / toc
    if (window.metadata.toc > 0) {
        generate_toc(window.metadata.toc)

        $('#toc-controller').click(function() {
            var thistext = $(this).text();
            $(this).text(thistext.indexOf('Hide') != -1
                ? thistext.replace('Hide', 'Show')
                : thistext.replace('Show', 'Hide'));
            $("#pyppl-report-toc").toggle();
            $('#pyppl-report-main').toggleClass('with-toc without-toc');
        });
    }

    // admonition
    $('div.admon').each(function(){
        var $title = $('<p class="admon-title" />');
        var title = $(this).attr('data-head');
        var klass = 'alert-primary';
        switch(true) {
            case $(this).hasClass('note'):
                title = title || 'Note';
                break;
            case $(this).hasClass('warn') || $(this).hasClass('warning'):
                title = title || 'Warning';
                klass = 'alert-warning'
                break;
            case $(this).hasClass('info') || $(this).hasClass('tip'):
                title = title || 'Warning';
                klass = 'alert-info';
                break;
            case $(this).hasClass('danger') || $(this).hasClass('error'):
                title = title || 'Error';
                klass = 'alert-danger';
                break;
            case $(this).hasClass('example'):
                title = title || 'Example';
                klass = 'alert-secondary';
                break;
        };
        $(this).addClass('alert ' + klass).attr('role', 'alert');
        if (title != "false") {
            $title.text(title);
            $(this).prepend($title);
        }
    });


    // links
    // add target="_blank" to all links unless the links have target specified
    $('a').each(function() {
        var link = $(this);
        if (link.is('.pyppl-report-reference')) {
            link.attr('href',
                      'https://scholar.google.com/scholar?q=' +
                      escape(link.text().split(/:\s*(.+)/)[1]));
        }
        var href = link.attr('href');
        // exclude anchor links as well
        if (!!link.attr('target')
                || !href
                || href[0] == '#'
                || href.indexOf('javascript:') == 0) {
            return;
        }

        link.attr('target', '_blank');
    });

    // images
    var previewimg = 'data:image/jpeg;base64, '
    $('img[src="data:null"]').each(function(){
        $(this)
            .attr('src', previewimg)
            .attr('data-echo', $(this).attr('data-src'))
            .removeAttr('data-src');
    }).on('load', function(){
        $(this).css({
            'max-width': '420px',
            'max-height': '500px'
        })
        .attr('title', 'Click to zoom in.')
        .click(function() {
            // popups
            $('#figurePreviewer-image').attr('src', $(this).attr('src'));
            $('#figurePreviewer').html($(this).next().text());
            $('#figurePreviewer-modal').modal('show');
        });
    });

    // panels
    var panelTab = function($wrapper) {
        var panelid = $wrapper.prop('id');
        $wrapper
            .addClass('tab-content')
            .children('.panel')
            .addClass('tab-pane fade')
            .attr('role', 'tabpanel')
            .first()
            .addClass('show active')
            .end()
            .end()
            .before('<ul class="nav nav-tabs" role="tablist">' +
                    $wrapper.children('.panel')
                        .get()
                        .map((panel, index) => '<li class="nav-item">'+
                            '<a class="nav-link '+ (index==0 ? 'active' : '') +'" ' +
                            '   id="'+ panelid + '-' + index + '" ' +
                            '   data-toggle="tab" ' +
                            '   href="#'+ panelid + '-' + index + '-content' + '" ' +
                            '   role="tab" ' +
                            '   aria-controls="'+ panelid + '-' + index + '-content' + '" ' +
                            '   aria-selected="'+ (index==0 ? 'true' : 'false') +'">' +
                            $(panel).attr('data-head') +
                            '</a>' +
                            '</li>')
                        .join('\n') +
                    '</ul>')
            .children('.panel')
            .each(function(index) {
                $(this)
                    .attr('aria-labelledby', panelid + '-' + index)
                    .prop('id', panelid + '-' + index + '-content');
            });
    };

    var panelAccordion = function($wrapper) {
        var panelid = $wrapper.prop('id');
        $wrapper
            .addClass('accordion')
            .children('.panel')
            .each(function(index){
                $(this)
                    .wrap('<div class="card" />')
                    .wrap('<div id="'+ panelid + '-' + index + '-content" '+
                          '     class="collapse '+ (index==0 ? 'show' : '') +'" '+
                          '     aria-labelledby="'+ panelid + '-' + index + '" '+
                          '     data-parent="#'+ panelid +'">')
                    .wrap('<div class="card-body" />');
                $('#' + panelid + '-' + index + '-content')
                    .before('<div class="card-header" id="'+ panelid + '-' + index + '">'+
                            '   <div class="mb-0">' +
                            '       <button class="btn btn-link" type="button" data-toggle="collapse" '+
                            '               data-target="#'+ panelid +'-' + index + '-content' +'" '+
                            '               aria-expanded="'+ (index==0 ? 'true' : 'false') +'" '+
                            '               aria-controls="'+ panelid +'-' + index + '-content' +'">' +
                            $(this).attr('data-head') +
                            '       </button>' +
                            '   </div>' +
                            '</div>');
            });
    };
    // has preceding siblings,      no leading siblings
    $(':not(div.panel) + div.panel, div.panel:first-child').each(function(index){
        var panels = $(this).nextUntil(':not(div.panel)')
               .addBack()
               .wrapAll('<div id="pyppl-report-panel-'+ (index+1) +'" />');
        var $panelWrapper = $('#pyppl-report-panel-' + (index + 1));
        if ($(this).hasClass('tab')) {
            panelTab($panelWrapper);
        } else if ($(this).hasClass('accordion')) {
            panelAccordion($panelWrapper);
        } else if (panels.length <= 4) {
            panelTab($panelWrapper);
        } else {
            panelAccordion($panelWrapper);
        }
    });

    // toggle layui-this for toc items
    $('.accordion').on('shown.bs.collapse', function(event){
        $(document).scrollTop(
            $(this).find('.collapse:visible').prev().offset().top -
            $('#pyppl-report-header').outerHeight()
        );
    });

    // image previewer
    $('body').append('<div class="modal fade" id="figurePreviewer-modal" tabindex="-1" role="dialog" aria-labelledby="figurePreviewer" aria-hidden="true"> \
		<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl"> \
		<div class="modal-content"> \
			<div class="modal-header"> \
			<div class="modal-title" id="figurePreviewer"></div> \
			<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> \
			</div> \
			<div class="modal-body"> \
			<img src="" style="cursor: pointer;" id="figurePreviewer-image" style="width:100%"> \
			</div> \
		</div> \
		</div> \
    </div>');

    $('#figurePreviewer-image').click(function(){
        var a = document.createElement('a');
        a.href = this.src;
        a.target = '_blank';
        a.click();
    });
});
