/* Minification failed. Returning unminified contents.
(801,35-36): run-time error JS1003: Expected ':': }
(1020,28-29): run-time error JS1003: Expected ':': }
 */
/// <reference path="ad.js" />
$(document).ready(function () {
    var container = $(comments.defaults.comment.container_selector);

    if (container != null && container.length > 0) {
	    var hasTopicId = (container.data('topic-id') != null && container.data('topic-id') != 0);
	    if (document.URL.indexOf('comments=') == -1 && hasTopicId) {
	        setTimeout(function () {
                comments.init();
            }, 1000); //1 second delay
	    } else {
            comments.init();
        }
    }
});

var comments = {
    panelOpen: false,
    timeout: {},
    defaults: {
        scrollSpeed: 200,
        message: {
            selector: '#Message',
            submit_selector: '#message, #submit',
            cancel_selector: '#comment-cancel',
            reply_base: '#reply-base',
            url: '/comments/comment',
            reply_url: 'comments/reply',
            reply_to_html: '<a href="#reply" id="reply-base">Replying to {user} </a>',
            comment_replies_popular: '#comment-replies-popular',
            comment_lock: '#comment-replies-popular,#comment-replies',
            reply_selector: '#comment-reply',
            reply_id_selector: '[Name=ReplyId]',
            comment_link: '.comment-link'
        },
        comment: {
            change_page_selector: '.change_page',
            container_selector: '#comment-container',
            selector: '#comments',
            reply_selector: '.comment-replies a.reply',
            report_selector: '.comment-replies a.report',
            report_url: '/comments/report/',
            has_voted_url: '/comments/hasvoted/',
            url: '/comments/comments',
            reply_page_url: '/comments/replypage',
            highlight_class: 'highlight',
            list_reply_attr: 'reply',
            list_reply_selector: 'ol > li[data-reply]',
            comment_reply_selector: 'ol > li[data-reply="{reply}"]',
            replied_selector: '.replied',
            url_page_selector: 'comments'
        },
        vote: {
            up_vote_url: '/comments/upvote/',
            down_vote_url: '/comments/downvote/',
            data_vote_selector: 'vote',
            selector: '.comment-replies > li a[data-vote]',
            negative_class: 'neg',
            vote_controls_selector: 'div.vote-controls',
            vote_selector_not: 'a[data-vote!="{vote}"]',
            vote_selector: 'a[data-vote="{vote}"]',
            vote_counter_selector: '.vote',
            down_vote_selector: '#comments .votedown > a',
            down_vote_class: 'downVoted'
        },
        topic: {
            id_attr: 'data-topic-id',
            type_attribute: 'section',
            rows_per_first_page_attr: 'data-rowsperfirstpage'
        },
        user: {
            next_at: '.nextat',
            got_data_marker: 'data-got-data',
            next_at_url: '/comments/usersnextevent/',
            id_data_attr: 'user-id',
            user_toggle_parent: '.hover-toggle-parent',
            user_panel_select: '.hover-toggle-parent[data-user-id="{user}"]'
        },
        admin: {
            lock_topic_url: '/comments/locktopic/',
            lock_selector: '#adminControls a.lock',
            deleteTopic_url: '/comments/deletetopic/',
            delete_selector: '#adminControls a.delete',
            disableVoting_url: '/comments/toggledisablevoting/',
            disableVoting_selector: '#adminControls a.disablevoting',
            update_event_url: '/comments/topicevent/',
            update_event_selector: '#adminControls a.update',
            delete_comment_url: '/comments/deletecomment/',
            delete_comment_selector: '.comment-replies > li a.delete',
            delete_notify_comment_url: '/comments/deletecommentandnotifyuser/',
            delete_notify_comment_selector: '.comment-replies > li a.delete-notify',
            add_bulk_vote_url: '/comments/addbulkvote/',
            remove_bulk_vote_url: '/comments/removebulkvote/',
            bulk_vote_selector: '.updateVote',
            bulk_vote_direction: 'data-updatevote',
            hide_comment_selector: '.hide-comment',
            hide_comment_url: '/comments/hidecomment/',
            get_moderator_name_selector: '.getMod',
            moderator_name: '.mod',
            get_moderator_name_url: '/comments/getmoderatorname/',
            show_comment_selector: '.show-comment',
            show_comment_url: '/comments/showcomment/',
            breakcache_selector: '#adminControls a.breakcache',
            breakcache_url: '/comments/breakcache/'
        }
    },
    locked: false,
    lock: function (locked) {
        comments.locked = locked;
    },
    init: function () {
        window.onpopstate = function (event) {
            var replyId = comments.getReplyId();
            if (replyId && replyId > 0) {
                comments.scrollToReply(replyId);
            } else {
                var data = comments.getFilterData();
                comments.loadComments(data);
            }
        };
        $(window).on('comments.initComplete load', function () {
            if (document.URL.indexOf('comments=') > -1) {
                comments.scrollTo(comments.defaults.comment.container_selector);
            }

            if (document.URL.indexOf('#') > -1) {
                var replyId = comments.getReplyId();
                if (replyId && replyId > 0) {
                    comments.scrollTo(comments.defaults.comment.container_selector);
                }
            }
        });

        $(document.body).on('comments.loadComplete', function () {
            
            updateLanguage();

            comments.setNgc();
               
            if ((document.URL.indexOf('comments=') > -1) && (!document.URL.indexOf('#') > -1)) {
                var pageSelected = $('.but.page.selected');
                if (pageSelected) {
                    var pageNumber = pageSelected.data('page');
                    if (pageNumber) {
                        pageNumber = pageNumber.trim();
                        if (pageNumber != comments.getParameterByName(comments.defaults.comment.url_page_selector).trim()) {
                            var filter = comments.getFilterData();
                            filter.page = parseInt(pageNumber);
                            comments.saveHistory(filter.contentId, filter.page, 0);
                        }
                    }
                }
            }
        });

        $(document).on('mouseover', comments.defaults.user.user_toggle_parent, function (e) {
            var element = e;
            if (!comments.panelOpen) {
                if (comments.timeout) {
                    clearTimeout(comments.timeout);
                }
                comments.timeout = setTimeout(function () {
                    comments.panelOpen = true;
                    comments.loadUserNextEvent(element);
                }, 500);
            }
        });
        $(document).on('mouseleave', comments.defaults.user.user_toggle_parent, function (e) {
            if (comments.timeout) {
                clearTimeout(comments.timeout);
            }
            comments.panelOpen = false;
        });
        $(document).on('click', '#detail .comment-link', function (e) {
            e.preventDefault();
            comments.scrollTo(comments.defaults.comment.selector);
        });
        $(document).on('click', comments.defaults.message.cancel_selector, function (e) {
            e.preventDefault();
            comments.resetReplyBox();
        });
        $(document).on('click', comments.defaults.comment.reply_selector, function (e) {
            e.preventDefault();
            comments.addReply(e);
        });
        $(document).on('click', comments.defaults.vote.selector, function (e) {
            e.preventDefault();
            if (comments.locked || $(e.target).hasClass('selected')) {
                return;
            }
            comments.addVote(e);
        });
        $(document).on('click', comments.defaults.comment.report_selector, function (e) {
            e.preventDefault();
            comments.reportComment(e);
        });
        $(document).on('click', comments.defaults.comment.change_page_selector, function (e) {
            e.preventDefault();
            var page = parseInt($(e.target).data('page'));
            comments.changePage(page);
        });
        $(document).on('click', comments.defaults.vote.down_vote_selector, function (e) {
            e.preventDefault();
            $(e.target).closest('div').css('display', 'none');
            $(e.target).closest('li').removeClass(comments.defaults.vote.down_vote_class);
        });
        $(document).on('keyup', function (e) {
            switch (e.which) {
                case 37: // prev (arrow left)
                    if (comments.locked || $(comments.defaults.message.selector).is(":focus")) {
                        break;
                    }
                    var prev = $(comments.defaults.comment.container_selector).find('[data-type="prev"]');
                    if (prev) {
                        prev.click();
                    }
                    break;
                case 39: // next (arrow right)
                    if (comments.locked || $(comments.defaults.message.selector).is(":focus")) {
                        break;
                    }
                    var next = $(comments.defaults.comment.container_selector).find('[data-type="next"]');
                    if (next) {
                        next.click();
                    }
                    break;
                case 27: // close message (esc)
                    $(comments.defaults.message.cancel_selector).click();
                    break;
            };
        }),
        //Admin
            $(document).on('click', comments.defaults.admin.lock_selector, function (e) {
                e.preventDefault();
                if (comments.locked) {
                    return;
                }
                if (confirm("Are you sure to " + $(comments.defaults.admin.lock_selector).text().toLowerCase() + " this topic?")) {
                    comments.admin.addLock(e);
                }
            });
        $(document).on('click', comments.defaults.admin.breakcache_selector, function (e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }
            comments.admin.breakCache(e);

        });

        $(document).on('click', comments.defaults.admin.delete_selector, function (e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }

            if (confirm("Are you sure to delete this topic?")) {
                comments.admin.deleteTopic(e);
            }
        });
        $(document).on('click', comments.defaults.admin.disableVoting_selector, function (e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }
            comments.admin.toggleDisableVoting(e);
            
        });
        $(document).on('click', comments.defaults.admin.update_event_selector, function (e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }
            comments.admin.updateTopicEventId();
        });
        $(document).on('click', comments.defaults.admin.delete_comment_selector, function (e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }
            if (confirm("Are you sure to delete this comment?")) {
                comments.admin.deleteComment(e);
            }
        });
        $(document).on('click', comments.defaults.admin.delete_notify_comment_selector, function (e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }
            if (confirm("Are you sure to delete this comment?")) {
                comments.admin.deleteCommentAndNotifyUser(e);
            }
        });
        $(document).on('click', comments.defaults.admin.bulk_vote_selector, function(e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }
            comments.admin.bulkVote(e);
        });

        $(document).on('click', comments.defaults.admin.hide_comment_selector, function(e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }
            comments.admin.hideComment(e);
        });

        $(document).on('click', comments.defaults.admin.get_moderator_name_selector, function (e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }
            comments.admin.getModeratorName(e);
        });

        $(document).on('click', comments.defaults.admin.show_comment_selector, function(e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }
            comments.admin.showComment(e);
        });

        $(document).on('click', comments.defaults.comment.replied_selector, function (e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }
            var replyId = $(e.target).attr("data-reply");
            var filter = comments.getFilterData();
            comments.saveHistory(filter.contentId, filter.page, replyId);
            comments.scrollToReply(replyId);
        });

        $(document).on('click', comments.defaults.message.comment_link, function (e) {
            e.preventDefault();
            if (comments.locked) {
                return;
            }

            var filter = comments.getFilterData();
            var replyId = $(this).attr("data-id");
            comments.saveHistory(filter.contentId, filter.page, replyId);
            comments.scrollToReply(replyId);
        });

        var replyId = comments.getReplyId();
        if (replyId && replyId > 0) {
            comments.scrollToReply(replyId);
        } else {
            var data = comments.getFilterData();
            comments.loadComments(data);
        }

        $(document).on('mouseenter', '.hover-toggle-parent', function () {
            $(this).parent('li').addClass('hover');
        });
        $(document).on('mouseleave', '.hover-toggle-parent', function () {
            $(this).parent('li').removeClass('hover');
        });

        $(document.body).trigger('comments.initComplete');
    },
    setNgc: function() {
        $('.comment-item').each(function (i, obj) {
            var visible = $(obj).data('gc');
            var authorUserId = $(obj).data('user-id');
            var loggedInUserId = parseInt($('#user-id').val());
            var seeNgc = $('#see-ngc').val() === "true" ? true : false;

            if (visible)
                return;

            if (seeNgc) {
                $(obj).css("background-color", "#606060");
                $(obj).css("opacity", "0.4");
                return;
            }

            if (authorUserId !== loggedInUserId || !loggedInUserId) {
                $(obj).remove();
            }
        });
    },
    changePage: function (page) {
        comments.loadComments(comments.getFilterData(page));
        
        var filter = comments.getFilterData();
        //If we're moving from the first load to the second page, rewrite the history
        if (page == 2 && filter.page == 1 && document.URL.indexOf('comments=') == -1 && document.URL.indexOf('#') == -1) {
            comments.rewriteHistory(document.URL, 1, 0);
        }
        comments.saveHistory(filter.contentId, page);
        comments.scrollTo(comments.defaults.comment.selector);
    },
    loadHasVoted: function () {
        var element = $(comments.defaults.comment.list_reply_selector);
        if (element && element.length > 0) {
            var results = element.map(function () {
                return $(this).data('reply');
            });
            if (results.length > 0) {
                var query = "";
                results.each(function (i, v) {
                    query += "id=" + v;
                    if (i < results.length - 1) {
                        query += '&';
                    }
                });
                $.ajax({
                    type: 'GET',
                    url: comments.defaults.comment.has_voted_url + '?' + query,
                    async: true
                }).done(function (data) {
                    if (data && data.result) {
                        $(data.result).each(function () {
                            comments.updateVote(this);
                        });
                    }
                    comments.findNegativeVotes();
                });
            }
        }
    },
    updateVote: function (result) {
        var element = comments.findVoteElement(result.Key);
        if (element && element.length > 0) {
            var positive = $(element.find('[data-vote="+"]'));
            var negative = $(element.find('[data-vote="-"]'));
            if (result.Value == 0) {
                //Cannot vote
                return;
            } else if (result.Value == 1) {
                //Positive vote
                positive.addClass('selected');
                negative.addClass('removeVote');
            } else if (result.Value == 2) {
                //Negative vote
                positive.addClass('removeVote');
                negative.addClass('selected');
            }

            positive.show();
            negative.show();
        }
    },
    findVoteElement: function (replyId) {
        var element = $(comments.defaults.comment.comment_reply_selector.replace("{reply}", replyId));
        if (element && element.length > 0) {
            return element.find(comments.defaults.vote.vote_controls_selector);
        }
    },
    loadComments: function (data, replyId) {
        $(comments.defaults.message.comment_lock).css('opacity', '0.4');
        comments.lock(true);
        var defaults = this.defaults;
        var $this = $(comments.defaults.comment.container_selector);
        if ($this.length == 0) {
            return;
        }
        $.ajax({
            type: 'GET',
            url: defaults.comment.url,
            async: true,
            data: data,
        }).done(function (data) {
            $this.html(data);
            if (replyId) {
                var reply_element = $(comments.defaults.comment.comment_reply_selector.replace("{reply}", replyId));
                if (reply_element.length > 0) {
                    comments.scrollToReply(replyId);
                }
            }
            comments.loadHasVoted();
            comments.lock(false);
            comments.refreshAd();
            $(document.body).trigger('comments.loadComplete');

        });
    },
    loadUserNextEvent: function (e) {
        var $this = $(e.target).parent().parent();
        if ($this.attr(comments.defaults.user.got_data_marker) == "false") {
            var userId = $this.data(comments.defaults.user.id_data_attr);
            $.ajax({
                type: 'GET',
                url: comments.defaults.user.next_at_url + userId
            }).done(function (data) {
                var elements = $(comments.defaults.user.user_panel_select.replace("{user}", userId));
                elements.attr(comments.defaults.user.got_data_marker, true);
                if (data && data.Id != 0 && data.Title.length > 0) {
                    var nextAt = elements.find(comments.defaults.user.next_at);
                    var eventElements = nextAt.children('a');
                    eventElements.attr("href", eventElements[0].href + data.Id);
                    eventElements.text(data.Title);
                    nextAt.show();
                }
            });
        }
    },
    getReplyId: function () {
        return document.location.hash.length > 0 ? parseInt(document.location.hash.replace('#', '')) : null;
    },
    saveHistory: function (contentId, page, replyId) {
        var url = '';

        var queryStart = window.location.href.search('reviews/') > 0
                            || window.location.href.search('features/') > 0
                            || window.location.href.search('tracks/') > 0
                            || window.location.href.search('events/') > 0
                            || window.location.href.search('news/') > 0
            ? ''
            : '?';

        var contentQueryStringNameAndValue = queryStart + comments.buildContentQueryStringNameAndValue(contentId);

        url = contentQueryStringNameAndValue
            + ((replyId > 0) ? ('#' + replyId) : ((queryStart == '' ? '?' : '&') + comments.defaults.comment.url_page_selector + '=' + page));

        history.pushState({
            page: page,
            reply: replyId
        },
            null,
            url
        );

        if (typeof ga != 'undefined') {
            var urlStripped = window.location.pathname + window.location.search + window.location.hash;
            urlStripped = urlStripped.substring(1);
            ga('send', 'pageview', urlStripped);
        }
    },
    rewriteHistory: function (url, page, replyId) {
        // Replace current history
        history.replaceState({
            page: page,
            reply: replyId
        }, null, url);
    },
    buildContentQueryStringNameAndValue: function (id) {
        if (window.location.href.search('tracks/') > 0) {
            return ('');
        }
        // Check podcast/ exchange
        var search = window.location.search;
        if (search.match('exchange=')) {
            return 'exchange=' + id;
        } else if (search.match('podcast=')) {
            return 'podcast=' + id;
        } else if (search.match('set=')) {
            return 'set=' + id;
        } else if (search.match('id=')) {
            return 'id=' + id;
        }
        return id;
    },
    getParameterByName: function (name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    },
    getFilterData: function (page) {
        var pageFromUrlString = comments.getParameterByName(comments.defaults.comment.url_page_selector);
        if (pageFromUrlString.length > 0) {
            var pageFromUrl = parseInt(pageFromUrlString);
        }

        var pageElement = $('.page.selected');
        var currentPage = pageElement.length > 0 ? parseInt(pageElement.attr('data-page')) : 1;
        var commentContainer = $(comments.defaults.comment.container_selector);
        var data = {
            contentId: comments.defaults.content_id || commentContainer.data('content-id'),
            topicId: commentContainer.attr(comments.defaults.topic.id_attr),
            page: page || pageFromUrl || currentPage || 1,
            perPage: comments.defaults.per_page || commentContainer.data('per-page'),
            perFirstPage: comments.defaults.per_first_page || commentContainer.data('per-first-page'),
            section: commentContainer.data(comments.defaults.topic.type_attribute)
        }
        return data;
    },
    onBegin: function (data) {
        var clean = $(comments.defaults.message.selector).val().trim();
        if (clean.length == 0) {
            $("#Message").attr("placeholder", " I need a message!").addClass("input-validation-error");
            return false;
        }
        // reject if tags in message
        var regex = new RegExp('<[^>]*>', 'g');
        if (regex.test(clean)) {
            alert('You cannot use HTML!\nLinks and videos will be automatically embedded.');
            return false;
        }
        $(comments.defaults.message.selector).val(clean);
        comments.lock(true);
        $(comments.defaults.message.submit_selector).attr('disabled', 'disabled');
    },
    onComplete: function (data) {
        comments.lock(false);
        $(comments.defaults.message.submit_selector).removeAttr('disabled');

        if (data && data.responseJSON && data.responseJSON.errorMessage && data.responseJSON.errorMessage.length > 0) {
            alert(data.responseJSON.errorMessage);
        } else {
            $(comments.defaults.message.submit_selector).removeAttr('disabled');
            if (data && data.responseJSON) {
                comments.setTopicId(data.responseJSON.topicId);
            }
            $(comments.defaults.message.selector).val('');
            comments.loadComments(comments.getFilterData(1));
        }

    },
    OnFailure: function (data) {
        if (data && data.responseJSON) {
            alert(data.responseJSON.errorMessage);
        }
    },
    setTopicId: function (topicId) {
        $(comments.defaults.comment.container_selector).attr(comments.defaults.topic.id_attr, topicId);
    },
    updateRowsPerFirstPage: function (value) {
        $(comments.defaults.comment.selector).attr(comments.defaults.topic.rows_per_first_page_attr, parseInt($(comments.defaults.comment.selector).attr(comments.defaults.topic.rows_per_first_page_attr)) + value)
    },
    refreshAd: function () {
        if ($(comments.defaults.comment.list_reply_selector).length > 4) {
            $.each(Ad.Spaces.Slots, function (i, v) {
                if (v.Name == "Sky_Comments") {
                    if (v.Slot) {
                        googletag.pubads().refresh([v.Slot]);
                    }
                    else {
                        googletag.cmd.push(function () {
                            v.Slot = Ad.BuildSlot(v);
                            Ad.PushSlot(v);
                            googletag.pubads().refresh([v.Slot]);
                        });
                        v.HasLoaded = true;
                    }
                }
            });
        }
    },
    scrollToReply: function (replyId) {
        var reply_element = $(comments.defaults.comment.comment_reply_selector.replace("{reply}", replyId));
        if (reply_element.length > 0) {
            comments.scrollTo(reply_element);
            $(comments.defaults.comment.list_reply_selector).removeClass(comments.defaults.comment.highlight_class);
            reply_element.addClass(comments.defaults.comment.highlight_class);
        } else {
            var filter = comments.getFilterData();
            $.ajax({
                type: 'GET',
                url: comments.defaults.comment.reply_page_url + '?id=' + replyId + '&perPage=' + filter.perPage + '&perFirstPage=' + filter.perFirstPage,
                async: true,
            }).done(function (data) {
                filter.Page = data.Page;
                filter.replyId = replyId;
                comments.loadComments(filter, replyId);
            });
        }
    },
    scrollTo: function (sElement) {
        var element = (typeof sElement == 'object') ? sElement : $(sElement);
        if (!element || element.length == 0) {
            return;
        }
        $('html, body').animate({
            scrollTop: element.offset().top
        }, comments.defaults.scrollSpeed);
    },
    resetReplyBox: function () {
        $(comments.defaults.message.selector).val("");
        $(comments.defaults.message.reply_base).remove();
        $(comments.defaults.message.reply_id_selector).val(null)
        if ($(comments.defaults.comment.comment_replies_popular).length) {
            $(comments.defaults.comment.comment_replies_popular).after($(comments.defaults.message.reply_selector));
        } else {
            $('#comment-list').prepend($(comments.defaults.message.reply_selector));
        }
    },
    addReply: function (e) {
        $(comments.defaults.message.reply_selector).appendTo($(e.target).parent().parent().parent().parent());
        // move reply box if not fully visible
        var scrollBottom = $(document).scrollTop() + $(window).height();
        var replyOffsetBottom = $(comments.defaults.message.reply_selector).offset().top + $(comments.defaults.message.reply_selector).height();

        if (replyOffsetBottom > scrollBottom) {
            $('html, body').animate({
                scrollTop: $(document).scrollTop() + parseInt($(comments.defaults.message.reply_selector).css('margin-bottom')) + (replyOffsetBottom - scrollBottom)
            }, {
                duration: comments.defaults.scrollSpeed,
                complete: function () {
                    $(comments.defaults.message.selector).focus();
                }
            });
        } else {
            $(comments.defaults.message.selector).focus();
        }

        var originalComment = $(e.target).parent().parent().parent().parent();

        var replyId = originalComment.attr('data-' + comments.defaults.comment.list_reply_attr);
        $(comments.defaults.message.reply_id_selector).val(replyId);

        // add reply link at top to recall textbox
        var reply = comments.defaults.message.reply_to_html.replace('{user}', originalComment.attr('data-user'));
        if (!$(comments.defaults.message.reply_base).length) {
            if ($(comments.defaults.comment.comment_replies_popular).length) {
                $(comments.defaults.comment.comment_replies_popular).after("<h2>" + reply + "</h2>");
            } else {
                $('#comment-list').prepend(reply);
            }

            $(comments.defaults.comment.reply_base).click(function (e) {
                e.preventDefault();
                comments.resetReplyBox();
            });
        } else {
            $(comments.defaults.message.reply_base).html(reply);
        }

        $(comments.defaults.message.reply_id_selector).val(replyId);
    },
    addVote: function (e) {
        var $this = $(e.target);
        var vote = $this.attr('data-' + comments.defaults.vote.data_vote_selector);
        var reply = $this.attr('data-' + comments.defaults.comment.list_reply_attr);
        var replyParent = $(comments.defaults.comment.comment_reply_selector.replace("{reply}", reply));
        var voteControls = replyParent.find(comments.defaults.vote.vote_controls_selector);
        var dataVote = voteControls.find(comments.defaults.vote.vote_selector.replace("{vote}", vote));
        var otherVote = voteControls.find(comments.defaults.vote.vote_selector_not.replace("{vote}", vote));
        var filter = comments.getFilterData();
        filter.replyId = reply;

        $.ajax({
            type: 'POST',
            url: (vote == '+' ? comments.defaults.vote.up_vote_url : comments.defaults.vote.down_vote_url) + reply,
            dataType: 'json',
            data: filter,
            beforeSend: function () {
                comments.lock(true);
                $this.closest('div').css('opacity', '0.4');
            }
        })
            .success(function (data) {
                comments.lock(false);
                $this.closest('div').css('opacity', '1');

                replyParent.find(comments.defaults.vote.vote_counter_selector).html(data.vote != 0 ? data.vote : "");
                comments.negativeVote(data.vote, replyParent);

                if (data.hasVoted == true) {
                    dataVote.attr('class', 'but selected');
                    otherVote.attr('class', 'but removeVote');
                } else {
                    otherVote.attr('class', 'but');
                    dataVote.attr('class', 'but');
                }
            })
            .fail(function (data) {
                comments.lock(false);
                $this.closest('div').css('opacity', '1');
                dataVote.attr('class', 'but selected');
            });
    },
    negativeVote: function (vote, replyParent) {
        if (replyParent && replyParent.length > 0) {
            if (vote < -2) {
                replyParent.addClass(comments.defaults.vote.negative_class);
            } else {
                replyParent.removeClass(comments.defaults.vote.negative_class);
            }
        }
    },
    findNegativeVotes: function () {
        var voteControls = $(comments.defaults.vote.vote_counter_selector);

        voteControls.each(function () {
            var voteElement = $(this);
            var voteText = voteElement.text();
            var vote = 0;
            if (voteText.length > 0) {
                vote = parseInt(voteText);
            }
            comments.negativeVote(vote, voteElement.parent().parent());
        });

    },
    reportComment: function (e) {
        var originalComment = $(e.target).parent().parent().parent().parent();
        var commentId = originalComment.attr('data-' + comments.defaults.comment.list_reply_attr);
        var isConfirmed = confirm('Are you sure you would like to report this comment as offensive and/or inappropriate?');
        if (isConfirmed) {
            $.ajax({
                type: 'POST',
                url: comments.defaults.comment.report_url,
                data: { commentId },
                dataType: 'json'
            }).complete(function () {
                $(e.target).parent().html('Reported').css({ 'font-size': '11px', 'line-height': '14px'});
            });
        }
    },
    admin: {
        breakCache: function (e) {
            var $this = $(e.target);
            var breakSelector = $(comments.defaults.admin.breakcache_selector);
            var filter = comments.getFilterData();
            $.ajax({
                type: 'POST',
                url: comments.defaults.admin.breakcache_url,
                data: filter,
                dataType: 'json',
                beforeSend: function () {
                    comments.lock(true);
                    $this.closest('li').css('opacity', '0.4');
                },
            }).done(function (data) {
                comments.lock(false);
                alert('cache refreshed');

            });
        },
        addLock: function (e) {
            var $this = $(e.target);
            var lockSelector = $(comments.defaults.admin.lock_selector);
            var locked = Boolean(parseInt(lockSelector.data("locked")));
            var filter = comments.getFilterData();
            $.ajax({
                type: 'POST',
                url: comments.defaults.admin.lock_topic_url + "?lockTopic=" + locked,
                data: filter,
                dataType: 'json',
                beforeSend: function () {
                    comments.lock(true);
                    $this.closest('li').css('opacity', '0.4');
                },
            }).done(function (data) {
                comments.lock(false);
                if (data.result > 0) {
                    $(comments.defaults.admin.lock_selector).text(locked ? "Lock" : "Unlock");
                    $(comments.defaults.admin.lock_selector).data('locked', (locked == 1 ? 0 : 1));
                    comments.loadComments(comments.getFilterData());
                }
            });
        },
        deleteTopic: function () {
            var filter = comments.getFilterData();
            $.ajax({
                type: 'POST',
                url: comments.defaults.admin.deleteTopic_url,
                data: filter,
                dataType: 'json',
                beforeSend: function () {
                    comments.lock(true);
                },
            }).done(function (data) {
                comments.lock(false);
                if (data && data.responseJSON && data.responseJSON.errorMessage && data.responseJSON.errorMessage.length > 0) {
                    alert(data.responseJSON.errorMessage);
                }
                if (data.result > 0) {
                    comments.loadComments(comments.getFilterData());
                }
            });
        },
        toggleDisableVoting: function () {
            var filter = comments.getFilterData();
            $.ajax({
                type: 'POST',
                url: comments.defaults.admin.disableVoting_url,
                data: filter,
                dataType: 'json',
                beforeSend: function () {
                    comments.lock(true);
                },
            }).done(function (data) {
                comments.lock(false);
                if (data && data.errorMessage && data.errorMessage.length > 0) {
                    alert(data.errorMessage);
                }
                if (data.result > 0) {
                    comments.loadComments(comments.getFilterData());
                }
            });
        },
        updateTopicEventId: function () {
            var eventId = $('#adminControls input[type=text]').val();
            if (!$.isNumeric(eventId) || Math.floor(eventId) != eventId) {
                alert("Invalid event Id");
                return
            }

            if (confirm("Are you sure to update this Event Id?")) {
                var filter = comments.getFilterData();
                console.log(filter);
                $.ajax({
                    type: 'POST',
                    url: comments.defaults.admin.update_event_url,
                    data: {
                        topicId: filter.topicId,
                        contentId: filter.contentId,
                        section: filter.section,
                        page: filter.page,
                        replyId: filter.replyId,
                        perPage: filter.perPage,
                        perFirstPage: filter.perFirstPage,
                        eventId: eventId
                    },
                    dataType: 'json',
                    beforeSend: function () {
                        comments.lock(true);
                    }
                })
                    .done(function (data) {
                        comments.lock(false);

                        if (data.status) {
                            alert("Successfully Updated");
                            comments.loadComments(comments.getFilterData(1));
                        }
                    })
            }
        },
        deleteComment: function (e) {
            var filter = comments.getFilterData();
            filter.replyId = $(e.target).parent().parent().parent().parent().attr('data-reply');
            $.ajax({
                type: 'POST',
                url: comments.defaults.admin.delete_comment_url,
                data: filter,
                dataType: 'json',
                beforeSend: function () {
                    comments.lock(true);
                    $(e.target).closest('li').css('opacity', '0.4');
                }
            })
                .done(function (data) {
                    comments.lock(false);
                    if (data.page > 0) {
                        $(e.target).closest('li').css('opacity', '1');
                        comments.loadComments(comments.getFilterData());
                    }
                });
        },
        deleteCommentAndNotifyUser: function (e) {
            var filter = comments.getFilterData();
            filter.replyId = $(e.target).parent().parent().parent().parent().attr('data-reply');
            $.ajax({
                type: 'POST',
                url: comments.defaults.admin.delete_notify_comment_url,
                data: filter,
                dataType: 'json',
                beforeSend: function () {
                    comments.lock(true);
                    $(e.target).closest('li').css('opacity', '0.4');
                }
            })
                .done(function (data) {
                    comments.lock(false);
                    if (data.page > 0) {
                        $(e.target).closest('li').css('opacity', '1');
                        comments.loadComments(comments.getFilterData());
                    }
                });
        },
        bulkVote: function (e) {
            var $this = $(e.target);
            var reply = $this.parent().parent().parent().parent();
            var replyId = reply.attr('data-' + comments.defaults.comment.list_reply_attr)
            var url = $this.attr(comments.defaults.admin.bulk_vote_direction) == "+" ? comments.defaults.admin.add_bulk_vote_url : comments.defaults.admin.remove_bulk_vote_url;

            var filter = comments.getFilterData();
            filter.replyId = replyId;
            $.ajax({
                type: 'POST',
                url: url + replyId,
                dataType: 'json',
                data: filter,
                beforeSend: function () {
                    comments.lock(true);
                }
            })
                .success(function (data) {
                    comments.lock(false);
                    reply.find(comments.defaults.vote.vote_counter_selector).html(data.vote != 0 ? data.vote : "");
                })
                .fail(function (data) {
                    comments.lock(false);
                });
        },
        hideComment: function (e) {
            var filter = comments.getFilterData();
            filter.replyId = $(e.target).parent().parent().parent().parent().attr('data-reply');
            $.ajax({
                type: 'POST',
                url: comments.defaults.admin.hide_comment_url,
                data: filter,
                dataType: 'json',
                beforeSend: function () {
                    comments.lock(true);
                    $(e.target).closest('li').css('opacity', '0.4');
                }
            })
            .done(function (data) {
                comments.lock(false);
                $(e.target).closest('li').css('opacity', '1');
                comments.loadComments(comments.getFilterData());
            });
        },
        getModeratorName: function (e) {
            var id = $(e.target).parent().parent().parent().parent().attr('data-reply');
            $.ajax({
                type: 'GET',
                url: comments.defaults.admin.get_moderator_name_url,
                data: { id },
                dataType: 'json'
            })
                .done(function (data) {
                    var element = $(e.target).parent();
                    $(e.target).remove();
                    element.text(data.result);
            });
        },
        showComment: function (e) {
            var filter = comments.getFilterData();
            filter.replyId = $(e.target).parent().parent().parent().parent().attr('data-reply');
            $.ajax({
                type: 'POST',
                url: comments.defaults.admin.show_comment_url,
                data: filter,
                dataType: 'json',
                beforeSend: function () {
                    comments.lock(true);
                    $(e.target).closest('li').css('opacity', '0.4');
                }
            })
            .done(function (data) {
                comments.lock(false);
                $(e.target).closest('li').css('opacity', '1');
                comments.loadComments(comments.getFilterData());
            });
        }
    }
}
;
