$(function(){
    // Show the original version of a comment.
    $(document).on('click', 'a.comment-original', function(e) {
        e.preventDefault();

        var $this = $(this);
        var $toHide = $($this.attr('data-switch-from'));
        var $toShow = $($this.attr('data-switch-to'));

        $this.hide();
        $toHide.hide();
        $toShow.show();
    });

    // Show the localized version of a comment.
    $(document).on('click', 'a.comment-localize', function(e) {
        e.preventDefault();

        var $this = $(this);
        var url = $this.attr('href');
        var $target = $($this.attr('data-target'));

        var $toHide = $($this.attr('data-switch-from'));
        var $toShow = $($this.attr('data-switch-to'));

        if ($target.text().length > 0) {
            $this.hide();
            $toHide.hide();
            $toShow.show();
            return;
        }

        var $parent = $this.parent();
        var $loading = $('.loading', $parent);
        if ($loading.length == 0) {
            $loading = getLoading().addClass('loading-sm');
        }

        $this.hide();
        $parent.prepend($loading);

        $.ajax({
            url: url,
            success: function(data) {
                var text = data.localization.replace(/\n/g, '<br>');
                if (!data.ok) {
                    text = '<em class="text-muted">' + text + '</em>';
                }

                $target.html(text);
                $this.hide();
                $toHide.hide();
                $toShow.show();
            },
            complete: function() {
                $loading.remove();
            },
            error: function() {
                $this.show();
            },
        });
    });
});