var $rewardCounterTotal = $(".reward_counter");
var $rewardCounterUser = $(".reward-next");
var $rewardButton = $(".reward_button");

var $karmaWrap = $("#karma-wrap");

var $likesUserListModal = $('#likes_user_list');
var $repostUserListModal = $('#repost_user_list');
var $rewardUserListModal = $('#reward_user_list');

var $userListModal = $("#user_list_modal");

var rewardCounter = 0;

$("#sub_reg").click(function(e) {
    e.preventDefault();
    subRegAuthorID = "journal" in postData ? 'j' + postData.journal : postData.authorID;
    $("#registrationModal").modal("show");
});

var scr_position = $(window).scrollTop();

$(window).scroll(function () {
    var scroll = $(window).scrollTop();

    if (scroll > scr_position) $("#sub_reg").removeClass('shown');
    else $("#sub_reg").addClass('shown');

    scr_position = scroll;
});

iziToast.settings({
    class: 'toast',
    layout: 2,
    icon: '',
    pauseOnHover: true,
    maxWidth: 600,
    titleLineHeight: 35,
    messageLineHeight: 20
});

$rewardButton.click(function(e) {
    e.preventDefault();
    var $this = $(this);
    $.ajax({
        type: "POST",
        global: false,
        url: "/ajax/reward.php",
        data: ({
            type: "reward_user",
            author: postData.authorID,
            postID: postData.postID
        }),
        dataType: 'json',
        success: function(data) {
            iziToast.destroy();

            if(data.status == "ok") {
                if(data.userPostRewards == 0) $this.removeClass('btn-active').addClass('btn-grey');
                else if(data.userPostRewards == 1) $this.removeClass('btn-grey').addClass('btn-active');
                $rewardCounterTotal.text(data.totalPostRewards);

                var $likesBodyContainer = $this.parent().find('.liked-user-list__body');
                var $userLikeElement = $likesBodyContainer.find('a[data-like-user='+ postData.userID +']');

                if(data.userPostRewards == 0 && $userLikeElement.length) {
                    $likesBodyContainer.animate({'margin-left': '-45px'}, 200, function () {

                        $likesBodyContainer.children('a[data-like-user="' + postData.userID + '"]').remove();
                        $likesBodyContainer.css('margin-left', '0px');

                        //hide likes container
                        if (!$likesBodyContainer.children().length) {
                            $likesBodyContainer.parent().hide();
                        }

                    });
                }
                else if(data.userPostRewards == 1 && !$userLikeElement.length) {
                    var $element = $('<a />')
                        .append($('<img />')
                            .attr('src', '//cont.ws/uploads/users/' + postData.userID + '.jpg')
                        )
                        .attr('data-like-user', postData.userID)
                        .attr('title', '')
                        .attr('data-placement', 'top')
                        .attr('data-original-title', postData.username)
                        .attr('data-toggle', 'tooltip');

                    //prepend element
                    $element.prependTo($likesBodyContainer);

                    //shift body container
                    $likesBodyContainer.css('margin-left', '-45px');
                    $likesBodyContainer.animate({'margin-left': '0px'}, 200);
                }

                var caption = getNoun(data.totalUsersCount, 'Поддержал ', 'Поддержали ', 'Поддержали ');

                //caption
                caption += data.totalUsersCount;
                caption += getNoun(data.totalUsersCount, ' человек', ' человека', ' человек')

                //set caption
                $likesBodyContainer.parent().find('strong').text(caption);

                var label = data.totalPostRewards;

                label += getNoun(data.totalPostRewards, ' континентальный', ' континентальных', ' континентальных');
                label += getNoun(data.totalPostRewards, ' рубль', ' рубля', ' рублей')

                $likesBodyContainer.parent().find('a span').text(label);

                var userCounterText = data.userPostRewards == 0 ? 'Отмена' : '+' + (data.userPostRewards);
                $rewardCounterUser.text(userCounterText);

                rewardCounter = data.userPostRewards;
                $rewardCounterUser.fadeIn(200);
                setTimeout(function() {
                    var currentRewardsValue = data.userPostRewards;
                    if(rewardCounter == currentRewardsValue) $rewardCounterUser.fadeOut(200);
                }, 1200)
            }
            else if(data.status == "error") {
                if(!('title' in data)) data.title = 'Ошибка';
                var toastData = {
                    title: data.title,
                    message: data.message,

                };

                if('button' in data) {
                    toastData.buttons = [['<button>'+data.button.title+'</button>', function (instance, toast) {
                        window.location.href = data.button.link;
                    }, true]];
                }

                switch (data.toastType) {
                    case 'info':
                        iziToast.show(toastData);
                        break;
                    default:
                        iziToast.error(toastData);
                }
            }
        }
    });
});

