/* ====================================================================
ОБЕРТКА ДЛЯ ОЖИДАНИЯ JQUERY
==================================================================== */
(function waitForJQuery() {
if (typeof jQuery === 'undefined') {
setTimeout(waitForJQuery, 10);
} else {
(function($){
if (typeof aveabspath !== 'undefined') {
// 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;
if (action === 'open' || action === 'close') {
cid = DOC_ID;
} else {
var $link = $(obj).closest('a.mod_comment_answer');
cid = $link.attr('rel');
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;
}
// Удаление и модерация (Отправляем запрос, PHP проверит права)
$.get(aveabspath + 'index.php', {
module: 'comment',
action: action,
docid: DOC_ID,
Id: cid
}, function(data){
if (action === 'delete'){
$(obj).parents('.mod_comment_comment').eq(0).remove();
}
if (action === 'open'){
var $openButton = $('#mod_comment_open');
$openButton.attr('id', 'mod_comment_close').html(' ' + COMMENT_SITE_CLOSE);
$openButton.removeClass('btn-outline-success').addClass('btn-outline-danger');
}
if (action === 'close'){
var $closeButton = $('#mod_comment_close');
$closeButton.attr('id', 'mod_comment_open').html(' ' + COMMENT_SITE_OPEN);
$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;
}
if (form.comment_author_email && !form.comment_author_email.value){
alert(COMMENT_ERROR_EMAIL);
$(form.comment_author_email).focus();
return false;
}
if (typeof REQ_F1 !== 'undefined' && REQ_F1 == '1') {
if (form.comment_author_website && !form.comment_author_website.value) {
alert("Пожалуйста, заполните поле: " + NAME_F1);
$(form.comment_author_website).focus();
return false;
}
}
if (typeof REQ_F2 !== 'undefined' && REQ_F2 == '1') {
if (form.comment_author_city && !form.comment_author_city.value) {
alert("Пожалуйста, заполните поле: " + NAME_F2);
$(form.comment_author_city).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 createEditForm(cid, revert, targetElement) {
var currentImg = $('#' + cid).find('.mod_comment_attached_image img').attr('src');
var deletePhotoHtml = '';
if (currentImg) {
deletePhotoHtml = '
' +
'' +
'' +
'
';
}
// Блок для превью нового фото
var editPreviewHtml = '' +
'

' +
'
';
// Поле для загрузки НОВОГО фото
var uploadNewPhotoHtml = '' +
'' +
'' +
editPreviewHtml +
'
';
var textarea = '';
var charsLeft = '' + COMMENT_CHARS_LEFT + '
';
var buttonSave = ' ';
var buttonReset = '';
targetElement.after(
' '
).remove();
$('.saveButton').off('click').on('click', function(){saveChanges(this, false, cid);});
$('.cancelButton').off('click').on('click', function(){saveChanges(this, revert, cid);});
$('#ta_' + cid).limit(MAX_CHARS, '#charsLeft_' + cid);
}
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();
createEditForm(cid, revert, $this);
})
.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();
var deleteImg = $('#del_img_' + cid).is(':checked') ? 1 : 0;
var fd = new FormData();
fd.append('module', 'comment');
fd.append('action', 'edit');
fd.append('Id', cid);
fd.append('text', t);
fd.append('delete_image', deleteImg);
var fileInput = $('#new_file_' + cid)[0];
if (fileInput && fileInput.files[0]) {
fd.append('comment_image', fileInput.files[0]);
}
$.ajax({
url: aveabspath + 'index.php?ajax=1',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(txt){
if (deleteImg == 1 || (fileInput && fileInput.files[0])) {
location.reload();
} else {
$box.after('').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('').remove();
setClickable();
}
}
function displayNewComment(data){
if (data === 'wrong_securecode'){
$('#captcha').after(''+COMMENT_WRONG_CODE+'
');
$('#securecode').focus();
}
else {
$('#end' + $('#parent_id').val()).before(data);
$('#parent_id').val('');
$('#mod_comment_new form')[0].reset();
$('#image_preview_wrapper').addClass('d-none');
$('#image_preview_img').attr('src', '#');
$('#mod_comment_new').insertAfter('#end');
setClickable();
}
getCaptha();
}
$(document).ready(function(){
setClickable();
// ЛОГИКА ПРЕДПРОСМОТРА ДЛЯ ФОРМ РЕДАКТИРОВАНИЯ
$(document).on('change', '.edit-file-input', function() {
var cid = $(this).data('cid');
var file = this.files[0];
var previewWrapper = $('#edit_preview_wrapper_' + cid);
var previewImg = $('#edit_preview_img_' + cid);
if (file) {
var reader = new FileReader();
reader.onload = function(e) {
previewImg.attr('src', e.target.result);
previewWrapper.removeClass('d-none');
}
reader.readAsDataURL(file);
} else {
previewWrapper.addClass('d-none');
}
});
// ЛОГИКА ПРЕДПРОСМОТРА ДЛЯ НОВОГО КОММЕНТАРИЯ
$(document).on('change', '#comment_image', function() {
const file = this.files[0];
const previewWrapper = $('#image_preview_wrapper');
const previewImg = $('#image_preview_img');
const errorDiv = $('#file_error');
if (errorDiv.length) errorDiv.addClass('d-none').text('');
if (file) {
if (file.size > 2 * 1024 * 1024) {
if (errorDiv.length) errorDiv.removeClass('d-none').text('Файл слишком большой (макс. 2Мб)');
this.value = '';
previewWrapper.addClass('d-none');
return;
}
const reader = new FileReader();
reader.onload = function(e) {
previewImg.attr('src', e.target.result);
previewWrapper.removeClass('d-none');
}
reader.readAsDataURL(file);
}
});
$(document).on('click', '#remove_image_btn', function() {
$('#comment_image').val('');
$('#image_preview_wrapper').addClass('d-none');
$('#image_preview_img').attr('src', '#');
});
$(document).on('click', '#captcha img', function(){getCaptha();});
$(document).on('click', '#reload_captcha', function(e){
e.preventDefault();
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();
createEditForm(cid, revert, commentTextBlock);
});
/* --- УДАЛЕНИЕ: Доступно всем, у кого в шаблоне есть кнопка --- */
$(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');
var modalInstance = bootstrap.Modal.getInstance($modal[0]) || new bootstrap.Modal($modal[0]);
modalInstance.hide();
});
var modal = new bootstrap.Modal($modal[0]);
modal.show();
});
/* --- ТОЛЬКО ДЛЯ АДМИНИСТРАТОРОВ (UGROUP == 1) --- */
if (typeof UGROUP !== 'undefined' && UGROUP == 1) {
$(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');});
}
$('#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();
var formData = new FormData(this);
$.ajax({
url: aveabspath + 'index.php?ajax=1',
type: 'POST',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
submitButton.prop('disabled', true).text('Отправка...');
},
success: function(data) {
displayNewComment(data);
submitButton.prop('disabled', false).text(originalButtonText);
},
error: function() {
alert("Ошибка при отправке.");
submitButton.prop('disabled', false).text(originalButtonText);
}
});
return false;
});
$('#buttonReset').click(function(){
$('#parent_id').val('');
$('#mod_comment_new form')[0].reset();
$('#image_preview_wrapper').addClass('d-none');
$('#mod_comment_new').insertAfter('#end');
});
});
})(jQuery);
}
})();