Files
comment/js/comment.js
2025-12-15 07:48:07 +05:00

297 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* ====================================================================
ОБЕРТКА ДЛЯ ОЖИДАНИЯ JQUERY
==================================================================== */
(function waitForJQuery() {
if (typeof jQuery === 'undefined') {
// jQuery еще не загружен. Ждем 10 мс и проверяем снова.
setTimeout(waitForJQuery, 10);
} else {
// JQuery загружен, можно запускать основной код.
(function($){
// ====================================================================
// КОРРЕКЦИЯ: ПРИНУДИТЕЛЬНАЯ ФИКСАЦИЯ HTTPS
// ====================================================================
if (typeof aveabspath !== 'undefined') {
aveabspath = 'https://bag.local/';
}
// ====================================================================
/*Limit symbols*/
(function($){$.fn.extend({limit:function(limit,element){var interval,f;var self=$(this);$(this).focus(function(){interval=window.setInterval(substring,100)});$(this).blur(function(){clearInterval(interval);substring()});substringFunction="function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";if(typeof element!='undefined')substringFunction+="if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}";substringFunction+="}";eval(substringFunction);substring()}})})(jQuery);
function getCaptha(){
now = new Date();
$('#captcha img').attr('src', aveabspath+'inc/captcha.php?cd=' + now);
};
// ИСПРАВЛЕННАЯ ФУНКЦИЯ cAction
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);
// --- ИСПРАВЛЕНИЕ: Добавлено .show() для отображения формы после перемещения ---
$('#mod_comment_new').insertBefore('#end'+cid).show();
return;
}
// ... (остальной код для admin actions: delete, lock, open/close)
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'){
$('#mod_comment_open').attr('id', 'mod_comment_close').html(COMMENT_SITE_CLOSE);
}
if (action=='close'){
$('#mod_comment_close').attr('id', 'mod_comment_open').html(COMMENT_SITE_OPEN);
}
// ====================================================================
// ИСПРАВЛЕНИЕ: ДИНАМИЧЕСКАЯ СМЕНА ИКОНКИ ЗАМКА (Font Awesome)
// ====================================================================
if (action=='unlock'){
// Меняем классы: mod_comment_unlock (открыт) -> mod_comment_lock (закрыт)
// Меняем цвет: text-success (зеленый) -> text-dark (темный)
$(obj).removeClass('mod_comment_unlock text-success')
.addClass('mod_comment_lock text-dark')
.attr('title',COMMENT_LOCK_LINK)
.find('i.fa') // Ищем иконку FA
.removeClass('fa-unlock').addClass('fa-lock'); // Меняем иконку
}
if (action=='lock'){
// Меняем классы: mod_comment_lock (закрыт) -> mod_comment_unlock (открыт)
// Меняем цвет: text-dark (темный) -> text-success (зеленый)
$(obj).removeClass('mod_comment_lock text-dark')
.addClass('mod_comment_unlock text-success')
.attr('title',COMMENT_UNLOCK_LINK)
.find('i.fa') // Ищем иконку FA
.removeClass('fa-lock').addClass('fa-unlock'); // Меняем иконку
}
// ====================================================================
});
}
};
// ИСПРАВЛЕННАЯ ФУНКЦИЯ VALIDATE: Устойчива к отсутствию полей
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;
}
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').click(function(){
var cid = $(this).parents('.mod_comment_box').attr('id');
var revert = $(this).html();
var textarea = '<p><textarea rows="7" id="ta_'+cid+'" class="editable">'+revert+'</textarea></p>';
var charsLeft = '<p>'+COMMENT_CHARS_LEFT+' <span class="charsLeft" id="charsLeft_'+cid+'"></span></p>';
var buttonSave = '<input type="button" value="'+COMMENT_BUTTON_EDIT+'" class="button saveButton" /> ';
var buttonReset = '<input type="button" value="'+COMMENT_BUTTON_CANCEL+'" class="button cancelButton" />';
$(this).after('<div class="box"><div class="block" id="forms"><fieldset><legend>'+COMMENT_EDIT_TITLE
+'</legend>'+textarea+buttonSave+buttonReset+charsLeft+'</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');
};
// ИСПРАВЛЕННАЯ ФУНКЦИЯ saveChanges
function saveChanges(obj,cancel,cid){
if (!cancel){
var t = $(obj).parent().children().children().val();
$.ajax({
url: aveabspath+'index.php?ajax=1',
type: 'POST',
data: {
module: 'comment',
action: 'edit',
Id: cid,
text: t
},
success: function(txt){
$(obj).parent().parent().parent().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 {
$(obj).parent().parent().parent().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-error">'+COMMENT_WRONG_CODE+'</div>');
$('#securecode').focus();
}
else {
$('#end'+$('#parent_id').val()).before(data);
$('#parent_id').val('');
$('#mod_comment_new form')[0].reset();
// --- Перемещаем форму обратно в конец. УБРАНО .hide() для сохранения видимости.
$('#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(){cAction(this,'answer');});
$(document).on('click', '.mod_comment_edit', function(){
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">'+revert+'</textarea></p>';
var charsLeft = '<p>'+COMMENT_CHARS_LEFT+' <span class="charsLeft" id="charsLeft_'+cid+'"></span></p>';
var buttonSave = '<input type="button" value="'+COMMENT_BUTTON_EDIT+'" class="button saveButton" /> ';
var buttonReset = '<input type="button" value="'+COMMENT_BUTTON_CANCEL+'" class="button cancelButton" />';
commentTextBlock.after(
'<div class="box"><div class="block" id="forms"><fieldset><legend>'+COMMENT_EDIT_TITLE
+'</legend>'+textarea+buttonSave+buttonReset+charsLeft+'</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) {
$(document).on('click', '.mod_comment_delete', function(){
if (confirm('Вы уверены, что хотите удалить комментарий?')) {
cAction(this, 'delete');
}
});
$(document).on('click', '.mod_comment_lock', function(){cAction(this, 'lock');});
$(document).on('click', '.mod_comment_unlock', function(){cAction(this, 'unlock');});
$(document).on('click', '#mod_comment_open', function(){cAction(this,'open');});
$(document).on('click', '#mod_comment_close', function(){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.val();
var formData = form.serialize();
$.ajax({
url: aveabspath+'index.php?ajax=1',
type: 'POST',
data: formData,
dataType: 'html',
// Отключаем кнопку перед отправкой
beforeSend: function() {
submitButton.prop('disabled', true).val('Отправка...');
},
// Включаем кнопку обратно и обрабатываем ответ
success: function(data) {
displayNewComment(data);
submitButton.prop('disabled', false).val(originalButtonText);
},
timeout: 3000,
error: function(xhr, status, error) {
console.error("AJAX Error (Creation):", status, error);
alert("Ошибка при отправке комментария. Пожалуйста, проверьте консоль.");
// Включаем кнопку обратно в случае ошибки
submitButton.prop('disabled', false).val(originalButtonText);
}
});
return false;
});
// Сброс формы
$('#buttonReset').click(function(){
$('#parent_id').val('');
$('#mod_comment_new form')[0].reset();
$('#mod_comment_new').insertAfter('#end');
});
});
})(jQuery);
}
})();