$(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 = $('<div class="ui dividing left rail"> \
                            <div id="pyppl-report-toc" class="ui sticky fixed top"> \
                                <div class="ui vertical following fluid accordion text menu"><div> \
                            </div> \
                        </div>');

        var add_toc = function(node, dom) {
            if (node.level == 1) {
                var menode = $('<div class="item" />')
                    .append('<a href="#'+ node.me.prop('id') +'" class="title"></a>')
                    .appendTo(dom);
                if (node.children.length > 0) {
                    menode.find('a')
                        .append('<i class="dropdown icon"></i><b>'+ node.me.html() +'</b>');
                } else {
                    menode.find('a').html(node.me.html());
                }
            }  else {
                var menode = $('<div class="menu content" />')
                    .append('<a href="#'+ node.me.prop('id') +'" class="item">'
                            + node.me.text() + '</a>')
                    .appendTo(dom);
            }
            if (node.children.length > 0) {
                var dnode = $('<div />').addClass('content menu');
                dnode.appendTo(menode);
                for (var i in node.children) {
                    add_toc(node.children[i], dnode);
                }
            }
        };
        for (var i in tocs.children) {
            add_toc(tocs.children[i], tocroot.find('#pyppl-report-toc > div:first'), i==0);
        }

        $('#pyppl-report-container').prepend(tocroot);
        $('#pyppl-report-main').addClass('with-toc');
    };

    // sidebar / toc
    if (window.metadata.toc > 0) {
        generate_toc(window.metadata.toc)
        $('<div id="toc-controller"><i title="Toggle sidebar" class="arrow alternate circle left outline icon"></i></div>')
            .prependTo('body')
            .click(function(){
                $('#pyppl-report-toc').toggle();
                $('#pyppl-report-main').toggleClass('with-toc without-toc');
                $(this).children('i').toggleClass('left right');
            });

    }

    // admonition
    $('div.admon').each(function(){
        var $title = $('<div class="header" />');
        var title = $(this).attr('data-head');
        var klass = 'positive';
        switch(true) {
            case $(this).hasClass('note'):
                title = title || 'Note';
                break;
            case $(this).hasClass('warn') || $(this).hasClass('warning'):
                title = title || 'Warning';
                klass = 'warning'
                break;
            case $(this).hasClass('info') || $(this).hasClass('tip'):
                title = title || 'Warning';
                klass = 'info';
                break;
            case $(this).hasClass('danger') || $(this).hasClass('error'):
                title = title || 'Error';
                klass = 'negative';
                break;
            case $(this).hasClass('example'):
                title = title || 'Example';
                klass = 'violet';
                break;
        };
        $(this).addClass('ui message ' + klass);
        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
            .children('.panel')
            .addClass('ui tab attached segment')
            .end()
            .prepend('<div class="ui menu top attached tabular">' +
                    $wrapper.children('.panel')
                        .get()
                        .map((panel, index) => '<a class="item '+ (index==0 ? 'active' : '') +'" ' +
                            '                      data-tab="'+ panelid + '-' + index + '">'+
                            $(panel).attr('data-head') +
                            '</a>')
                        .join('\n') +
                    '</div>')
            .children('.panel')
            .each(function(index) {
                $(this).attr('data-tab', panelid + '-' + index);
                if (index==0) {
                    $(this).addClass('active');
                }
            });
    };

    var panelAccordion = function($wrapper) {
        var panelid = $wrapper.prop('id');
        $wrapper
            .addClass('ui styled fluid accordion')
            .children('.panel')
            .addClass('content')
            .each(function(index){
                $(this)
                    .before('<div class="title">'+
                            '   <i class="dropdown icon"></i>' +
                            $(this).attr('data-head') +
                            '</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="ui longer modal" id="figurePreviewer-modal"> \
        <div class="header" id="figurePreviewer"></div> \
		<div class="image content"> \
            <div class="ui image"> \
			    <img class="image" 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();
    });
});
