var Comments = new Object();

// комментируемая таблица
Comments.table = null;

// комментируемая запись в таблице
Comments.item_id = 0;

// Выбранный коммент (хэш в адресе)
Comments.selected=0;

// ID пользователя
Comments.user_id=0;

// Комментарий с MAX значением ID (последний)
Comments.last=0;
Comments.last_read=0;
Comments.unread=[];
Comments.cookie=[];

// функция получения комментариев
Comments.getComments = function (table, item_id)
{
    // определяем непрочитанные комментарии
    Comments.unread=[];
    $.getJSON('/execplugin/?plg=comments&plugFunc=getComments', {table:table, id:item_id}, function(data){
       Comments.last_read=parseInt(data.last_read);
       Comments.last=parseInt(data.last);
       var html=TrimPath.processDOMTemplate("commentsTpl", {comments:data['comments'], deletable:data['deletable'], children:false});
       $(".comments").html(html);
       // если есть выбранный коммент - прокрутимся к нему и выделим
       if(Comments.selected!=0) {
          $(".comments").find("a.comment_link[rel='"+Comments.selected+"']").closest("div").addClass('selected_comment');
          $.scrollTo($(".comments").find("a.comment_link[rel='"+Comments.selected+"']").closest("div"), 700, {offset:-100});
       }
       // определяем есть ли непрочитанные комментарии
       Comments.unreadCheck();
    });
}

// определяем, есть ли непрочитанные комментарии
Comments.unreadCheck = function() {
    if(Comments.unread.length>0) {
        $("#comments_unread").text(Comments.unread.length).show();
    }
}

// функция голосования за комментарий
Comments.vote = function (comment_id, vote, elem)
{
    $.getJSON('/execplugin/?plg=comments&plugFunc=vote', {id:comment_id, vote:vote}, function(response){
       switch (parseInt(response['code']))
       {
           case 1:
           var votes=(response['votes']>0)? '+'+response['votes']: response['votes'];
           $(elem).closest("span").find("a").find("i").text(votes);
           $(elem).closest("span").find("a[class!='new_window']").remove();
           break;

           case -1:
              $(elem).closest("span").append("<br>Ты уже голосовал");
              $(elem).closest("span").find("a[class!='new_window']").remove();
           break;

           case -2:
              $(elem).closest("span").append("<br>Ты не можешь голосовать");
              $(elem).closest("span").find("a[class!='new_window']").remove();
           break;

           case -3:
              $(elem).closest("span").append("<br>Это твой комментарий");
              $(elem).closest("span").find("a[class!='new_window']").remove();
           break;

           case -4:
              $(elem).closest("span").append("<br>Время голосования истекло");
              $(elem).closest("span").find("a[class!='new_window']").remove();
           break;
       }
       
    });
}

// функция отправления сообщения
Comments.send = function (message, parent)
{
    // показываем индикатор загрузки ajax
    $(".ajax-loader").show();
    $.ajax({
        'url': '/execplugin/?plg=comments&plugFunc=addComment',
        'dataType':'json',
        'type': "POST",
        'data': {message:message, parent:parent, id:Comments.item_id, table:Comments.table},
        'success': function (response)
        {
            if(parseInt(response)!=-1) {
                // перегрузим комментарии
                Comments.getComments(Comments.table, Comments.item_id);
                // сбрасываем форму
                document.getElementById("write_comment").reset();
                $("#write_comment").find(":submit").attr("disabled", '').show();
                $(".ajax-loader").hide();
                $("#write_comment").find("input[name='c_parent_id']").val(0);
            }
            else {
                alert('Вы не можете оставлять комментарии здесь.');
            }
        }
    });
}

// функция отправления отредактированного сообщения
Comments.edit = function (message, id, elem)
{
    // показываем индикатор загрузки ajax
    $.ajax({
        'url': '/execplugin/?plg=comments&plugFunc=editComment',
        'dataType':'json',
        'type': "POST",
        'data': {message:message, id:id},
        'success': function (response)
        {
            if(parseInt(response.code)!=-1) {
                // перегрузим комментарии
                $(elem).parent("p.text").html(response.message);
            }
            else {
                alert('Редактировать комментарий можно только в течении 2-ух минут с момента его написания.');
            }
        }
    });
}

// загруженные слайды ленты
Comments.loadedSlides = new Array();

// лента последних комментов
Comments.commentsHistory = function (slide, opts)
{
    $.getJSON('/execplugin/?plg=comments&plugFunc=get_comments_history', {slide:slide}, function(comments){
        if(comments.length>0)
        {
            var html=TrimPath.processDOMTemplate("last_comments_tpl", {comments:comments});
            Comments.loadedSlides.push(slide);
            opts.addSlide(html);
        }
    });
}

// удаление комментария
Comments.deleteComment= function (id, mode, elem)
{
    $.getJSON('/execplugin/?plg=comments&plugFunc=deleteComment', {id:id, action:mode}, function(resp){
    if(parseInt(resp)>0)
    {
        // перегрузим комментарии
        Comments.getComments(Comments.table, Comments.item_id);
        // обновим заметки на фото
        if($.fn.annotateImage && window.Photo && Photo.annotationObj)
        $.fn.annotateImage.ajaxLoad(Photo.annotationObj);
    }
    else
    {
        alert('Комментарий не может быть удалён.');
    }
    });
}
