372 lines
19 KiB
JavaScript
372 lines
19 KiB
JavaScript
/* ====================================================================
|
||
ОБЕРТКА ДЛЯ ОЖИДАНИЯ JQUERY
|
||
==================================================================== */
|
||
(function waitForJQuery() {
|
||
if (typeof jQuery === 'undefined') {
|
||
// jQuery еще не загружен. Ждем 10 мс и проверяем снова.
|
||
setTimeout(waitForJQuery, 10);
|
||
} else {
|
||
// JQuery загружен, можно запускать основной код.
|
||
|
||
(function($){
|
||
|
||
// ====================================================================
|
||
// КОРРЕКЦИЯ: ПРИНУДИТЕЛЬНАЯ ФИКСАЦИЯ HTTPS (если требуется)
|
||
// ====================================================================
|
||
if (typeof aveabspath !== 'undefined') {
|
||
// ПРЕДУПРЕЖДЕНИЕ: Если aveabspath должен быть динамическим,
|
||
// удалите эту строку.
|
||
// aveabspath = 'https://bag.local/';
|
||
}
|
||
// ====================================================================
|
||
|
||
/* Limit symbols */
|
||
(function($){
|
||
$.fn.extend({
|
||
limit: function(limit, element){
|
||
var interval, f;
|
||
var self = $(this);
|
||
|
||
function substring(){
|
||
var val = $(self).val();
|
||
var length = val.length;
|
||
|
||
if(length > limit){
|
||
$(self).val($(self).val().substring(0,limit));
|
||
length = limit;
|
||
}
|
||
|
||
if(typeof element !== 'undefined'){
|
||
if($(element).html() != limit - length){
|
||
$(element).html((limit - length <= 0) ? '0' : limit - length);
|
||
}
|
||
}
|
||
}
|
||
|
||
$(this).focus(function(){
|
||
interval = window.setInterval(substring, 100);
|
||
});
|
||
|
||
$(this).blur(function(){
|
||
clearInterval(interval);
|
||
substring();
|
||
});
|
||
|
||
substring();
|
||
}
|
||
})
|
||
})(jQuery);
|
||
|
||
function getCaptha(){
|
||
var now = new Date();
|
||
$('#captcha img').attr('src', aveabspath + 'inc/captcha.php?cd=' + now.getTime());
|
||
}
|
||
|
||
function cAction(obj, action){
|
||
var cid;
|
||
|
||
// --- Логика для действий с документом (open/close) ---
|
||
if (action === 'open' || action === 'close') {
|
||
cid = DOC_ID;
|
||
} else {
|
||
// 1. Пытаемся найти ссылку и взять ID из атрибута rel
|
||
var $link = $(obj).closest('a.mod_comment_answer');
|
||
cid = $link.attr('rel');
|
||
|
||
// 2. Если rel не найден, берем ID из родительского блока
|
||
if (typeof cid === 'undefined' || cid === false || cid === '') {
|
||
cid = $(obj).parents('.mod_comment_box').attr('id');
|
||
}
|
||
}
|
||
|
||
if (typeof cid === 'undefined' || cid === false || cid === '') {
|
||
console.error("Comment ID not found for action: " + action);
|
||
return;
|
||
}
|
||
|
||
if (action === 'answer'){
|
||
$('#parent_id').val(cid);
|
||
// Перемещаем форму и показываем ее
|
||
$('#mod_comment_new').insertBefore('#end' + cid).show();
|
||
return;
|
||
}
|
||
|
||
// Действия администратора
|
||
if (UGROUP == 1){
|
||
$.get(aveabspath + 'index.php', {
|
||
module: 'comment',
|
||
action: action,
|
||
docid: DOC_ID,
|
||
Id: cid
|
||
}, function(){
|
||
if (action === 'delete'){
|
||
// Удаляем блок комментария
|
||
$(obj).parents('.mod_comment_comment').eq(0).remove();
|
||
}
|
||
|
||
if (action === 'open'){
|
||
// 1. Меняем ID и текст
|
||
var $openButton = $('#mod_comment_open');
|
||
$openButton.attr('id', 'mod_comment_close').html('<i class="bi bi-unlock-fill me-1"></i> ' + COMMENT_SITE_CLOSE);
|
||
// 2. МЕНЯЕМ КЛАССЫ СТИЛЕЙ
|
||
$openButton.removeClass('btn-outline-success').addClass('btn-outline-danger');
|
||
}
|
||
|
||
if (action === 'close'){
|
||
// 1. Меняем ID и текст
|
||
var $closeButton = $('#mod_comment_close');
|
||
$closeButton.attr('id', 'mod_comment_open').html('<i class="bi bi-lock-fill me-1"></i> ' + COMMENT_SITE_OPEN);
|
||
// 2. МЕНЯЕМ КЛАССЫ СТИЛЕЙ
|
||
$closeButton.removeClass('btn-outline-danger').addClass('btn-outline-success');
|
||
}
|
||
|
||
// Динамическая смена иконки замка для отдельного комментария
|
||
if (action === 'unlock'){
|
||
$(obj).removeClass('mod_comment_unlock text-success')
|
||
.addClass('mod_comment_lock text-dark')
|
||
.attr('title', COMMENT_LOCK_LINK)
|
||
.find('i')
|
||
.removeClass('bi-unlock-fill').addClass('bi-lock-fill');
|
||
}
|
||
if (action === 'lock'){
|
||
$(obj).removeClass('mod_comment_lock text-dark')
|
||
.addClass('mod_comment_unlock text-success')
|
||
.attr('title', COMMENT_UNLOCK_LINK)
|
||
.find('i')
|
||
.removeClass('bi-lock-fill').addClass('bi-unlock-fill');
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
function validate(formData, jqForm, options){
|
||
$('.alert').remove();
|
||
var form = jqForm ? jqForm[0] : $('#mod_comment_new form')[0];
|
||
|
||
// Проверка имени
|
||
if (form.comment_author_name && !form.comment_author_name.value){
|
||
alert(COMMENT_ERROR_AUTHOR);
|
||
$(form.comment_author_name).focus();
|
||
return false;
|
||
}
|
||
|
||
// Проверка email
|
||
if (form.comment_author_email && !form.comment_author_email.value){
|
||
alert(COMMENT_ERROR_EMAIL);
|
||
$(form.comment_author_email).focus();
|
||
return false;
|
||
}
|
||
|
||
// Проверка текста
|
||
if (!form.comment_text || !form.comment_text.value){
|
||
alert(COMMENT_ERROR_TEXT);
|
||
if (form.comment_text) $(form.comment_text).focus();
|
||
return false;
|
||
}
|
||
|
||
// Проверка капчи (если требуется)
|
||
if (IS_IM && form.securecode && !form.securecode.value){
|
||
alert(COMMENT_ERROR_CAPTCHA);
|
||
$(form.securecode).focus();
|
||
return false;
|
||
}
|
||
|
||
return true;
|
||
}
|
||
|
||
function setClickable(){
|
||
// Отвязываем предыдущие обработчики, чтобы избежать множественных вызовов
|
||
$('.editable_text').off('click');
|
||
|
||
$('.editable_text').click(function(){
|
||
var $this = $(this);
|
||
var cid = $this.parents('.mod_comment_box').attr('id');
|
||
var revert = $this.html();
|
||
|
||
var textarea = '<p><textarea rows="7" id="ta_' + cid + '" class="editable form-control">' + revert + '</textarea></p>';
|
||
var charsLeft = '<p>' + COMMENT_CHARS_LEFT + ' <span class="charsLeft badge bg-secondary" id="charsLeft_' + cid + '"></span></p>';
|
||
var buttonSave = '<button type="button" class="btn btn-primary saveButton">' + COMMENT_BUTTON_EDIT + '</button> ';
|
||
var buttonReset = '<button type="button" class="btn btn-secondary cancelButton">' + COMMENT_BUTTON_CANCEL + '</button>';
|
||
|
||
$this.after(
|
||
'<div class="box"><div class="block" id="forms"><fieldset><legend class="h6">' + COMMENT_EDIT_TITLE
|
||
+ '</legend>' + textarea + charsLeft + buttonSave + buttonReset + '</fieldset></div></div>'
|
||
).remove();
|
||
|
||
$('.saveButton').click(function(){saveChanges(this, false, cid);});
|
||
$('.cancelButton').click(function(){saveChanges(this, revert, cid);});
|
||
|
||
$('#ta_' + cid).limit(MAX_CHARS, '#charsLeft_' + cid);
|
||
})
|
||
.attr('title', COMMENT_EDIT_LINK)
|
||
.mouseover(function(){$(this).addClass('editable');})
|
||
.mouseout(function(){$(this).removeClass('editable');});
|
||
|
||
// Лимит символов для новой формы
|
||
$('#in_message').limit(MAX_CHARS, '#charsLeft_new');
|
||
}
|
||
|
||
function saveChanges(obj, cancel, cid){
|
||
var $box = $(obj).parents('.box');
|
||
|
||
if (!cancel){
|
||
var t = $box.find('#ta_' + cid).val();
|
||
|
||
$.ajax({
|
||
url: aveabspath + 'index.php?ajax=1',
|
||
type: 'POST',
|
||
data: {
|
||
module: 'comment',
|
||
action: 'edit',
|
||
Id: cid,
|
||
text: t
|
||
},
|
||
success: function(txt){
|
||
$box.after('<div class="mod_comment_text editable_text">' + txt + '</div>').remove();
|
||
var now = new Date();
|
||
var date = now.toLocaleString();
|
||
$('#' + cid).find('.mod_comment_changed').html(' (' + COMMENT_TEXT_CHANGED + ' ' + date + ')');
|
||
setClickable();
|
||
},
|
||
error: function(xhr, status, error) {
|
||
console.error("AJAX Error (Edit):", status, error);
|
||
alert("Ошибка при редактировании комментария.");
|
||
}
|
||
});
|
||
}
|
||
else {
|
||
$box.after('<div class="mod_comment_text editable_text">' + cancel + '</div>').remove();
|
||
setClickable();
|
||
}
|
||
}
|
||
|
||
function displayNewComment(data){
|
||
if (data === 'wrong_securecode'){
|
||
$('#captcha').after('<div class="alert alert-danger">'+COMMENT_WRONG_CODE+'</div>');
|
||
$('#securecode').focus();
|
||
}
|
||
else {
|
||
$('#end' + $('#parent_id').val()).before(data);
|
||
$('#parent_id').val('');
|
||
$('#mod_comment_new form')[0].reset();
|
||
// Перемещаем форму обратно в конец
|
||
$('#mod_comment_new').insertAfter('#end');
|
||
setClickable();
|
||
}
|
||
getCaptha();
|
||
}
|
||
|
||
$(document).ready(function(){
|
||
|
||
setClickable();
|
||
|
||
// Смена капчи
|
||
$(document).on('click', '#captcha img', function(){getCaptha();});
|
||
|
||
// Ответ на комментарий
|
||
$(document).on('click', '.mod_comment_answer', function(e){
|
||
e.preventDefault();
|
||
cAction(this, 'answer');
|
||
});
|
||
|
||
// Редактирование (для администратора/автора)
|
||
$(document).on('click', '.mod_comment_edit', function(e){
|
||
e.preventDefault();
|
||
var cid = $(this).parents('.mod_comment_box').attr('id');
|
||
var commentTextBlock = $('#' + cid).find('.mod_comment_text');
|
||
var revert = commentTextBlock.html();
|
||
|
||
var textarea = '<p><textarea rows="7" id="ta_' + cid + '" class="editable form-control">' + revert + '</textarea></p>';
|
||
var charsLeft = '<p>' + COMMENT_CHARS_LEFT + ' <span class="charsLeft badge bg-secondary" id="charsLeft_' + cid + '"></span></p>';
|
||
var buttonSave = '<button type="button" class="btn btn-primary saveButton">' + COMMENT_BUTTON_EDIT + '</button> ';
|
||
var buttonReset = '<button type="button" class="btn btn-secondary cancelButton">' + COMMENT_BUTTON_CANCEL + '</button>';
|
||
|
||
commentTextBlock.after(
|
||
'<div class="box"><div class="block" id="forms"><fieldset><legend class="h6">' + COMMENT_EDIT_TITLE
|
||
+ '</legend>' + textarea + charsLeft + buttonSave + buttonReset + '</fieldset></div></div>'
|
||
).remove();
|
||
|
||
$('.saveButton').click(function(){saveChanges(this, false, cid);});
|
||
$('.cancelButton').click(function(){saveChanges(this, revert, cid);});
|
||
$('#ta_' + cid).limit(MAX_CHARS, '#charsLeft_' + cid);
|
||
});
|
||
|
||
if (UGROUP == 1) {
|
||
// Удаление (с использованием Bootstrap Modal)
|
||
$(document).on('click', '.mod_comment_delete', function(e){
|
||
e.preventDefault();
|
||
var $deleteButton = $(this);
|
||
var $modal = $('#deleteCommentModal');
|
||
|
||
// Привязываем действие к кнопке подтверждения в модальном окне
|
||
$('#confirmDeleteButton').off('click').on('click', function() {
|
||
cAction($deleteButton[0], 'delete');
|
||
// Закрываем модальное окно (совместимость с BS5)
|
||
var modalInstance = bootstrap.Modal.getInstance($modal[0]) || new bootstrap.Modal($modal[0]);
|
||
modalInstance.hide();
|
||
});
|
||
|
||
// Открываем модальное окно (совместимость с BS5)
|
||
var modal = new bootstrap.Modal($modal[0]);
|
||
modal.show();
|
||
});
|
||
|
||
// Блокировка/разблокировка
|
||
$(document).on('click', '.mod_comment_lock', function(e){e.preventDefault(); cAction(this, 'lock');});
|
||
$(document).on('click', '.mod_comment_unlock', function(e){e.preventDefault(); cAction(this, 'unlock');});
|
||
|
||
// Открыть/Закрыть комментарии для документа
|
||
$(document).on('click', '#mod_comment_open', function(e){e.preventDefault(); cAction(this, 'open');});
|
||
$(document).on('click', '#mod_comment_close', function(e){e.preventDefault(); cAction(this, 'close');});
|
||
}
|
||
|
||
// Отправка формы (AJAX)
|
||
$('#mod_comment_new form').on('submit', function(e){
|
||
e.preventDefault();
|
||
|
||
var form = $(this);
|
||
if (!validate(null, form, null)) {
|
||
return false;
|
||
}
|
||
|
||
var submitButton = form.find('input[type="submit"], button[type="submit"]').first();
|
||
var originalButtonText = submitButton.text();
|
||
if (!originalButtonText) originalButtonText = submitButton.val();
|
||
|
||
var formData = form.serialize();
|
||
|
||
$.ajax({
|
||
url: aveabspath + 'index.php?ajax=1',
|
||
type: 'POST',
|
||
data: formData,
|
||
dataType: 'html',
|
||
|
||
beforeSend: function() {
|
||
submitButton.prop('disabled', true).text('Отправка...');
|
||
},
|
||
|
||
success: function(data) {
|
||
displayNewComment(data);
|
||
submitButton.prop('disabled', false).text(originalButtonText);
|
||
},
|
||
timeout: 3000,
|
||
error: function(xhr, status, error) {
|
||
console.error("AJAX Error (Creation):", status, error);
|
||
alert("Ошибка при отправке комментария.");
|
||
submitButton.prop('disabled', false).text(originalButtonText);
|
||
}
|
||
});
|
||
return false;
|
||
});
|
||
|
||
// Сброс формы
|
||
$('#buttonReset').click(function(){
|
||
$('#parent_id').val('');
|
||
$('#mod_comment_new form')[0].reset();
|
||
$('#mod_comment_new').insertAfter('#end');
|
||
});
|
||
});
|
||
|
||
})(jQuery);
|
||
}
|
||
})(); |