<script src="{{ static('libs/featherlight/featherlight.min.js') }}" type="text/javascript"></script>
{% compress js %}
    {{ comment_form.media.js }}
    {% if not REQUIRE_JAX %}
        <script type="text/javascript">
            $(function () {
                $('#id_body').keypress(function () {
                    if (!("MathJax" in window)) {
                        $.ajax({
                            type: "GET",
                            url: '{{ static('mathjax_config.js') }}',
                            dataType: "script",
                            cache: true,
                            success: function () {
                                $.ajax({
                                    type: "GET",
                                    url: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/config=TeX-AMS_HTML',
                                    dataType: "script",
                                    cache: true,
                                    success: function () {
                                        mathjax_pagedown($);
                                    }
                                });
                            }
                        });
                    }
                });
            });
        </script>
    {% endif %}
    <script type="text/javascript">
        $(document).ready(function () {
            window.reply_comment = function (parent) {
                var $comment_reply = $('#comment-' + parent + '-reply');
                var reply_id = 'reply-' + parent;
                if ($comment_reply.find('#' + reply_id).length == 0) {
                    var $reply_form = $('#new-comment').clone(true).prop('id', reply_id);
                    $reply_form.find('h3').html('{{ _('Replying to comment') }}');
                    $reply_form.prepend('<a class="close">x</a>');
                    $reply_form.find('form.comment-submit-form input#id_parent').val(parent);
                    $reply_form.appendTo($comment_reply);
                    register_dmmd_preview($('#' + reply_id + ' #id_body-preview'));
                }
                $comment_reply.fadeIn();

                $('html, body').animate({
                     scrollTop: $comment_reply.offset().top - $('#navigation').height() - 4
                }, 500);
            };

            $(document).on('click', '.close', function() {
                $(this).closest('.reply-comment').fadeOut();
            });

            function update_math($comment) {
                if ('MathJax' in window) {
                    var $body = $comment.find('.comment-body');
                    MathJax.Hub.Queue(['Typeset', MathJax.Hub, $body[0]], function () {
                        $body.find('.tex-image').hide();
                        $body.find('.tex-text').show();
                    });
                }
            }

            window.show_revision = function (comment_id, offset) {
                var $comment = $("#comment-" + comment_id);

                // If .comment-body is hidden, then this is a bad comment that the user has not clicked
                // Thus the revision retrieval should do nothing
                if (!$comment.find('.comment-body').is(':visible'))
                    return;

                var cur_revision = parseInt($comment.attr("data-revision"));
                var max_revision = parseInt($comment.attr("data-max-revision"));
                var revision_ajax = $comment.attr("data-revision-ajax");
                var show_revision = cur_revision + offset;

                $comment.attr("data-revision", show_revision);

                $.get(revision_ajax, {
                    revision: show_revision
                }).done(function (body) {
                    $comment.find('.previous-revision').css({visibility: show_revision == 0 ? 'hidden' : ''});
                    $comment.find('.next-revision').css({visibility: show_revision == max_revision ? 'hidden' : ''});
                    $comment.find('.content').html(body);

                    var edit_text = '{{ _('edit {edits}') }}'.replace("{edits}", show_revision);

                    if (show_revision == 0) {
                        edit_text = '{{ _('original') }}';
                    } else if (show_revision == max_revision && max_revision == 1) {
                        edit_text = '{{ _('edited') }}';
                    }

                    $comment.find('.comment-edit-text').text(' ' + edit_text + ' ');
                    update_math($comment);
                });
            };

            function ajax_vote(url, id, delta, on_success) {
                return $.ajax({
                    url: url,
                    type: 'POST',
                    data: {
                        id: id
                    },
                    success: function (data, textStatus, jqXHR) {
                        var score = $('#comment-' + id + ' .comment-score').first();
                        score.text(parseInt(score.text()) + delta);
                        if (typeof on_success !== 'undefined')
                            on_success();
                    },
                    error: function (data, textStatus, jqXHR) {
                        alert('Could not vote: ' + data.responseText);
                    }
                });
            }

            var get_$votes = function (id) {
                var $comment = $('#comment-' + id);
                return {
                    upvote: $comment.find('.upvote-link').first(),
                    downvote: $comment.find('.downvote-link').first()
                };
            };

            window.comment_upvote = function (id) {
                ajax_vote('{{ url('comment_upvote') }}', id, 1, function () {
                    var $votes = get_$votes(id);
                    if ($votes.downvote.hasClass('voted'))
                        $votes.downvote.removeClass('voted');
                    else
                        $votes.upvote.addClass('voted');
                });
            };

            window.comment_downvote = function (id) {
                ajax_vote('{{ url('comment_downvote') }}', id, -1, function () {
                    var $votes = get_$votes(id);
                    if ($votes.upvote.hasClass('voted'))
                        $votes.upvote.removeClass('voted');
                    else
                        $votes.downvote.addClass('voted');
                });
            };

            var $comments = $('.comments');
            $comments.find('a.hide-comment').click(function (e) {
                e.preventDefault();
                if (!(e.ctrlKey || e.metaKey || confirm('Are you sure you want to hide this comment?')))
                    return;

                var id = $(this).attr('data-id');
                $.post('{{ url('comment_hide') }}', {id: id}).then(function () {
                    $('#comment-' + id).remove();
                    $('#comment-' + id + '-children').remove();
                }).catch(function () {
                    alert('Failed.');
                });
            });

            $comments.find('a.edit-link').featherlight({
                afterOpen: function () {
                    if ('DjangoPagedown' in window) {
                        var $wmd = $('.featherlight .wmd-input');
                        if ($wmd.length) {
                            window.DjangoPagedown.createEditor($wmd.get(0));
                            if ('MathJax' in window) {
                                var preview = $('.featherlight div.wmd-preview')[0];
                                window.editors[$wmd.attr('id')].hooks.chain('onPreviewRefresh', function () {
                                    MathJax.Hub.Queue(['Typeset', MathJax.Hub, preview]);
                                });
                                MathJax.Hub.Queue(['Typeset', MathJax.Hub, preview]);
                            }
                        }
                    }
                    $('#comment-edit').submit(function (event) {
                        event.preventDefault();
                        var id = $('#comment-edit').find('.comment-id').text();
                        var readback = $('#comment-edit').find('.read-back').text();
                        $.post($(this).attr('action'), $(this).serialize()).done(function (data) {
                            $.featherlight.current().close();
                            $.ajax({
                                url: readback
                            }).done(function (data) {
                                var $comment = $('#comment-' + id);
                                var $area = $comment.find('.comment-body').first();
                                $area.html(data);
                                update_math($comment);
                                var $edits = $comment.find('.comment-edits').first();
                                $edits.text('updated');
                            }).fail(function () {
                                console.log('Failed to update comment:' + id);
                            });
                        });
                    });
                },
                variant: 'featherlight-edit'
            });

            var $root = $('html, body');
            $comments.find('a.comment-link').click(function () {
                var href = $.attr(this, 'href');
                $root.animate({
                    scrollTop: $(href).offset().top
                }, 500, function () {
                    window.location.hash = href;
                });
                return false;
            });

            $('img.unveil').unveil(200);

            window.comment_show_content = function (comment_id) {
                var $comment = $('#comment-' + comment_id);
                $comment.find('.comment-body').show();
                $comment.find('.bad-comment-body').hide();
            };
        });
    </script>
{% endcompress %}