var modalQueryOffsets = {
    like: 0,
    repost: 0
};

var currentModalOpen;

function getDataForModal(type) {
    var qData = {
        type: "get_modal_data",
        modal: type,
        author: postData.authorID,
        postID: postData.postID
    };

    if(type != 'reward') {
        qData.offset = modalQueryOffsets[type];
        modalQueryOffsets[type] += 40;
    }

    $.ajax({
        type: "POST",
        global: false,
        url: "/ajax/post.php",
        data: qData,
        dataType: 'json',
        success: function(data) {
            $userListModal.find("#"+ type +"_user_list").append(data.html);
        }
    });
}

$(".user-list-modal-button").click(function(e) {
    var $this = $(this);
    var modalType = $this.data('modal-type');

    currentModalOpen = modalType;

    var labelText;
    switch (currentModalOpen) {
        case 'reward':
            labelText = $rewardCounterTotal.eq(0).text() + ' континентальных рублей';
            break;

        case 'like':
            labelText = $karmaWrap.text() + ' кармы';
            break;
    }

    $userListModal.find(".modal-title").text($this.find("strong").text());
    $userListModal.find(".modal-header p").text(labelText);

    $userListModal.find(".aggregation-modal__users:not(#"+ modalType +"_user_list)").hide();

    var $dataContainer = $userListModal.find("#"+ modalType +"_user_list");
    $dataContainer.show();

    if(modalType === 'reward' && $dataContainer.children().length) $dataContainer.html('');

    getDataForModal(modalType);
});

$userListModal.scroll(function() {
    if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
        if(currentModalOpen != 'reward') getDataForModal(currentModalOpen);
    }
});

$('ul.post_meta_buttons_block').on('mouseenter', 'button', function (evt) {


    $(this).data('hovered', true);

    var popUp = $(this).parent().find('.liked-user-list');
    var arrow = $(this).parent().find('.liked-user-list__arrow');

    if (!popUp.find('.liked-user-list__body').children().length) return;
    clearTimeout(popUp.data('timeoutID') * 1);
    popUp.fadeIn(100);
    arrow.fadeIn(100);

});


$('ul.post_meta_buttons_block').on('mouseenter', '.liked-user-list', function (evt) {

    evt.stopPropagation();
    var arrow = $(this).parent().find('.liked-user-list__arrow');

    clearTimeout($(this).data('timeoutID'));
    $(this).fadeIn(100);
    arrow.fadeIn(100);

});

$('ul.post_meta_buttons_block').on('mouseleave', 'button', function (evt) {


    $(this).data('hovered', false);

    var popUp = $(this).parent().find('.liked-user-list');
    var arrow = $(this).parent().find('.liked-user-list__arrow');

    popUp.data('timeoutID', setTimeout(function () {
        popUp.fadeOut(100);
        arrow.fadeOut(100);
    }, 250));


});

$('ul.post_meta_buttons_block').on('mouseleave', '.liked-user-list', function (evt) {

    evt.stopPropagation();

    var self = $(this);
    var arrow = $(this).parent().find('.liked-user-list__arrow');

    self.data('timeoutID', setTimeout(function () {
        self.fadeOut(100);
        arrow.fadeOut(100);
    }, 250));

});


$(".likely__widget_bookmark").click(function(e) {
    e.preventDefault();

    var $this = $(this);
    var $bookmarksCount = $(".bookmarks_counter");
    var postID = $this.attr('data-post-id');
    var activeClass = 'likely__widget_bookmark--pushed';

    $.ajax({
        type: "POST",
        global: false,
        url: "/ajax.php",
        data: ({
            type: 27,
            post: postID
        }),
        dataType: "json",
        success: function(data) {
            if(data.status == "removed") $this.removeClass(activeClass);
            else $this.addClass(activeClass);

            if(data.count == 0) $bookmarksCount.hide();
            else $bookmarksCount.show();
            $bookmarksCount.html(data.count);
        }
    });
});


