// Doghole Comment
(function() {

    var $content;
    
    var setCommentError = function(error) {
        var $comment_error = $('.comment-error').stop();
        $comment_error.css('display', 'block');
        setTimeout(function(){$comment_error.css('display','none')},3000);
        return $comment_error.html(error);
    };
    
    var commentBlur = function(cancel, blur) { 
        if (cancel) {
            var $cancelReply = $('#cancel-comment-reply-link');
            if ($cancelReply.length && $cancelReply.css('display') !== 'none') {
                $cancelReply.click();
                if (!blur)
                    return true;
            }
            if (!blur)
                return false;
        }
        if (blur) {
            $(".comment-triggered").hide();
            $(".comment-trigger").fadeIn("slow");
            var tmp = $content.val();
            $content.val('').attr('placeholder', '').blur();
            window.Doghole.Cookies.set('comment_content', tmp, 30);
            return true;
        }
        return false;
    }

    $(window).on('popstate', function (e) {
        var state = event.state;
        if (state && state.commentContent) {
            $('.comment-page').html(state.commentContent);
            initComment();
        } 
    });
    // Initialize comment control
    var initComment = function () {
        $(document).ready(function() {
            
            // As its name, will be called after press ESC while editing or before comment page changed.
            var foldCommentTextarea = function () {
                var $commentDiv = $('.comment-list .respond');
                if($commentDiv.length) {
                    $('comment').append($commentDiv);
                    $commentDiv.find('[name=replyTo]').val('');
                }
                commentBlur(false, true);
            };
            
            
            // Comment page changed
            $('body').off('click', '.comment-page-num').on('click', '.comment-page-num', function(e){
                e.preventDefault();
                window.history.replaceState({status: 0, commentContent: $('.comment-page')[0].innerHTML}, '', location.href);
                var changedUrl = $(this).attr('href');
                var commentPageUrl = changedUrl.replace(/(\/[^\/]*?)$/, '/comments$1');
                foldCommentTextarea();
                $('.comment-page').load(commentPageUrl, function(response, status, xhr){
                    var scroll_to_top_position = $('[id^=li-comment-]:first').offset().top - 80;
                    if (scroll_to_top_position < 0) {
                        scroll_to_top_position = 0;
                    }
                    initComment();
                    window.history.replaceState({status: 0, commentContent: $('.comment-page')[0].innerHTML}, '', changedUrl);
                    $('body,html').finish().animate({
                        scrollTop: scroll_to_top_position
                    },
                    800);
                });
                window.history.pushState({status: 0} ,'' , changedUrl);
                return false;
            });
            
            var ni = x => $(`.new-comment-form input[name="${x}"]`),
            $author = ni('author'),
            $mail = ni('email'),
            $url = ni('url');
            $content = $('.new-comment-form textarea');
            
            $("comment,.comment-list").off('click', '.new-comment').on('click', '.new-comment', function() {
                $(".comment-trigger").hide();
                $(".comment-triggered").fadeIn("slow");
                $content.attr('placeholder', 
                'Press Esc to fold comment input box.\r\nComment now supports Markdown.')
                $.each($(".new-comment-form").find('textarea, input[type="text"]'), function(i, that){
                    var $that = $(that);
                    if ($that.length) {
                        $that.val($that.val() || window.Doghole.Cookies.get('comment_' + $that.attr('name')) || '');
                    }
                });
            }).off('keyup', '.new-comment textarea').on('keyup', '.new-comment textarea', function(e) {
                var current_height;
                current_height = $(this).height();
                if (current_height < this.scrollHeight && current_height < 350) {
                    $(this).height(this.scrollHeight);
                }
                if (e.which === 27 && !commentBlur(true, false)) {
                    foldCommentTextarea();
                }
            }).off('input propertychange', '.new-comment-form textarea,.new-comment-form input[type="text"]')
              .on('input propertychange', '.new-comment-form textarea,.new-comment-form input[type="text"]', function(){
                // save comment params to cookie
                var $this = $(this);
                window.Doghole.Cookies.set('comment_' + $this.attr('name'), $this.val(), 30);
            }).off('click', '.reply').on('click', '.reply', function(e){  // reply
                e.preventDefault();
                // Copy comment div to assigned div
                var $commentDiv = $('.respond');
                if ($commentDiv.length) {
                    $(this).parents('.author').next().after($commentDiv);
                    $commentDiv.find('[name=replyTo]').val($(this).attr('to'));
                    $content.click();
                    $content.focus();
                }
                return false;
            }).off('submit', '.new-comment-form').on('submit', '.new-comment-form', function(e) {
                e.preventDefault();
                var that = this, refreshSubmit = function(enable){
                    $(that).find('button.comment-submit-button')[enable?'removeClass':'addClass']('btn-loading');
                };
                refreshSubmit(false);
                var content, $form, 
                author = $author.val() || '',
                mail = $mail.val() || '',
                url = $url.val() || '';
                content = $content.val();
                $comment_parent = $('#comment-parent');
                $form = $('.new-comment-form');
                if (content.length < 5) {
                    setCommentError('Min length of comment is 5');
                    $content.focus();
                    refreshSubmit(true);
                    return false;
                }
                if (!author.length) {
                    setCommentError('Author name is required');
                    $author.focus();
                    refreshSubmit(true);
                    return false;
                }
                if(url.length) {
                    var urlReg = /^(https?:\/\/)?([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}(\/.*?)?$/;
                    if(!urlReg.test(url)) {
                        setCommentError('Invalid url format');
                        $url.focus();
                        refreshSubmit(true);
                        return false;
                    }
                }
                if ($mail.length) {
                    if (!mail) {
                        setCommentError('Mail is required');
                        $mail.focus();
                        refreshSubmit(true);
                        return false;
                    }
                    var mailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                    if(!mailReg.test(mail)) {
                        setCommentError('Invalid mail format');
                        $mail.focus();
                        refreshSubmit(true);
                        return false;
                    }
                }
                var postUrl = $form.attr('action');
                var postData = {};
                $.each($form.serializeArray(), function(i, field){
                    postData[field.name] = field.value;
                });
                // ajax
                $.ajax({
                    url:postUrl, 
                    type:'post', 
                    data: postData,
                    complete: function(data) {
                        data = JSON.parse(data.responseText);
                        if(!data.ok) {
                            setCommentError(typeof data.data == 'string' && data.data || "评论失败");
                        }
                        else {
                            data = data.data;
                            if (data) {
                                // Create new comment
                                var $newComment = $(`<li id="li-comment-${data.id}" class="comment"></li>`).append(
                                    $('<div class="author"></div>')
                                        .append(
                                            $('<img referrerpolicy="same-origin" class="avatar"></img>').attr({
                                                alt: data.author,
                                                src: data.email
                                            }))
                                        .append($('<div class="author-name"></div>').append(
                                            (data.url?$('<b></b>').append(
                                                $('<a></a>').attr({
                                                    href: data.url,
                                                    rel: 'external nofollow'
                                                }).text(data.author)
                                            ):$('<b></b>').text(data.author))).append(
                                                $('<a>reply</a>').attr({
                                                    rel:'nofollow', class: 'reply', to: data.id
                                                })
                                            ))
                                        .append($(`<div class="author-date"><small>${data.createTime}</small></div>`))
                                ).append(
                                    (function (){
                                        return $('<div class="comment-content"></div>')[data.markdown?'append':'text'](data.content).prepend(data.commentStatus == 'RELEASED'?
                                            '':('<span class="comment-error">您的评论待审核后可见</span><br/>')
                                        )
                                        })()
                                    );
                                // Render katex
                                if (data.markdown && katex) $.each($newComment.find('.katex'), function (i, v) {
                                    katex.render(v.textContent, v);
                                });
                                if (data.replyTo == -1) {
                                    // append to comment end
                                    $('ol.comment-list:first').append($newComment);
                                }
                                else {
                                    var finds = $('#li-comment-' + data.replyTo);
                                    if (!finds.length) {
                                        location.reload(); 
                                    }
                                    // dom of new comment
                                    $newComment = $('<ol class="comment-list"></ol>').append($newComment);
                                    
                                    var appendTo = finds.find('.comment-children:first');
                                    if (!appendTo.length){
                                        appendTo = finds;
                                        $newComment = $('<div class="comment-children"></div>').append($newComment);
                                    }
                                    appendTo.append($newComment);
                                }
                                // Render code highlight
                                if (data.markdown && Prism) Prism.highlightAll();
                                
                                var scroll_to_top_position = $('#li-comment-' + data.id).offset().top - 80;
                                if (scroll_to_top_position < 0) {
                                    scroll_to_top_position = 0;
                                }
                                $('body,html').finish().animate({
                                    scrollTop: scroll_to_top_position
                                },
                                800);
                            } else {
                                location.reload(); 
                            }
                            if(!commentBlur(true, false)) {
                                var $commentDiv = $('.comment-list .respond');
                                if($commentDiv.length) {
                                    $('comment').append($commentDiv);
                                    $commentDiv.find('[name=replyTo]').val('');
                                }
                                commentBlur(false, true);
                            }
                            window.Doghole.Cookies.del('comment_content');
                            $('li[id^="li-comment-"].comment.active').removeClass('active');
                        }
                        $content.focus();
                        refreshSubmit(true);
                        $content = $('.new-comment-form textarea');
                    }
                });
                return false;
            });
            // hash tag highlight
            var hashTag = location.hash.slice(1);
            if (hashTag.indexOf('comment-') == 0) {
                $(`#li-${hashTag}`).addClass('active');
            }
        });
    }
    initComment();
}).call(this);