<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('mathjax3_config.js') }}',
              dataType: "script",
              cache: true,
              success: function () {
                $.ajax({
                  type: "GET",
                  url: 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js',
                  dataType: "script",
                  cache: true,
                  success: function () {
                    mathjax_pagedown($);
                  }
                });
              }
            });
          }
        });
      });
    </script>
  {% endif %}
  <script type="text/javascript">
    $(document).ready(function () {
      let loading_gif = "<img src=\"{{static('loading.gif')}}\" style=\"height: 3em; margin-bottom: 3px\" class=\"loading\">";
      window.reply_comment = function (parent) {
        var $comment_reply = $('#comment-' + parent + '-reply');
        var reply_id = 'reply-' + parent;
        var new_id = 'id' + parent + '_body';
        if ($comment_reply.find('#' + reply_id).length == 0) {
          var $reply_form = $('#new-comment').clone(true).prop('id', reply_id).css("display", "");
          $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.find('div#wmd-button-bar-id_body').empty().prop('id','wmd-button-bar-' + new_id);
          $reply_form.find('textarea.wmd-input').val('').prop('id', 'wmd-input-' + new_id);
          $reply_form.find('div#id_body-preview').attr('data-textarea-id', 'wmd-input-' + new_id).prop('id', new_id + '-preview');
          $reply_form.appendTo($comment_reply);
          register_dmmd_preview($reply_form.find('div#' + new_id + '-preview'));
          if ('DjangoPagedown' in window) {
            window.DjangoPagedown.createEditor($reply_form.find('div.wmd-wrapper').get(0));
          }
        }
        $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.typeset($body[0]);
        }
      }

      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);
          }
        });
      }
      const queryString = window.location.search;
      const urlParams = new URLSearchParams(queryString);
      const target_comment = urlParams.get('comment-id');

      window.comment_get_replies = function (id, parent_none) {
        var $comment_show_btn = $("#comment-" + id  + " .show_more_reply");
        $comment_show_btn.hide();
        var $comment = $("#comment-" + id + "-children");
        $comment.append(loading_gif);
        ajax_get_reply('{{ url('comment_get_replies') }}', id, parent_none);
      }

      function ajax_get_reply(url, id, parent_none) {
        return $.ajax({
          url: url,
          type: 'GET',
          data: {
            id: id,
            parent_none: parent_none,
          },
          success: function(data) {
            var $comment_loading = $("#comment-" + id + "-children .loading");
            $comment_loading.hide();
            var $comment = $("#comment-" + id + "-children");
            $comment.append(data);
            MathJax.typeset($('#comments')[0]);
            register_time($('.time-with-rel'));
          }
        })
      }

      window.comment_show_more = function (id, parent_none, offset, target_comment) {
        if (parent_none == 1) {
          var $comment_show_btn = $("#comment-0"  + " .show_more_comment");
          $comment_show_btn.hide();
          var $comment = $("#comment-0");
          $comment.append(loading_gif);
        } else {
          var $comment_show_btn = $("#comment-" + id  + "-children" + " .show_more_comment");
          $comment_show_btn.hide();
          var $comment = $("#comment-" + id + "-children");
          $comment.append(loading_gif);
        }
        ajax_comment_show_more('{{ url('comment_show_more') }}', id, parent_none, offset, target_comment);
      }

      function ajax_comment_show_more(url, id, parent_none, offset, target_comment) {
        return $.ajax({
          url: url,
          type: 'GET',
          data: {
            id: id,
            parent_none: parent_none,
            offset: offset,
            target_comment: target_comment,
          },
          success: function(data) {
            if (parent_none == 1) {
              var $comment_loading = $("#comment-0" + " .loading");
              $comment_loading.hide();
              var $comment = $("#comment-0");
              $comment.append(data);
            } else {
              var $comment_loading = $("#comment-" + id + "-children .loading");
              $comment_loading.hide();
              var $comment = $("#comment-" + id + "-children");
              $comment.append(data);
            }
            MathJax.typeset($('#comments')[0]);
            register_time($('.time-with-rel'));
          }
        })
      }

      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 () {
          register_dmmd_preview($('#id-edit-comment-body-preview'));
          if ('DjangoPagedown' in window) {
            var $wmd = $('.featherlight .wmd-wrapper');
            if ($wmd.length) {
              window.DjangoPagedown.createEditor($wmd.get(0));
              if ('MathJax' in window) {
                var preview = $('.featherlight div.wmd-preview')[0];
                MathJax.typeset(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();
      };

      $("#write-comment").click( function(event)  {
        event.preventDefault();
        $("#new-comment").show("slow");
        $("#write-comment").hide();
        $(".no-comments-message").hide();
      });

    });
  </script>
{% endcompress %}