var upVoted = false;
$(".vote-up").click(function(event){
    event.preventDefault();

    var $this = $(this);
    var isPostBar = $this.hasClass('bar-button');

    if(!upVoted) {
        upVoted = true;
        $.ajax({
            type: "POST",
            global: false,
            url: "/ajax.php",
            data: ({
                type: 13,
                post: postData.postID
            }),
            dataType: "json",
            success: function(data) {
                iziToast.destroy();
                if(data.status == 'ok') {
                    $(".vote-up").removeClass('btn-grey').addClass('btn-active');

                    $('.karma-wrap').html(data.karma);

                    var $likesBodyContainer = $this.parent().find('.liked-user-list__body');
                    var $userLikeElement = $likesBodyContainer.find('a[data-like-user='+ postData.userID +']');

                    var $element = $('<a />')
                        .append($('<img />')
                            .attr('src', '//cont.ws/uploads/users/' + postData.userID + '.jpg')
                        )
                        .attr('data-like-user', postData.userID)
                        .attr('title', '')
                        .attr('data-placement', 'top')
                        .attr('data-original-title', postData.username)
                        .attr('data-toggle', 'tooltip');

                    //prepend element
                    $element.prependTo($likesBodyContainer);

                    //shift body container
                    $likesBodyContainer.css('margin-left', '-45px');
                    $likesBodyContainer.animate({'margin-left': '0px'}, 200);

                    var caption = getNoun(data.total, 'Оценил ', 'Оценили ', 'Оценили ');

                    //caption
                    caption += data.total;
                    caption += getNoun(data.total, ' человек', ' человека', ' человек')

                    //set caption
                    $likesBodyContainer.parent().find('strong').text(caption);

                    // set new karma value on popup
                    $likesBodyContainer.parent().find('span').text(data.karma + ' кармы');
                }
                else {
                    iziToast.error({
                        title: 'Ошибка',
                        message: data.message
                    });
                }
                upVoted = false;
            }
        });
    }

});

$(".repost-button").click(function(event) {
    
    var $this = $(this);

    $.ajax({
                type: "POST",
                global: false,
                url: "/ajax.php",
                data: ({
                    type: 'share post',
                    action: $(".repost-button").hasClass('btn-grey') ? 0 : 1,
                    postID: postData.postID
                }),
                success: function(data) {
                    
                    var $likesBodyContainer = $this.parent().find('.liked-user-list__body');
                    var $userLikeElement = $likesBodyContainer.find('a[data-like-user='+ postData.userID +']');

                    if(data == 1) {
                        
                        $(".repost-button").removeClass('btn-grey').addClass('btn-active');
                        
                        var count =  ($('.repost-wrap').text() * 1 || 0) + 1;
                        
                        $('.repost-wrap').text(count);

                        var $element = $('<a />')
                            .append($('<img />')
                                .attr('src', '//cont.ws/uploads/users/' + postData.userID + '.jpg')
                            )
                            .attr('data-like-user', postData.userID)
                            .attr('title', '')
                            .attr('data-placement', 'top')
                            .attr('data-original-title', postData.username)
                            .attr('data-toggle', 'tooltip');

                            //prepend element
                             $element.prependTo($likesBodyContainer);

                             //shift body container
                             $likesBodyContainer.css('margin-left', '-45px');
                             $likesBodyContainer.animate({'margin-left': '0px'}, 200);

                            var caption = getNoun(count, 'Поделился ', 'Поделились ', 'Поделились ');

                            //caption
                            caption += count;
                            caption += getNoun(count, ' человек', ' человека', ' человек')

                            //set caption
                            $likesBodyContainer.parent().find('strong').text(caption);                       
                        

                    } else {
                        
                        var count = Math.max(($('.repost-wrap').text() * 1 || 0) - 1,0);
                        $(".repost-button").removeClass('btn-active').addClass('btn-grey');
                        $('.repost-wrap').text(count);
                        
                        $likesBodyContainer.children('a[data-like-user="' + postData.userID + '"]').remove();
                        var caption = getNoun(count, 'Поделился ', 'Поделились ', 'Поделились ');

                            //caption
                            caption += count;
                            caption += getNoun(count, ' человек', ' человека', ' человек')

                            //set caption
                            $likesBodyContainer.parent().find('strong').text(caption);
                       
                        
                    }
                }
            });
});


$('.visits-stats').on('mouseenter', function (evt) {


    $(this).data('hovered', true);

    var popUp = $(this).find('.visits-stats-popup');
    var arrow = $(this).find('.visits-arrow');

    clearTimeout(popUp.data('timeoutID') * 1);
    popUp.fadeIn(100);
    arrow.fadeIn(100);

});

$('.visits-stats').on('mouseleave', function (evt) {


    $(this).data('hovered', false);

    var popUp = $(this).find('.visits-stats-popup');
    var arrow = $(this).find('.visits-arrow');

    popUp.data('timeoutID', setTimeout(function () {
        popUp.fadeOut(100);
        arrow.fadeOut(100);
    }, 250));

});
