1(function($) {
2    var fadeOption = {duration: 150};
3
4    function toggleLeft() {
5        $('#sidebar_bg').show('fade', fadeOption);
6        $('#dokuwiki__aside').show();
7    }
8
9    function toggleRight() {
10        $('#sidebar_bg').show('fade', fadeOption);
11        $('#dokuwiki__tools').show();
12    }
13
14    function preventParentWheel(e) {
15    	var curScrollPos = $(this).scrollTop();
16    	var scrollableDist = $(this).prop('scrollHeight') - $(this).outerHeight();
17    	var wheelEvent = e.originalEvent;
18    	var dY = wheelEvent.deltaY;
19
20    	if (dY < 0 && curScrollPos <= 0) {
21    		return false;
22    	}
23    	if (dY > 0 && curScrollPos >= scrollableDist) {
24    		return false;
25    	}
26    }
27
28    function showSearch() {
29        $('div.search').toggle();
30        $('div.search').find('input.edit').select();
31    }
32
33    function bindEvents() {
34        $('.sidebar').on('wheel scroll', preventParentWheel);
35        $('.btn_left').click(function() {
36            toggleLeft();
37        });
38        $('.btn_right').click(function() {
39            toggleRight();
40        });
41        $('#sidebar_bg').click(function() {
42            $(this).hide('fade', fadeOption);
43            $('#dokuwiki__aside').hide();
44            $('#dokuwiki__tools').hide();
45        });
46        $('.btn_search').click(function() {
47            showSearch();
48        });
49        $(document).keydown(function(e) {
50            if (e.which == 70 && e.altKey) {
51                showSearch();
52                e.preventDefault();
53            }
54        });
55    }
56
57    function initUI() {
58        // Move TOC
59        if ($('.page h2').length > 0) {
60            $('.toc_wikipedia').find('#dw__toc').insertBefore($('.page h2:first'));
61        } else {
62            $('.toc_wikipedia').find('#dw__toc').insertAfter($('.page h1:first').next('.level1'));
63        }
64        $('.toc_dokuwiki').find('#dw__toc').insertAfter($('.page h1:first'));
65        // Anchor link should be shifted by header pixel
66        $(window).on("hashchange", function () {
67            window.scrollTo(window.scrollX, window.scrollY - 48);
68        });
69    }
70
71    $(function() {
72        initUI();
73        bindEvents();
74    });
75})(jQuery);
76