/* ====================================================================
ОБЕРТКА ДЛЯ ОЖИДАНИЯ JQUERY
==================================================================== */
(function waitForJQuery() {
if (typeof jQuery === 'undefined') {
setTimeout(waitForJQuery, 10);
} else {
(function($) {
if (typeof aveabspath === 'undefined') {
window.aveabspath = '/';
}
/* --- ТАЙМЕРЫ --- */
function initCommentTimers() {
$('.timer-count:not(.timer-running)').each(function() {
var $timer = $(this);
$timer.addClass('timer-running');
var timeLeft = parseInt($timer.attr('data-left'));
var cid = $timer.attr('id').replace('timer_', '');
var countdown = setInterval(function() {
timeLeft--;
if (timeLeft <= 0) {
clearInterval(countdown);
$('#controls_' + cid).fadeOut(300);
$('#timer_container_' + cid).html('Время на правку истекло');
return;
}
var minutes = Math.floor(timeLeft / 60);
var seconds = timeLeft % 60;
$timer.text(minutes + ':' + (seconds < 10 ? '0' : '') + seconds);
$timer.attr('data-left', timeLeft);
}, 1000);
$timer.data('interval-id', countdown);
});
}
/* Limit Plugin */
$.fn.extend({
limit: function(limit, element) {
return this.each(function() {
var self = $(this);
function substring() {
var val = self.val();
if (val.length > limit) self.val(val.substring(0, limit));
if (typeof element !== 'undefined') {
var remaining = limit - self.val().length;
$(element).html(remaining < 0 ? '0' : remaining);
}
}
self.on('focus keyup paste', substring);
substring();
});
}
});
function getCaptha() {
var now = new Date();
$('#captcha img').attr('src', aveabspath + 'inc/captcha.php?cd=' + now.getTime());
}
function validate(form) {
var checks = [
{ field: form.comment_author_name, msg: "Введите имя" },
{ field: form.comment_author_email, msg: "Введите Email" },
{ field: form.comment_text, msg: "Введите текст" }
];
for (var i = 0; i < checks.length; i++) {
if (checks[i].field && !checks[i].field.value.trim()) {
alert(checks[i].msg);
$(checks[i].field).focus();
return false;
}
}
return true;
}
/* --- ДЕЙСТВИЯ (DELETE, LOCK, OPEN/CLOSE, VOTE) --- */
function cAction(obj, action) {
var $btn = $(obj);
var cid = $btn.data('id');
if (!cid && action !== 'open' && action !== 'close') return;
$.get(aveabspath + 'index.php', {
module: 'comment',
action: action,
docid: typeof DOC_ID !== 'undefined' ? DOC_ID : '',
Id: cid ? cid : ''
}, function() {
if (action === 'close') {
$btn.attr('id', 'mod_comment_open')
.removeClass('btn-outline-danger').addClass('btn-outline-success')
.html(' ' + COMMENT_SITE_OPEN);
$('#mod_comment_new').fadeOut(300);
}
else if (action === 'open') {
$btn.attr('id', 'mod_comment_close')
.removeClass('btn-outline-success').addClass('btn-outline-danger')
.html(' ' + COMMENT_SITE_CLOSE);
$('#mod_comment_new').fadeIn(300);
}
if (action === 'delete') {
var $commentBlock = $btn.closest('.mod_comment_comment');
$commentBlock.fadeOut(300, function() { $(this).remove(); });
}
if (action === 'unlock' || action === 'lock') {
var isLock = (action === 'lock');
$btn.toggleClass('mod_comment_lock mod_comment_unlock text-dark text-success')
.attr('title', isLock ? 'Разблокировать' : 'Заблокировать')
.find('i').toggleClass('bi-lock-fill bi-unlock-fill');
}
});
}
/* --- ИНИЦИАЛИЗАЦИЯ --- */
$(document).ready(function() {
initCommentTimers();
var $doc = $(document);
// --- ЛОГИКА ПРЕДПРОСМОТРА ИЗОБРАЖЕНИЯ (НОВАЯ ФОРМА) ---
$doc.on('change', '#comment_image', function() {
var input = this;
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#image_preview_img').attr('src', e.target.result);
$('#image_preview_wrapper').removeClass('d-none');
}
reader.readAsDataURL(input.files[0]);
}
});
$doc.on('click', '#remove_image_btn', function() {
$('#comment_image').val('');
$('#image_preview_wrapper').addClass('d-none');
$('#image_preview_img').attr('src', '#');
});
// --- ЛОГИКА ВЫБОРА РЕЙТИНГА В ФОРМЕ ---
$doc.on('mouseenter', '.star-choice', function() {
var val = $(this).data('value');
$(this).parent().find('.star-choice').each(function() {
if ($(this).data('value') <= val) {
$(this).removeClass('bi-star').addClass('bi-star-fill');
} else {
$(this).removeClass('bi-star-fill').addClass('bi-star');
}
});
});
$doc.on('mouseleave', '.rating-edit-block', function() {
var cid = $(this).find('input[type="hidden"]').attr('id').replace('rating_input_', '');
var currentRating = parseInt($('#rating_input_' + cid).val()) || 0;
$(this).find('.star-choice').each(function() {
if ($(this).data('value') <= currentRating) {
$(this).removeClass('bi-star').addClass('bi-star-fill');
} else {
$(this).removeClass('bi-star-fill').addClass('bi-star');
}
});
});
$doc.on('click', '.star-choice', function() {
var val = $(this).data('value');
var ratingInput = $(this).closest('.rating-edit-block').find('input[type="hidden"]');
if (ratingInput.length) {
ratingInput.val(val);
} else {
$('#comment_user_rating').val(val);
}
$(this).prevAll().addBack().removeClass('bi-star').addClass('bi-star-fill');
$(this).nextAll().removeClass('bi-star-fill').addClass('bi-star');
});
$doc.on('click', '#buttonReset', function() {
$('#comment_user_rating').val(0);
$('#user_rating_stars .star-choice').removeClass('bi-star-fill').addClass('bi-star');
$('#image_preview_wrapper').addClass('d-none');
});
$doc.on('click', '#reset_stars', function(e) {
e.preventDefault();
$('#comment_user_rating').val(0);
$('#user_rating_stars .star-choice').removeClass('bi-star-fill').addClass('bi-star');
});
$doc.on('click', '.reset-edit-stars', function(e) {
e.preventDefault();
var cid = $(this).data('id');
$('#rating_input_' + cid).val(0);
$('#user_rating_stars_' + cid + ' .star-choice').removeClass('bi-star-fill').addClass('bi-star');
});
// --- ЛОГИКА ГОЛОСОВАНИЯ (РЕЙТИНГ УЖЕ ОПУБЛИКОВАННЫХ) ---
$doc.on('mouseenter', '.star-item', function() {
var $parent = $(this).parent();
if ($parent.hasClass('comment-like')) {
$(this).css('transform', 'scale(1.2)');
}
else {
$(this).prevAll().addBack().removeClass('bi-star').addClass('bi-star-fill');
$(this).nextAll().removeClass('bi-star-fill').addClass('bi-star');
}
});
$doc.on('mouseleave', '.star-item', function() {
var $parent = $(this).parent();
if ($parent.hasClass('comment-like')) { $(this).css('transform', 'scale(1)'); }
});
$doc.on('click', '.star-item', function() {
var $container = $(this).closest('.comment-rating-container');
var commentId = $container.data('id');
var voteValue = $(this).data('value');
$.ajax({
url: 'index.php?module=comment&action=vote&ajax=1',
type: 'POST',
data: { comment_id: commentId, vote: voteValue, ajax: 1 },
success: function(response) {
var res = response.toString().trim();
if (res.indexOf('success') !== -1) {
$container.html('Спасибо!');
setTimeout(function(){ location.reload(); }, 1000);
} else if (res.indexOf('already_voted') !== -1) {
alert('Вы уже голосовали за этот комментарий.');
} else if (res.indexOf('own_comment') !== -1) {
alert('Нельзя голосовать за свой собственный комментарий.');
} else if (res.indexOf('forbidden_anon') !== -1) {
alert('Голосование доступно только зарегистрированным пользователям.');
} else {
alert('Ошибка при обработке голоса сервером.');
}
},
error: function(xhr) { alert('Ошибка связи с сервером. Статус: ' + xhr.status); }
});
});
$doc.on('click', '#mod_comment_close', function(e) { e.preventDefault(); cAction(this, 'close'); });
$doc.on('click', '#mod_comment_open', function(e) { e.preventDefault(); cAction(this, 'open'); });
// КНОПКА ОТВЕТА
$doc.off('click', '.mod_comment_answer').on('click', '.mod_comment_answer', function(e) {
e.preventDefault();
var cid = $(this).data('id');
var $form = $('#mod_comment_new');
$form.insertAfter('#comment_' + cid).show();
$('#parent_id').val(cid);
$('html, body').animate({ scrollTop: $form.offset().top - 150 }, 500);
$('#in_message').focus();
});
// Удаление
$doc.off('click', '.mod_comment_delete').on('click', '.mod_comment_delete', function(e) {
e.preventDefault();
if (confirm('Удалить этот комментарий?')) cAction(this, 'delete');
});
// Блокировка
$doc.off('click', '.mod_comment_lock, .mod_comment_unlock').on('click', '.mod_comment_lock, .mod_comment_unlock', function(e) {
e.preventDefault();
cAction(this, $(this).hasClass('mod_comment_lock') ? 'lock' : 'unlock');
});
// --- РЕДАКТИРОВАНИЕ (С ПРЕДПРОСМОТРОМ ТЕКУЩЕГО ФОТО) ---
$doc.off('click', '.mod_comment_edit').on('click', '.mod_comment_edit', function(e) {
e.preventDefault();
var cid = $(this).data('id');
var $wrapper = $('#comment_wrapper_' + cid);
var $textBlock = $wrapper.find('.mod_comment_text').first();
if ($wrapper.find('.edit-form-container').length > 0) return;
var isMyOwn = $wrapper.attr('data-is-own') == '1';
var currentRating = parseInt($wrapper.attr('data-user-rating')) || 0;
$('.edit-form-container').remove();
$('.mod_comment_text').show();
var cleanText = $textBlock.html().replace(/
/mg, "\n").trim();
var currentImg = $wrapper.find('.mod_comment_attached_image img').first().attr('src');
var starsEditBlock = '';
if (typeof SHOW_USER_RATING !== 'undefined' && SHOW_USER_RATING == '1' && isMyOwn) {
if (typeof UGROUP !== 'undefined' && (UGROUP != '2' || RATING_ANON_SET == '1')) {
var starsHtml = '';
for(var i=1; i<=5; i++) {
var starClass = (i <= currentRating) ? 'bi-star-fill' : 'bi-star';
starsHtml += ``;
}
starsEditBlock = `