/*VARIABLES*/

var ajaxObj = new XMLHTTP("update_value.php");
var ajax_view_line = new XMLHTTP("view_line2.php");
var prevCell = [];
var prevColumnHeight = [];
var ignore_document_click = 0;
var prevColor = {};
var fieldsTable = $('.fields__table');
var TOTAL_FIRST_CELLS_PADDINGS = 23;
var fieldsCell = $('.fields__cell');
var checkboxColumn = $('.fields__row--info .fields__cell--checkbox');
var checkboxHeaderColumn = $('.fields__row--header .fields__cell--checkbox');

let n_second_column = 2
var secondColumn
findSecondColumn() //Ищем второй столбец к которому есть доступ
var secondColumnWidth = secondColumn.outerWidth(true);

var secondHeaderColumn
findSecondHeaderColumn() //Ищем второй столбец к которому есть доступ

var lastScrollLeft = 0;
var checkboxColumnWidth = checkboxColumn.outerWidth(true);
var rowHeader = $('#f_row');
var rowHeaderHeight = rowHeader.height();
var paddingCell = 5;
var paddingExternal = 32;
var row = $('.fields__row--info');
var hiddenColumn = $('.hidden-column');
var BORDER_SIZE = 1;
var multi_select = $('.fields__multi-val-select');
// Инициализация полей типа "связь" и "дата" в фиксированном поиске
var under_mouse_object = 0;
var last_focus = 0;
// старое значение последнего поля с быстрым редактированием
var fast_edit_old = 0;
var dont_open_view = 0;
var timed_focus_el = 0;
var checkboxHeader = $('#f_row .custom-checkbox');
var all_lines_pp = get_lines_id();
var groups_fields = get_groups_fields();
// var table_data = init_data();
var globalCheckShiftStatus = 0;
var colorFormat = new ColorFormat(0, table_id);
var tableAcCount = 0;
var isTableTarget = 0;
var uniq_fields;
var click_status = 0;
var prev_show_block = 0;
var header_firts_cells = ("#" + checkboxHeaderColumn.css('background-color').replace(/[rgb(,)]/g,'').split(' ').map(el => parseInt(el).toString(16)).join(''));
var addLinkFieldsBlockPoints = {
    top: '',
    left: ''
}
var clientWidth,
    scrollWidth,
    addititonDivWidth;

let inner_block = document.querySelector('#inner_block')
inner_block.addEventListener('scroll', () => {
  $('ul.ui-widget.ui-autocomplete').css({
    display: 'none'
  })
  $('#body_id > .select2-container.select2-container--default.select2-container--open').css({
    //display: 'none'
    top: '-10000px'
  })
})
let checkbox_mode = false
let saved_header_row_height = 0;
let saved_header_left = 0;
let row_header = document.querySelector('.fields__row--header')
var fieldsCellHeaders = document.querySelectorAll('.fields__cell--header');
var rootStyle = getComputedStyle(document.documentElement);
var color1 = rootStyle.getPropertyValue('--cur-scheme-color-1').trim();
var color4 = rootStyle.getPropertyValue('--cur-scheme-color-4').trim();

rowGroupAppendCells();
setCellBackground();
setfieldsBorder();
addClassSecondCell();
createPrevColorArr();


const loadTableStyles = () => {
    fieldsTable.css({
        'margin-top': 0,
        'opacity': 0
    });
    var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    if (isMobile) {
        headerAdjustment();
        $(window).on('resize', function () {
            headerAdjustment();
        });
    }

    $(document).click(function (event) {
        if ($(event.target).closest(".pseudo_select_options").length) return;
        $(".pseudo_select_options").css("display", "none");
        event.stopPropagation();
    });

    colorPrefixAndPostfix();
    init_fields_text();
    init_fields_fast_edit();
    init_fast_edit_multi();
    init_table_anchor();
    init_fix_search_link();
    init_fix_search_date();
    init_shift_checkbox();
    init_date();
    init_big_texts();
    init_fields_same_ident();
    init_fields_additional();
    init_empty_group_fields();
    init_links_autocomplete();
    if ($('.fields__text-prefix, .fields__text-postfix').length > 0) {
      applyPaddingToFields();
    }

    all_width_select_text_formatting();
    var x = window.scrollX, y = window.scrollY;
    $('.fields__table').focus();
    window.scrollTo(x, y);

    setTimeout(() => {
      // если осталось немного до дна, то добавим
      let dno = $(window).height() - document.getElementById('inner_block').getBoundingClientRect().bottom;
      if (dno > 0 && dno < 50) {
        $(window).scrollTop( $(window).scrollTop() - 50 );
      }
    }, 1);

    // Настройка по удалению выделения, если в ячейке изображение
    const colorCells = $('.fields__cell-inner')
    const imgElems = colorCells.find('img:not([class])')

    imgElems.each(function (i, imgElem) {
        $(imgElem['offsetParent']).css('background-color', 'inherit')
    });

    // Отменяем форматирование у автокомплита после клика на карандаш/сабмит
    $('.fields__fast-edit-button--edit').on('click', function () {
        if ($(this).parent().parent().hasClass('fields__special-text--auto-links')) return;
        let $this_parent = $(this).parent();
        let parentCell = $this_parent.parent('.fields__cell-inner');
        parentCell.attr('prev-color', parentCell.css('background-color'));
        parentCell.css('background-color', 'inherit');

        var field_id = $(this).attr('field_id');
        var line_id = $(this).attr('line_id');
        var edit_field = $('textarea#fast_edit_span_' + field_id + '_' + line_id);
        var showBtn = $(this).parent().prev('.fields__resize-btn');

        activeResizeBtn($this_parent)

        edit_field.parent().css('width', '100%');
        showBtn.css('display', 'inline-block');
        showBtn.addClass('fields__resize-btn-down');
        showBtn.attr('title', lang['minimize_text']);
        showBtn.attr('bottom', '100px');
        showBtn.attr('margin-bottom', '10px');
        autosize(showBtn.next());
        let isHTMLeditingField = $(this).next('.fields__fast-edit--html.fields__fast-edit--special-text');

        if ($(this).prev('.fields__simple-text-resize').text().length < 100) {
            if (isHTMLeditingField) {
                if ($(this).prev('.fields__simple-text-resize').text().length > 39) edit_field.css('margin-top', 0);
                else {
                    if (edit_field && edit_field.length > 0) {
                        if (edit_field.val().length > 0 && edit_field.text().length < 1) edit_field.css('margin-top', '');
                        else edit_field.css('padding-top', 0);
                    }
                }

                edit_field.css('height', $(this).prev('.fields__simple-text-resize').height() + 18);
            } else {
                edit_field.css('margin-top', '-11px');
                edit_field.css('height', $(this).prev('.fields__simple-text-resize').height() + 13);
            }
        } else {
            if (isHTMLeditingField) {
                edit_field.css('margin-top', '0');
                edit_field.css('height', $(this).prev('.fields__simple-text-resize').height() + 18);
            } else {
                edit_field.css('margin-top', '-40px');
                edit_field.css('height', $(this).prev('.fields__simple-text-resize').height());
            }
        }
        edit_field.css('overflow', 'hidden');
        edit_field.css('overflow-wrap', 'break-word');
        if ($this_parent.hasClass('fields__simple-text--fixed')) {
            $this_parent.removeClass('fields__simple-text--fixed')
        }

        if ($(this).prev('.fields__simple-text-resize').val() == '' && $(this).prev('.fields__simple-text-resize').text() == '') {
            edit_field.val('');
        }

        $this_parent.css({
            'color': 'black'
        });

        minCustomColumnWidth(showBtn.parents('.fields__row'), $this_parent.hasClass('fields__simple-text--fixed') ? true : false);
    });

    $('.fields__fast-edit-button--done').on('click', function (e) {
        let $this = $(this).parent();
        let parentCell = $this.parent('.fields__cell-inner');
        var showBtn = $this.prev('.fields__resize-btn');

        // Условие в таблице для полей связи
        if (parentCell.find('.fields__special-text--link').length != 0) {
          parentCell.attr('prev-color', parentCell.css('background-color'));
        } else {
          parentCell.css('background-color', parentCell.attr('prev-color'));
        }

        $this.css({
            'color': 'inherit'
        })
        showBtn.attr('bottom', '100px');
        e.preventDefault()
    });

    // Меняем цвет текста элементов textarea при клике
    const textareaElem = $(colorCells.find('textarea'))

    textareaElem.on('focus', function () {
        let $this = $(this)
        let parentCell = $this.parent('.fields__cell-inner')
        parentCell.attr('active', '1')
    })

    textareaElem.on('focusout', function (e) {
        let $this = $(this)
        let parentCell = $this.parent('.fields__cell-inner')
        parentCell.attr('active', '0')
        parentCell.css('background-color', parentCell.attr('prev-color'))
        $this.css({
            'color': 'inherit'
        })
        e.preventDefault()
    })

    textareaElem.on('mouseover', function () {
        let $this = $(this)
        let parentCell = $this.parent('.fields__cell-inner')
        let activeInput = parentCell.attr('active')
        if (activeInput == undefined || activeInput == 0) {
            parentCell.attr('prev-color', parentCell.css('background-color'))
            parentCell.css('background-color', 'inherit')

            $this.css({
                'color': 'black'
            })
        }
    })

    textareaElem.on('mouseout', function (e) {
        let $this = $(this)
        let parentCell = $this.parent('.fields__cell-inner')
        let activeInput = parentCell.attr('active')
        if (activeInput == undefined || activeInput == 0) {
            parentCell.css('background-color', parentCell.attr('prev-color'))
            $this.css({
                'color': 'inherit'
            })
            e.preventDefault()
        }
    })

    // Меняем цвет текста элементов input при клике
    const editElem = $(colorCells.find('input'))

    editElem.on('focus', function () {
        let $this = $(this)
        let parentCell = $this.parent('.fields__cell-inner')
        parentCell.attr('active', '1')
    })

    editElem.on('focusout', function (e) {
        let $this = $(this)
        let parentCell = $this.parent('.fields__cell-inner')
        parentCell.attr('active', '0')
        parentCell.css('background-color', parentCell.attr('prev-color'))
        $this.css({
            'color': 'inherit'
        })
        e.preventDefault()
    })

    editElem.on('mouseover', function () {
        let $this = $(this)
        let parentCell = $this.parent('.fields__cell-inner')
        let activeInput = parentCell.attr('active')
        if (activeInput == undefined || activeInput == 0) {
            parentCell.attr('prev-color', parentCell.css('background-color'))
            parentCell.css('background-color', 'inherit')

            $this.css({
                'color': 'black'
            })
        }
    })

    editElem.on('mouseout', function (e) {
        let $this = $(this)
        let parentCell = $this.parent('.fields__cell-inner')
        let activeInput = parentCell.attr('active')
        if (activeInput == undefined || activeInput == 0) {
            parentCell.css('background-color', parentCell.attr('prev-color'))
            $this.css({
                'color': 'inherit'
            })
            e.preventDefault()
        }
    })

    // Меняем  цвет текста элементов select при клике
    const selectElem = $(colorCells.find('select'))
    selectElem.on('focus', function () {
        let $this = $(this)
        let parentCell = $this.prev('.fields__select-formatter')
        parentCell.attr('active', '1')
    })

    selectElem.on('focusout', function (e) {
        let $this = $(this)
        let parentCell = $this.prev('.fields__select-formatter')
        parentCell.attr('active', '0')
        parentCell.css('background-color', parentCell.attr('prev-color'))

        $this.css({
            'color': 'inherit',
            'background-color': 'transparent'
        })
        e.preventDefault()
    })

    selectElem.on('mouseover', function () {
        let $this = $(this)
        let parentCell = $this.prev('.fields__select-formatter')
        let activeInput = parentCell.attr('active')
        if (activeInput == undefined || activeInput == 0) {
            parentCell.attr('mouse-color', parentCell.css('background-color'))
            parentCell.css('background-color', 'inherit')

            $this.css({
                'color': 'black',
                'background-color': 'white'
            })
        }
    })

    selectElem.on('mouseout', function (e) {
        let $this = $(this)
        let parentCell = $this.prev('.fields__select-formatter')
        let activeInput = parentCell.attr('active')
        if (activeInput == undefined || activeInput == 0) {
            parentCell.css('background-color', parentCell.attr('mouse-color'))
            $this.css({
                'color': 'inherit',
                'background-color': 'transparent'
            })
            e.preventDefault()
        }
    })

    // Меняем цвет текста элементов input при клике(дата)
    const editElemDate = $(colorCells.find('.fields__date-field input.hasDatepicker'))
    const dateTrigger = $(colorCells.find('.ui-datepicker-trigger'))

    //Клик на календарик и снятие форматирования
    dateTrigger.on('click', function () {
        let $input = $(this).parent().find('input')
        let parentCell = $input.parents('.fields__cell-inner')
        let activeInput = parentCell.attr('active')
        if (activeInput == undefined || activeInput == 1) {
            parentCell.attr('prev-color', parentCell.css('background-color'))
            parentCell.css('background-color', 'inherit')

            $input.css({
                'color': 'black'
            })
        }
    })

    editElemDate.on('focus', function () {
        let $this = $(this)
        let parentCell = $this.parents('.fields__cell-inner')
        parentCell.attr('active', '1')
    })

    editElemDate.on('focusout', function (e) {
        let $this = $(this)
        let parentCell = $this.parents('.fields__cell-inner')
        parentCell.attr('active', '0')
        parentCell.css('background-color', 'inherit')
        $this.css({
            'color': 'inherit'
        })
        e.preventDefault()
    })

    editElemDate.on('mouseover', function () {
        let $this = $(this)
        let parentCell = $this.parents('.fields__cell-inner')
        let activeInput = parentCell.attr('active')
        if (activeInput == undefined || activeInput == 0) {
            parentCell.attr('prev-color', parentCell.css('background-color'))
            parentCell.css('background-color', 'inherit')

            $this.css({
                'color': 'black'
            })
        }
    })

    editElemDate.on('mouseout', function (e) {
        let $this = $(this)
        let parentCell = $this.parents('.fields__cell-inner')
        let activeInput = parentCell.attr('active')
        if (activeInput == undefined || activeInput == 0) {
            parentCell.css('background-color', parentCell.attr('prev-color'))
            $this.css({
                'color': 'inherit'
            })
            e.preventDefault()
        }
    })

    // Выбранный цвет шрифта полей даты
    editElemDate.css({
      'color': 'inherit'
    })

    // Вычисляем высоту футера
    // calcHeightFooter();

    // Убираем лишние символы из наименований полей
    editTableFieldsName();

    uniq_fields = init_uniq_fields();

    init_fields_data(table_id, 'any');

    addFakeField();
    addititonDivWidth = checkboxHeaderColumn.outerWidth() + secondHeaderColumn.outerWidth();

    $('.fields__fast-edit-button').each((i, el) => {
        $(el).click(() => {
            minCustomColumnWidth($(el).parents('.fields__row'), true)
        });
    });

    $('.fields__fast-edit--text').each((i, el) => {
        $(el).on('keyup', () => {
            minCustomColumnWidth($(el).parents('.fields__row'), true, true, $(el).parents('.fields__cell'));
        });
    });
    //Для редактируемых полей
    document.querySelectorAll('.fields__cell-inner').forEach(function(cell) {
      if ((cell.querySelector('input') || cell.querySelector('select') || cell.querySelector('textarea')) &&
      !cell.querySelector('.fields__simple-text--link')) {
          cell.style.paddingTop = '0';
          cell.style.paddingBottom = '0';
      }
    });
};
/*  Происходят страшные вещи,
    1. Сначала ждем пока применятся пользовательские стили
    2. Потом ждем таймаута и только потом прячем лоаер и показываем иаблицу
    Иначе все дергается, без существенного рефакоринга спрятать по другому это не получится
*/
$(document).ready(() => {
    const table = document.querySelector('.fields__table');
    loadTableStyles()
    $('.fields').fixedTable(false , false);
    fieldsTable.addClass('fields__table--stable');
    setTimeout(() => {
        hidePreloader();
        table.style.opacity = 1
    }, 200)
})

/* new functions*/
let secondCellHeight = 0
let secondCellWidth = 0
let table = document.querySelector('.fields__table');
let table_header = document.querySelector('.fields__row--header')
let footer = document.querySelector('.fields__footer');
let fields__wrap = document.querySelector('.fields__wrap');

/*  Изолированая логика липкого заголовка таблицы
    с горизонтальным скроллом заголовков вслед за содержимым

    Примечание: заголовок не может быть липким к скроллу страницы css-only
    из-за наличия горизонтального скролла таблицы
*/
(() => {
    // Копируем ширину строк
    const copyCellWidth = (originalCells, clonedCells) => {
        for (let i = 0; i < originalCells.length; i++) {
            const originalCell = originalCells[i];
            const clonedCell = clonedCells[i];

            const computedStyles = window.getComputedStyle(originalCell);
            clonedCell.style.width = computedStyles.getPropertyValue('width');
        }
    }

    const getTableHeaderFixedTop = () => {
        const topHeader = document.getElementById('top_header_div');
        if (!topHeader) {
            return 0;
        }
        return Math.max(0, topHeader.getBoundingClientRect().bottom);
    }

    // Липкий заголовок
    /**
     * Добавляет класс фиксированного заголовка к клонированному заголовку
     * Помещает его в таблицу
     * Показывает если статический заголовок скрыт
     * @param {Element} clonedHeader
     */
    const stickyHeader = (clonedHeader) => {
        const table = document.querySelector('.fields__table');
        const headerRect = table_header.getBoundingClientRect();
        const tableRect = table.getBoundingClientRect();
        const fixedTop = getTableHeaderFixedTop();
        const isHeaderInvisible = headerRect.bottom <= fixedTop && tableRect.bottom > fixedTop;

        clonedHeader.classList.add('table-header-fixed')
        clonedHeader.style.top = `${fixedTop}px`;
        table.appendChild(clonedHeader)

        const originalCells = table_header.querySelectorAll('.fields__cell ');
        const clonedCells = clonedHeader.querySelectorAll('.fields__cell');
        copyCellWidth(originalCells, clonedCells);
        if (isHeaderInvisible) {
            clonedHeader.style.display = ''
            clonedHeader.style.width = `${table_header.scrollWidth}px`;
        } else {
            clonedHeader.style.display = 'none'
        }

    if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) {
        for (var i = 0; i < fieldsCellHeaders.length; i++) {
            fieldsCellHeaders[i].style.background = color1;
            if(i == 1 || i == 0) fieldsCellHeaders[i].style.background = color4;
        }
    }
    }

    // Горизонтальный скролл с липкими ячейками
    /**
     * Сдвигает целевой элемент по оси X по скроллу другого элемента
     * Чекбокс и вторая колонка ведут себя как липкие
     * @param {Element} targetElement - Элемент(таблица) повторяющий скролл другого
     * @param {Element} scrollableElement - Элемент чье положение копируется
     */
    const copyScrollX = (targetElement, scrollableElement) => {
        const checkbox = targetElement.querySelector('.fields__cell--checkbox');
        const secondCol = targetElement.querySelector('.fields__second-cell');

        targetElement.style.transform  = `translateX(-${scrollableElement.scrollLeft}px)`;
        secondCol.style.transform  = `translateX(${scrollableElement.scrollLeft}px)`;
        checkbox.style.transform  = `translateX(${scrollableElement.scrollLeft}px)`;
        checkbox.style.transform = `background: ${color1};`;
    }

/**
     * Создает и добавляет новый элемент липкого скроллбара на страницу.
     * Навешивает функционал скролла
     * Липкий скроллбар представляет собой интерфейсный элемент, который позволяет
     * пользователю прокручивать содержимое, оставаясь видимым на экране.
     *
     * @function stickyScrollbar
     * @returns {Element} Объект, содержащий три элемента:
     *
    */
    const stickyScrollbar = (target) => {
        /**
         * Создает и добавляет новый элемент липкого скроллбара на страницу.
         * Липкий скроллбар представляет собой интерфейсный элемент, который позволяет
         * пользователю прокручивать содержимое, оставаясь видимым на экране.
         *
         * @function appendStickyScrollbar
         * @returns {Object} Объект, содержащий три элемента:
         * @returns {Element} stickyScrollbar - основной элемент липкого скроллбара.
         * @returns {Element} stickyScrollbarContainer - контейнер для содержимого липкого скроллбара.
         * @returns {Element} stickyScrollbarContent - элемент, содержащий прокручиваемое содержимое.
         *
         * @example
         * const { stickyScrollbar, stickyScrollbarContainer, stickyScrollbarContent } = appendStickyScrollbar();
         *
         */
        const appendStickyScrollbar = () => {
            const stickyScrollbar = document.createElement('div');
            stickyScrollbar.classList.add('sticky-scrollbar');

            const stickyScrollbarContainer = document.createElement('div');
            stickyScrollbarContainer.classList.add('sticky-scrollbar__container');


            const stickyScrollbarContent = document.createElement('div');
            stickyScrollbarContent.classList.add('sticky-scrollbar__content');

            stickyScrollbarContainer.appendChild(stickyScrollbarContent);
            stickyScrollbar.appendChild(stickyScrollbarContainer);
            document.body.appendChild(stickyScrollbar);

            return {
                stickyScrollbar,
                stickyScrollbarContainer,
                stickyScrollbarContent,
            };
        };

        /**
         * Проверяет, виден ли низ целевого элемента на странице, и скрывает липкий скроллбар, если он виден.
         *
         * @param {Element} target - Целевой элемент, который будет проверяться.
         * @param {Element} stickyScrollbar - Элемент липкого скроллбара, который нужно скрыть.
         */
        const toggleScrollbarVisibility = (target, stickyScrollbar) => {
            const targetRect = target.getBoundingClientRect();
            const isTargetBottomVisible = targetRect.bottom <= window.innerHeight;

            if (isTargetBottomVisible) {
                stickyScrollbar.style.display = 'none'; // Скрыть скроллбар
            } else {
                stickyScrollbar.style.display = ''; // Показать скроллбар
            }
        };

        const setScrollWidth = (target, stickyScrollbarContent) => {
            const scrollWidth = target.scrollWidth;
            const clientWidth = target.clientWidth;
            stickyScrollbarContent.style.width = `${(scrollWidth / clientWidth) * 100}%`;
        }

        let isScrolledTable = false
        let isScrolledStickyScrollbar = false

        const { stickyScrollbar, stickyScrollbarContainer, stickyScrollbarContent } = appendStickyScrollbar();

        target.addEventListener('scroll', () => setScrollWidth(target, stickyScrollbarContent))
        window.addEventListener('resize', () => setScrollWidth(target, stickyScrollbarContent));

        target.addEventListener('scroll', function () {
            if(isScrolledStickyScrollbar) return;

            isScrolledTable = true;
            stickyScrollbarContainer.scrollLeft = target.scrollLeft
            isScrolledTable = false
        })

        stickyScrollbarContainer.addEventListener('scroll', function () {
            if(isScrolledTable) return;
            isScrolledStickyScrollbar = true;

            target.scrollLeft = stickyScrollbarContainer.scrollLeft;

            isScrolledStickyScrollbar = false;
        });

        document.addEventListener('scroll', () => toggleScrollbarVisibility(target, stickyScrollbar));
        window.addEventListener('resize', () => toggleScrollbarVisibility(target, stickyScrollbar));

        setScrollWidth(target, stickyScrollbarContent);
        toggleScrollbarVisibility(target, stickyScrollbar);
    }

    // Клонируем элемент, нельзя и не нужно его менять он и так вне видимости, это ломает верстку строк
    const clonedHeader = table_header.cloneNode(true);
    // Обертка таблицы с горзонтальным скроллом
    const tableWrapper = document.querySelector('.fields__wrap');

    stickyHeader(clonedHeader);

    window.addEventListener('resize', () => stickyHeader(clonedHeader));
    if (window.visualViewport) {
        window.visualViewport.addEventListener('resize', () => stickyHeader(clonedHeader));
    }

    if (parseInt(window_scroll) === 1) {
        var table = $('.fields__table');
        if (table.length > 0) {
            $(document).on('scroll', () => {
                stickyHeader(clonedHeader);
                // На первый взгляд связь липкого скроллбара с реальной прокруткой таблицы
                // На второй взгляд удаление ни на что не влияет
                // Протестировать по возможности и удалить
                let fixedTableLayer = $('.fixed-table-layer');
                if (!fixedTableLayer.hasClass('hidden')) {
                const fixedTableInner = $('.fixed-table-inner');
                fixedTableInner.scrollLeft($('#inner_block').scrollLeft());
                }
            });
        }
    }
    tableWrapper.addEventListener('scroll', function () {
        copyScrollX(clonedHeader, tableWrapper);
        stickyCells();
    })
    stickyScrollbar(tableWrapper);
})()

function stickyCells() {
    let checkboxHeaderColumnLeft
    let secondHeaderColumnLeft

    checkboxHeaderColumnLeft = 0
    secondHeaderColumnLeft = '32px'

    let cell_padding_top = window.getComputedStyle(secondColumn[0]).paddingTop.replace('px', '')
    let cell_padding_bottom = window.getComputedStyle(secondColumn[0]).paddingBottom.replace('px', '')

    cell_padding_top = Number(cell_padding_top)
    cell_padding_bottom = Number(cell_padding_bottom)
    let cell_height = `calc(100% - ${cell_padding_top + cell_padding_bottom}px)`

    checkboxColumn.css({
      'display': 'table-cell',
      'height': cell_height,
      'left': '0px',
      'z-index': '1000',
      'position': '-webkit-sticky',
      'position': 'sticky',
      'background-color': 'inherit',
    })
    checkboxHeaderColumn.css({
      'display': 'table-cell',
      'height': cell_height,
      'left': checkboxHeaderColumnLeft,
      'z-index': '1000',
      'position': '-webkit-sticky',
      'position': 'sticky',
    })
    secondColumn.css({
      'display': 'table-cell',
      'height': cell_height,
      'left': '32px',
      'z-index': '1000',
      'position': '-webkit-sticky',
      'position': 'sticky',
      'background-color': 'inherit',
    })
    secondHeaderColumn.css({
      'display': 'table-cell',
      'height': cell_height,
      'left': secondHeaderColumnLeft,
      'z-index': '1000',
      'position': '-webkit-sticky',
      'position': 'sticky',
      'background-color': checkboxHeaderColumn[0].style.backgroundColor,
    })
}
/*end new functions*/



function findSecondHeaderColumn() {
  let finded_second_header_column = $(`.fields__row--header .fields__cell:nth-child(${n_second_column})`);
  secondHeaderColumn = finded_second_header_column
}
function findSecondColumn() {
  let finded_second_column = $(`.fields__cell:nth-child(${n_second_column})`);
  if (finded_second_column.css('display') == 'none') {
    n_second_column++
    findSecondColumn()
  } else {
    secondColumn = finded_second_column
  }
}
function init_links_autocomplete() {
  let selects = document.querySelectorAll('select[disable_link="1"][type_field="5"]:not([disabled])')
  selects.forEach( (select) => {
    if ($(select).siblings('.autocomplete').length) {

      if (select.closest('.fields__special-text')) {
        let wrap = select.closest('.fields__special-text')

        if (wrap) {
          wrap.classList.add('fast-link-edit')
        }


        if (wrap.querySelector('.show-field-slave__item--inline')) { //Убираем доп. поля из основного input
          if (wrap.querySelector('.autocomplete__input')) {
            setTimeout(() => { //костыль, пока не понятно выполнения какой функции нужно сдать
              let autocomplete_input_value = wrap.querySelector('.autocomplete__input').value
              let inline_additional_value = wrap.querySelector('.show-field-slave__item--inline').innerHTML

              wrap.querySelector('.autocomplete__input').value = autocomplete_input_value.replace(inline_additional_value, '')
            }, 1);
          }
        }
      }
    }
  })

  let fast_link_edit_fields = document.querySelectorAll('.fields__special-text.fast-link-edit');
  fast_link_edit_fields.forEach((item) => {
    let edit_button = item.querySelector('.fields__fast-edit-button--edit')
    item.addEventListener('click', (e) => edit_button.click());
    item.addEventListener('mousedown', (e) => dont_open_view = 1);
  });
}

function showActionButtonsHeader() {
    checkbox_mode = true
    let action_list = document.querySelector('.new-fields-actions-list')

    saved_header_row_height = row_header.offsetHeight

    if (row_header.style.left != '0px' || row_header.style.left != 0) {
        saved_header_left = row_header.style.left
    }

    row_header.style.left = 0

    action_list.style.height = saved_header_row_height + 'px'
    action_list.classList.remove('hidden-action-list')
}
function hideActionButtonsHeader() {
    checkbox_mode = false

    row_header.style.left = saved_header_left

    let action_list = document.querySelector('.new-fields-actions-list')
    action_list.classList.add('hidden-action-list')
}
function checkAllCheckboxes() { //Проверка чекбоксов
  let checkboxes = document.querySelectorAll('[name="sel[]"]')
  let custom_checkall_checkbox = document.querySelector('.new-fields-actions-list .custom-checkbox')
  let checked = false

  let count = 0

  checkboxes.forEach( (checkbox) => {
      if (checkbox.checked) {
          checked = true
          count++
      }
  })

  if (count == checkboxes.length) {
    custom_checkall_checkbox.classList.add('checked')
  } else {
    custom_checkall_checkbox.classList.remove('checked')
  }

  if (!checked) {
    hideActionButtonsHeader()
  } else if (checkbox_mode == false){
    showActionButtonsHeader()
  }
}

// Подсветка строки при выборе чекбокса
(() => {
  let checkboxes = document.querySelectorAll('[name="sel[]"]')

  const onChangeCheckBox = (checkbox) => {
    const isChecked = checkbox.checked
    const row = checkbox.closest('.fields__row')
    // row.style.backgroundColor = '#f4f0d1';
    row.classList.toggle('checked', isChecked)
  }

  checkboxes.forEach( (checkbox) => {
    checkbox.addEventListener('change', () => onChangeCheckBox(checkbox))
  })
})();

function editTableFieldsName() {
    $('.fields__row.fields__row--header').find('a').each(function (i, item) {
        var str = $(item).html().toString();
        str = str.replace(/\n/, '');
        str = str.replace(/\t/, '');

        // Удаляем все пробелы и отступы в строке (ДО и ПОСЛЕ самого значения)
        for (let i = 0; i < str.length; i++) {
            while ((/\s/g).test(str.charAt(0))) {
                str = str.substr(1);
            }
        }
        for (let i = str.length - 1; i >= 0; i--) {
            if ((/\s/).test(str[i]) > 0) {
                str = str.slice(0, -1);
            } else {
                break;
            }
        }

        // Если есть вхождение символа двойных кавычек, то значением элемента будет значение из атрибута "title"
        if (str.split('"').length > 1) {
            $(item).html($(item).attr('title'));
        }
    });
}

/*FUNCTIONS*/
function headerAdjustment() {
    var columns = $('.fields__header').children();
    var firstColumn = $(columns[0]).width();
    var secondColumn = $(columns[1]).width();
    var thirdColumn;
    if (typeof window.act_arc_del_max_size !== 'undefined') {
        thirdColumn = window.act_arc_del_max_size;
    } else {
        thirdColumn = $(columns[2]).width();
    }
    var computedWidth = parseInt(firstColumn) + parseInt(secondColumn) + parseInt(thirdColumn);
    var headerTop = parseInt($('#top_header_div').width()) - 40;

    if (computedWidth > headerTop) {
        $('.fields__header').css('flex-wrap', 'wrap');
        $('#act_arc_del').css('width', '100%');
    } else {
        $('.fields__header').css('flex-wrap', 'nowrap');
        $('#act_arc_del').css('width', '40%');
        if (typeof window.act_arc_del_max_size === 'undefined') {
            window.act_arc_del_max_size = parseInt($('#act_arc_del').width());
        } else {
            if (window.act_arc_del_max_size > parseInt($('#act_arc_del').width())) {
                window.act_arc_del_max_size = parseInt($('#act_arc_del').width());
            }
        }
    }
}

function addNewFile(fieldId, lineId) {
    $(`#file_input_${fieldId}_${lineId}`).trigger('click');
}

async function addFile(fieldId, lineId, tableId) {
    let fileData = $(`#file_input_${fieldId}_${lineId}`).prop('files')[0];
    let response = await toBase64(fileData);

    let formdata = new FormData();
    formdata.append("csrf", csrf);
    formdata.append("add_file_name", fileData.name);
    formdata.append("add_file_data", response);
    formdata.append("field", fieldId);
    formdata.append("line", lineId);

    fetch("update_value.php", {
        method: "POST",
        body: formdata
    })
        .then(() => {
        const fileName = fileData.name;
        const encName = encodeURIComponent(fileName);

        const isAudio = /\.(mp3|wav|aac|m4a|mp4|ogg|oga|webm|flac)$/i.test(fileName);

        // уникальный id как в PHP 
        const uniqueId = `${fieldId}_${lineId}_${Date.now()}`;

        const linkHref = `open_file.php?table=${tableId}&field=${fieldId}&line=${lineId}&file=${encName}`;

        const stopMouseDown = `onmousedown="event.stopPropagation(); if(typeof dont_open_view!=='undefined') dont_open_view=1;"`;

        // delete для аудио 
        const fileJs = JSON.stringify(fileName).replace(/"/g, '&quot;');

        const audioDeleteBtn = `
        <a id="deleteBtn_${uniqueId}" href="javascript:void(0)" ${stopMouseDown}
            onclick="event.stopPropagation(); if(typeof dont_open_view!=='undefined') dont_open_view=1;
                    return deleteFile('src','${fieldId}','${lineId}', ${fileJs}, this);">
            <span class="b_drop_hoverpopup_cross" style="cursor:pointer; margin-left:5px;"></span>
        </a>
        `;

        // play/pause для аудио 
        const audioPlayBtn = `
            <a id="playBtn_${uniqueId}" href="javascript:void(0)" ${stopMouseDown}
            onclick="event.stopPropagation(); if(typeof dont_open_view!=='undefined') dont_open_view=1; return false;">
            <span class="b_drop_hoverpopup_play" style="cursor:pointer; margin-left:5px;"></span>
            </a>
        `;

        const audioPauseBtn = `
            <a id="pauseBtn_${uniqueId}" href="javascript:void(0)" ${stopMouseDown}
            onclick="event.stopPropagation(); if(typeof dont_open_view!=='undefined') dont_open_view=1; return false;">
            <span class="b_drop_hoverpopup_pause" style="cursor:pointer; margin-left:5px;"></span>
            </a>
        `;

        // delete для обычных файлов 
        const normalDeleteBtn = `
        <a class="file-cell__btn_delete" ${stopMouseDown}
            onclick="event.stopPropagation(); if(typeof dont_open_view!=='undefined') dont_open_view=1;
                    return deleteFile('src','${fieldId}','${lineId}', ${fileJs}, this);"></a>
        `;

        // кнопки
        const buttonsHtml = isAudio
            ? (audioDeleteBtn + audioPlayBtn + audioPauseBtn)
            : normalDeleteBtn;

        // сам блок
        let elem = `
            <div class="fields__cell-inner fields__cell-inner--with-fixed">
            <span class="file-cell" id="audio_wrap_${uniqueId}" style="margin-top: 10px;"
                    ${stopMouseDown}
                    onclick="event.stopPropagation();">
                <a class="file-cell__title" href="${linkHref}"
                ${stopMouseDown}
                onclick="event.stopPropagation(); if(typeof dont_open_view!=='undefined') dont_open_view=1;">
                ${fileName}
                </a>
                ${buttonsHtml}
            </span>
            </div>
        `;

        // JS плеер
        if (isAudio) {
            elem += `
    <script>
    (() => {
    const block = document.getElementById('audio_wrap_${uniqueId}');
    if (!block) return;

    const playBtn = document.getElementById('playBtn_${uniqueId}');
    const pauseBtn = document.getElementById('pauseBtn_${uniqueId}');
    const link = block.querySelector('a.file-cell__title');
    if (!playBtn || !pauseBtn || !link) return;

    const playIcon = playBtn.querySelector('span') || playBtn;
    const pauseIcon = pauseBtn.querySelector('span') || pauseBtn;

    let audio = block.querySelector('audio');
    if (!audio) {
        audio = document.createElement('audio');
        audio.preload = 'none';
        block.appendChild(audio);
    }
    audio.src = link.href;

    const stopAll = (e) => {
        if (!e) return;
        e.preventDefault();
        e.stopPropagation();
        if (e.stopImmediatePropagation) e.stopImmediatePropagation();
        if (typeof dont_open_view !== 'undefined') dont_open_view = 1;
    };

    // delete: модалка в HTML onClick, тут cleanup после факта
    const deleteBtn = document.getElementById('deleteBtn_${uniqueId}');
    if (deleteBtn) {
        deleteBtn.addEventListener('mousedown', (e) => { e.stopPropagation(); if(typeof dont_open_view!=='undefined') dont_open_view=1; });

        const cleanupAndRemove = () => {
        try {
            const a = block.querySelector('audio');
            if (a) {
            a.pause();
            a.removeAttribute('src');
            a.load();
            a.remove();
            }
        } catch (err) { console.warn('Audio cleanup error:', err); }
        if (block && block.parentNode) block.parentNode.removeChild(block);
        };

        const obs = new MutationObserver(() => {
        // если deleteBtn исчез — удаление подтвердили/перерисовали
        if (!document.body.contains(deleteBtn)) {
            cleanupAndRemove();
            obs.disconnect();
        }
        });
        obs.observe(document.body, { childList: true, subtree: true });
    }

    playBtn.addEventListener('click', (e) => {
        stopAll(e);
        audio.play().catch(err => console.error('Play error:', err));
        playIcon.classList.add('active');
        pauseIcon.classList.remove('active');
    });
    playBtn.addEventListener('mousedown', stopAll);

    pauseBtn.addEventListener('click', (e) => {
        stopAll(e);
        audio.pause();
        pauseIcon.classList.add('active');
        playIcon.classList.remove('active');
    });
    pauseBtn.addEventListener('mousedown', stopAll);

    audio.addEventListener('ended', () => {
        playIcon.classList.remove('active');
        pauseIcon.classList.remove('active');
    });

    block.addEventListener('click', (e) => e.stopPropagation());
    block.addEventListener('mousedown', (e) => { e.stopPropagation(); if(typeof dont_open_view!=='undefined') dont_open_view=1; });
    })();
    </script>
            `;
        }
        $(`#file_input_${fieldId}_${lineId}`).before(elem);
        });
}

function deleteFile(src, field_id, line_id, f_name, el) {

    jconfirm(lang.Delete_file + ' ' + f_name + '?',
        function () {
            src_field = field_id;
            src_line = line_id;
            let page_param = '';

            if (cur_subtable)
                page_param = '&subtable_page=' + cur_subtable['cur_page'] + '&rel_field=' + cur_subtable['rel_field'];

                ajaxObj.format = 0;
                ajaxObj.method = 'POST';
                ajaxObj.call('sel=drop_file&field=' + field_id + '&line=' + line_id + '&fname=' + encodeURIComponent(f_name) + '&csrf=' + csrf + page_param, function (resp) {
                    let res_arr = resp.toString().split('|');

                    $(el).prev().remove();
                    $(el).remove();

                    if (res_arr[0] == 'deleted' || res_arr[0] == 'message') { // удаляем из списка
                        displayNotification(lang.Success_save_notif, 1);
                    }
                });
        })
}

function addNewImage(id) {
    $('#image_input'+id).trigger('click');
}

async function addImage(fieldId, lineId, tableId) {

    let fileData = $('#image_input'+fieldId).prop('files')[0];
    let idxDot = fileData.name.lastIndexOf(".") + 1;
    let extFile = fileData.name.substr(idxDot, fileData.name.length).toLowerCase();
    if (extFile=="jpg" || extFile=="jpeg" || extFile=="png" || extFile=="gif" || extFile=="svg"){
        //TO DO
    }else{
        alert("Only jpg/jpeg, png, gif, svg files are allowed!");
        return;
    }

    let res = await toBase64(fileData );

    let formdata = new FormData();
    formdata.append("csrf", csrf);
    formdata.append("add_file_name", fileData.name);
    formdata.append("add_file_data", res);
    formdata.append("field", fieldId);
    formdata.append("line", lineId);

    fetch("update_value.php", {
        method: "POST",
        body: formdata
    })
        .then(result => {
            source = "cache/"+ tableId + '_' + fieldId + '_' + lineId + '_' + utf2eng(fileData.name) + ".png";
            source1 = tableId + '_' + fieldId + '_' + lineId + '_' + utf2eng(fileData.name) + ".png";
            element = '<span><a class="fancybox-item"  data-fancybox="gallery' + lineId + '_' + fieldId +'" href="open_file.php?field=' + fieldId +  '&line=' + lineId + '&file=' + fileData.name + '&show=1' + '"' + '><img src="' + source + '"' +' onmousedown="dont_open_view=1"></a><a onClick="(function(el){deleteFile(`' + source1 + '`,`' + fieldId + '`,`' + lineId + '`,`' + fileData.name + '`, el )})(this)" style="color:red;font-weight:bold;margin-left:10px;display:inline-block;width:30px;height:30px;font-size:15px">X</a></span><br>';
            $("#before_id"+fieldId).before(element);
        })
}
function toBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    })
};

function init_data() {
    var result = {};

    $.ajax({
        method: 'GET',
        async: false,
        url: 'get_value.php?&show_lines&table=' + table_id,
        success: function (resp) {
            result = JSON.parse(resp);
        },
        error: function () {
        }
    });

    return result;
}

function init_fields_fast_edit() {
    var fields = $('.fields__fast-edit');
    if (fields.length > 0) {
        fields.each(function (i) {
            var $this = $(this);
            if ($this.hasClass('fields__fast-edit--combobox')) {
                init_fields_link($this, i);
                tableAcCount++;
            } else if ($this.hasClass('fields__fast-edit--time')) {
                init_fields_date($this);
            }
        });
    }
    var addLinkFields = $('.user-data__value--add .fast_add_link_field.combobox');
    if (addLinkFields.length > 0) {
        addLinkFields.each(function (i) {
            var $this = $(this);
            init_fields_link($this, i);
        });
    }
    var edit_buttons = $('.fields__fast-edit-button--edit');
    if (edit_buttons.length > 0) {
        edit_buttons.each(function () {
            $(this).prev().css('padding-right', $(this).outerWidth(true));
            $(this).mouseup(function (e) {
                e.stopPropagation();
            });
            $(this).click(init_edit_buttons);
        });
    }
    var done_buttons = $('.fields__fast-edit-button--done');
    if (done_buttons.length > 0) {
        done_buttons.each(function () {
            $(this).mouseup(function (e) {
                e.stopPropagation();
            });
            $(this).click(init_done_buttons);
        })
    }
    $('.custom-color').each(function () {
        var $this = $(this);
        $this.find($('a')).css('color', $this.css('color'));
    })
}

/**
 * Метод, инициализирует текстовые поля(не редактируемые), в случае, если они превышают 50 символов, оно переносится
 */
function init_big_texts() {
    $('.fields__simple-text').each(function (i, item) {
        if (item.childNodes.length > 0) {
            if ($(item).first().text().length > 47) {

                let slaves = $(item).find('.show-field-slave__item'); //Смотрим доп. поля, добавляем перенос текста если длинное (> 35 символов)
                for (let i = 0; i < slaves.length; i++) {
                    if ($(slaves[i]).text().length > 35) {
                        $(slaves[i]).css({
                            'word-break': 'break-word'
                        })
                    }
                }

                $(item).css({
                    'max-width': other_field_max_width,
                });
            }
        } else {
            if (item.childNodes.length === 1 && typeof item.childNodes[0].tagName === 'undefined') {
                if ($(item).text().length > 47) {
                    $(item).css({
                        'white-space': 'pre-line',
                        'max-width': other_field_max_width + 'px',
                    });
                }
            }
        }
        if ($(item).first().parent().hasClass('fields__special-text--html')) {
            let resizeTxt = $(item).children('.fields__simple-text-resize');

            if ($(item).first().text().length < 40) {
                resizeTxt.css('padding-top', 0);
            }
            $(item).css({
                'display': 'inline-flex',
                'align-items': 'center',
                'white-space': 'pre-line',
                'max-width': other_field_max_width + 'px',
                'margin-bottom': 5,
            });
            if (resizeTxt.height() > 32 && resizeTxt.height() < 40) {
                resizeTxt.css('padding-top', '8%');
            }
        }
    });
}

/**
 * Метод выравнивает небольшие отсупы по бокам для input
 */
function init_fields_same_ident() {
    row.each(function(i, elem) {
      unindentationFields(elem, 'input.fields__fast-edit--date');
      unindentationFields(elem, 'input.fields__fast-edit--datetime');
      unindentationFields(elem, 'input.fields__fast-edit--num');
      $(elem).find('.fields__cell-number div.fields__value').css({
        "padding-right": 0,
      });
    });

    function unindentationFields(line, selector) {
      $(line).find(selector).closest('.fields__cell-inner').css({
        "padding-left": 0,
        "padding-right": 0,
      });
    }
}

function setCellBackground() {
    for (var i = 0; i < row.length; i++) {
        if (row.eq(i).find(secondColumn).css('background-color') == '' || row.eq(i).find(secondColumn).css('background-color') == 'rgba(0, 0, 0, 0)') {
            row.eq(i).find(secondColumn).css('background-color', row.eq(i).css('background-color'));
        }
        row.eq(i).find(checkboxColumn).css('background-color', row.eq(i).css('background-color'));
        row.eq(i).find($('.fields__row--simple .fields__cell--checkbox div')).css('background-color', row.eq(i).css('background-color'));
    }
}

function init_fields_additional() {
    $('.fields__resize-btn').each(function () {
        var $this = $(this);
        var needle;
        let addHiddenFields = $this.closest('.fields__cell-inner').find('.fields__simple-text:eq(0)').find('.show_field_slave--hidden');
        let addFields = $this.closest('.fields__cell-inner').find('.fields__simple-text:eq(0)').find('.show_field_slave');
        let fields_value = $this.closest('.fields__resize-btn-container').next()

        const checkTextCondition = (text) => {
            return text.length > 37 || text.match(/\n/g) || text.match(/<br>/g);
        };

        if (fields_value.children().length > 1) {
            if (fields_value.hasClass('fields__special-text--link')) {
                needle = fields_value.find('.fields__simple-text--link').children().filter(function(i, el) {
                    const isHasShowFieldSlave = $(this).children().hasClass('show_field_slave')
                    return isHasShowFieldSlave || checkTextCondition($(this).text().trim());
                }).length > 0;
            } else if (fields_value.hasClass('fields__special-text--hyperlink')) {
                let text = fields_value.find('.fields__simple-text-resize').first().text().trim();
                needle = checkTextCondition(text);
            } else {
                needle = true;
            }
        } else {
            let nextElement = fields_value.first();

            if (nextElement.length > 0) {
                let text = nextElement.text().trim();
                needle = checkTextCondition(text) || nextElement[0].getAttribute('data-expandable') === "true";
            }

            if (!needle) {
                nextElement.parent().find('.fields__resize-btn-container').css('display', 'none');
            }
        }

        if (($this.hasClass('fields__resize-btn--not-edit') && needle) || ($this.hasClass('fields__resize-btn--edit') && needle)) {
            $this.show();
            var text = fields_value;

            if (fields_value.hasClass('type_field-4')) {
              fields_value.width(fields_value.width() + 15);
            }

            if ($this.hasClass('fields__resize-btn--file')) {
                text.addClass('fields__simple-text--fixed-file');
            }
            text.addClass('fields__simple-text--fixed');
            $this.mouseup(function (e) {
                e.stopPropagation();
            });
            $this.attr('title', lang['show_all_text']);
            $this.click(function () {
                var $btn = $(this);
                var opened;

                if (text.hasClass('fields__simple-text--fixed')) {
                    text.removeClass('fields__simple-text--fixed');
                    $btn.addClass('fields__resize-btn-down');
                    $btn.parent().addClass('fields__resize-btn-down');
                    if (!text.hasClass('fields__simple-text--fixed-file')) {
                        $btn.css('bottom', '-14px');
                    }
                    $btn.attr('title', lang['minimize_text']);
                    opened = true;
                    if (addHiddenFields.length > 0) {
                        addHiddenFields.show();
                    }
                    if (addFields.length > 0) {
                        addFields.show();
                    }
                    autosize($btn.closest('.fields__resize-btn-container').next());
                    if (!$btn.closest('.fields__cell-inner').hasClass('fields__special-text--html')) {
                        $btn.closest('.fields__resize-btn-container').next().children('.fields__simple-text-resize').first().css('padding-top', 0);
                    }
                    if ($btn.closest('.fields__cell-inner').hasClass('fields__special-text--html')) {
                        $btn.closest('.fields__resize-btn-container').next().children('.fields__simple-text-resize').first().css('padding-top', 0);
                    }
                } else {
                    text.addClass('fields__simple-text--fixed');
                    $btn.removeClass('fields__resize-btn-down');
                    $btn.parent().removeClass('fields__resize-btn-down');
                    $btn.attr('title', lang['show_all_text']);
                    $btn.css('bottom', '-15px');
                    opened = false;
                    if (addHiddenFields.length > 0) {
                        addHiddenFields.hide();
                    }
                    if (addFields.length > 0) {
                        addFields.hide();
                    }
                    if ($btn.closest('.fields__cell-inner').hasClass('fields__special-text--html')) {
                        let edit_btn = $btn.closest('.fields__resize-btn-container').next().children('.fields__fast-edit-button.fields__fast-edit-button--edit').first();
                        let edit_field = edit_btn.next();
                        let resizeField = $btn.closest('.fields__resize-btn-container').next().children('.fields__simple-text-resize').first();

                        if (edit_field.text().length > 40 || edit_field.val().length > 40) resizeField.css('padding-top', '');
                        if (edit_btn.css('display') == 'none') {
                            if (resizeField.text().length > 40) {
                                edit_field.css('height', edit_field.height() - 10);
                                if (resizeField.height() > 32 && resizeField.height() < 40) {
                                    resizeField.css('padding-top', '8%');
                                } else {
                                    edit_field.css('padding-top', '16%');
                                }
                            } else {
                                edit_field.css('padding-top', 0);
                            }
                        } else {
                            if (resizeField.text().length > 40) {
                                resizeField.css('padding-top', '');
                                edit_field.css('height', edit_field.height() - 10);
                                edit_field.css('padding-top', '14%');
                                if (resizeField.height() > 32 && resizeField.height() < 40) {
                                    resizeField.css('padding-top', '16%');
                                }
                            } else {
                                resizeField.css('padding-top', 0);
                                edit_field.css('padding-top', 0);
                                edit_field.css('margin-top', 0);
                            }
                        }
                    }
                }
                if (opened && $this.css('display') == 'none') {
                    $btn.css('bottom', '-15px');
                }
                if (parseInt(window_scroll) === 1 || $btn.closest('.fields__cell-inner').hasClass('fields__special-text--html')) {
                    var field_id = $btn.parents('.fields__cell').attr('field_id');
                    var line_id = $btn.parents('.fields__row').attr('id').replace(/\D/g, '');
                    setNewHeight(line_id, field_id, opened);
                }
                autosize($btn.closest('.fields__resize-btn-container').next());
                minCustomColumnWidth($btn.parents('.fields__row'), text.hasClass('fields__simple-text--fixed') ? true : false);
            });
        }

        if (addHiddenFields.length > 0) {
            addHiddenFields.hide();
        }
        if (addFields.length > 0) {
            addFields.hide();
        }
    });
    $('.fields__multi-val-select-text').each(function () {
        $(this).val($(this).val().replace(/<br>/g, ', '));
    });

    $('.fields__simple-text-resize').each(function (){
        if($(this).find('button').length > 0){
            $(this).css({
                'display': 'flex',
                'align-items': 'center',
                'width': '100%'
            });
        }
    });
    $('.fields__simple-text--fixed').each(function () {
        $(this).parents('.fields__cell-inner').addClass('fields__cell-inner--with-fixed');
        if($(this).parents('.fields__cell-inner').find('.fields__simple-text-resize').find('button').length > 0){
            $(this).parents('.fields__cell-inner').find('.fields__simple-text-resize').css({
                'width': '80%',
                'align-self': 'flex-start',
                'padding-top': 0
            });
        }
        else {
            $(this).parents('.fields__cell-inner').find('.fields__simple-text-resize').css({
                'align-self': 'flex-start',
                'padding-top': 0
            });
        }

        $('textarea.fields__fast-edit--special-text').each(function (i, item) {
            $item = $(item);
            var edit_btn = $item.siblings('.fields__fast-edit-button.fields__fast-edit-button--edit');
            var done_btn = $item.siblings('.fields__fast-edit-button.fields__fast-edit-button--done');

            if ($item.parents('.fields__cell-inner').width() < 150) {
                edit_btn.css('right', '-16px');
                done_btn.css('right', '-16px');
                if ($item.parents('.fields__cell-inner').width() < 77) {
                    edit_btn.css('width', '14px');
                    done_btn.css('width', '14px').css('height', '14px');
                    if ($item.parents('.fields__cell-inner').width() < 70) {
                        edit_btn.css('right', '-15px');
                    }
                }
            }
        });
    });
}

function init_empty_group_fields() {
    let simple_row_cells = false

    if (document.querySelector('.fields__row--simple')) {
        simple_row_cells = document.querySelector('.fields__row--simple').querySelectorAll('.fields__cell')
    }

    let displayed_cells = []

    if (simple_row_cells) {
        simple_row_cells.forEach( (cell) => {
            if (cell.style.display != 'none') {
              displayed_cells.push(cell)
            }
          })
    }

    let group_titles = document.querySelectorAll('.fields__cell-group--title')


    group_titles.forEach( (title) => {

        let i = 0

        let hide_empty_cells = (elem) => {
            if (i > displayed_cells.length - 2) { // -2 т.к. считаем от второй ячейки

              elem.style.display = 'none'

              if (elem.nextElementSibling) {
                i++
                hide_empty_cells(elem.nextElementSibling)

              } else {
                return
              }

            } else {
              if (elem.nextElementSibling) {
                i++
                hide_empty_cells(elem.nextElementSibling)
              }
            }
        }

        hide_empty_cells(title)
    })
}

var last_fast_edit_value = '';

function init_fields_link(combobox, index) {
    var $combobox = combobox;

    if ($combobox.length > 0) {
        var field_id = $combobox.attr('field_id');
        var line_id = $combobox.attr('line_id');
        var url = 'select_value.php?field=' + field_id + '&line=' + line_id;
        create_combobox($combobox);
        var input = $combobox.next().find($('.autocomplete__input'));
        var btn = input.next();
        var timeout;

        // Если есть значение в autocomplete_val
        if (input.parents('.fields__special-text').find('.fields__simple-text .autocomplete_val').length == 0) {
            input.parents('.fields__cell-inner').css('background-color', 'inherit')
            input.parents('.fields__special-text').find('.fields__fast-edit-button').css('margin-top', '0')
            input.parents('.fields__special-text').find('.fields__simple-text--link').css('display', 'none')
        }

        $combobox.next().mouseup(function (e) {
            e.stopPropagation();
        });

        var onAcClick = function () {
            autocomplete_ajax_request($combobox, url, false, true, index);
            btn.off('click', onAcClick);
        };
        input.on('click', onAcClick);
        btn.on('click', onAcClick);
        input.on('keyup', function (e) {
            var word = '&q=';
            if (input.val() !== '') {
                word += encodeURIComponent(input.val());
            }
            var url_by_word = url + word;
            if (e.keyCode === 17 || e.keyCode === 18 || e.keyCode === 16 || e.keyCode === 27 || e.keyCode === 40 || e.keyCode === 37 ||
                e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 9 || e.keyCode === 20 || e.keyCode === 13) {
                return;
            }
            clearTimeout(timeout);
            timeout = setTimeout(function () {
                autocomplete_ajax_request($combobox, url_by_word, false, true);
            }, 100);
        });
        install_autocomplete_id(input);
        add_events_autocomplete(input);
    }
}

function init_fields_date(input) {
    var $input = $(input);

    if ($input.length > 0) {
        $input.mouseup(function (e) {
            e.stopPropagation();
        });

        if ($input.val() == '') {
            $input.parents('.fields__cell-inner').css('background-color', 'inherit');
        }

        $input.focus(function () {
            last_fast_edit_value = $(this).val();
        });

        $input.change(function (e) {
            var $this = $(this);

            if ($('#ui-datepicker-div').css('overflow') !== 'hidden'
                && $this.hasClass('fields__fast-edit--datetime') && $('#ui-datepicker-div').css('display') !== 'none') {
                return false; //отключаем быстрое редактирование в режиме календаря c часами и минутами, пока открыт сам календарик
            }

            if (!isDateValid($this.val().replace(/\//g,'.')) && $this.val() != '') {
                incorrectDateFieldFormat($this);
                $input.focusout();
                return false;
            }
            $this.css('background-color', '#fff6ad');
            save_value($this.attr('field_id'), $this.attr('line_id'), $this.val());
            $input.focusout();
        });
    }
}

function init_fields_text() {
    var fields = $('.fields__fast-edit--text');

        $('.preloader__block').css({'background-color': 'transparent'});
    var arr = new Array();
    fields.each(function (i) {
        var $input = $(this);
        arr.push($input[0].offsetWidth);

    });
    var obj = {};
    for (var i = 0; i < arr.length; i++) {
        var str = arr[i];
        obj[str] = true;
    }

    var newArr = Object.keys(obj);
    arr = [];

    for (var i = 0; i < newArr.length; i++) {
        var newNum = parseInt(newArr[i]);
        newNum = Math.round(newNum / 8);
        arr.push(newNum);
    }

    var $inputWidthArr = [];
    fields.each(function (i) {
        $inputWidthArr.push(this.offsetWidth);
    });
    fields.each(function (i) {
        var $input = $(this);
        var maxLength = null;
        var $inputLength = $input.length;


        if ($inputLength > 0) {
            if ($input.css('display') !== 'none') {
                $input.css({
                    'overflow': 'hidden'
                })
            }

            if ($input.val() == '') {
                $input.parents('.fields__cell-inner').css('background-color', 'inherit')
            }

            var $inputWidth = $inputWidthArr[i];
            for (var j = 0; j < newArr.length; j++) {
                if (newArr[j] == $inputWidth) {
                    maxLength = parseInt(arr[j]);
                }
            }

            if (($input.val().length > maxLength || $input.val().includes('\n')) && !$input.prev().hasClass('fields__resize-btn')) {

              let inpTopPadding = $input.css('padding-top');
              if (inpTopPadding.includes('px')) {
                inpTopPadding = +(inpTopPadding.slice(0, -2));
              };

              let inpBotPadding = $input.css('padding-bottom');
              if (inpBotPadding.includes('px')) {
                inpBotPadding = +(inpBotPadding.slice(0, -2));
              };

              if (typeof inpTopPadding == 'number' && typeof inpBotPadding == 'number') {
                let heightResult = $input.get(0).scrollHeight - inpTopPadding - inpBotPadding;
                $input.css({'height': heightResult + 'px'});
              } else {
                $input.css({'height': $input.get(0).scrollHeight + 'px'});
              }

            } else {
                // если есть кнопка, и количество текста не помещается в одну строку, показать кнопку
                if ($input.prev().hasClass('fields__resize-btn') && ($input.val().length > maxLength)) {
                    $input[0].setAttribute("data-expandable", "true");
                    var $this = $($input.prev());
                    $this.show();
                }
            }

            $input.click(function (e) {
                var $btn = $(this).prev().find('button');

                $(this).removeClass('fields__simple-text--fixed');
                if (!$(this).parent().parent().hasClass('fields__special-text--hyperlink')) {
                  $btn.addClass('fields__resize-btn-down');
                  $btn.parent().addClass('fields__resize-btn-down');
                }
                $btn.attr('title', lang['minimize_text']);
                $btn.next().css({
                    'height': $btn.next().height()
                });
                autosize(this);
                minCustomColumnWidth($btn.parents('.fields__row'), true);
            })
            $input.mouseup(function (e) {
                e.stopPropagation();
            });
            $input.focus(function () {
                last_fast_edit_value = $(this).val();
            });
            $input.keyup(function () {
                var $this = $(this);
                if (parseInt(window_scroll) === 1) {
                    setNewHeight($this.attr('line_id'), $this.attr('field_id'));
                }
            });
            $input.blur(function () {
                var $this = $(this);
                if ($this.hasClass('fields__fast-edit--num')) {
                    //Если есть минус в значении
                    if (/-/.test($this.val())) {
                        //Если этот минус вначале
                        if ($this.val().match('-')[0] === '-') {
                            if (/[.]/.test($this.val())) {
                                $this.val($this.val().replace(/[.]/g, ','));
                            }
                            $this.val($this.val().replace(/[^\d,]/g, ''));
                            $this.val('-' + $this.val())
                        }
                    } else {
                        if (/[.]/.test($this.val())) {
                            $this.val($this.val().replace(/[.]/g, ','));
                        }
                        $this.val($this.val().replace(/[^\d,]/g, ''));
                    }

                }
                if ($this.val() !== last_fast_edit_value) {
                    if ($(this).hasClass('fields__fast-edit--html') && !isValidHtmlCode($(this).val())) {
                        jalert(lang.Invalid_html);
                    } else {
                        $this.css('background-color', '#fff6ad');
                        save_value($this.attr('field_id'), $this.attr('line_id'), $this.val());
                        $this.focusout()
                    }
                }

                 // ── auto-links: всегда возвращаем div, даже если значение не менялось ──
                if ($this.hasClass('fields__fast-edit--auto-links')) {
                    setTimeout(function () { closeAutoLinksCell($this); }, 150);
                }
            });
        }
    });

}

function init_edit_buttons(e) {
    var target = $(e.target);
    if (target.prev().length === 0) {
        target.parent().prepend("<a></a>");
    }
    var field_id = target.attr('field_id');
    var line_id = target.attr('line_id');

    target.parent('.fields__special-text').css('padding', '0')

    if (line_id && field_id) {
        var text_field = $('#fast_edit_span_' + field_id + '_' + line_id);
        var done_btn = $('#button-done-' + line_id + '-' + field_id);
        var content;
        if ((target.prev().text().length > 0 && !target.parent().hasClass('fields__special-text--html')) || target.parent().prev().length === 0) {
            content = target.prev();
        } else {
            content = target.parent().prev();
        }

        if (target.parent().parent().hasClass('fields__special-text--auto-links')) {
            var al_display = target.parent().find('.fields__simple-text--auto-links').first();
            al_display.hide();
            target.hide();
            text_field.show();
            done_btn.show();

            text_field.css('height', 'auto');                            // сброс прежней высоты
            text_field.css('height', text_field[0].scrollHeight + 'px'); // верная высота в том же кадре — без дёрганья
            autosize(text_field);                                        // дальше авто-рост при наборе

            text_field.scrollTop(0);
            text_field.focus();
            if (text_field[0].setSelectionRange) text_field[0].setSelectionRange(0, 0);
            text_field.scrollTop(0);
            target.closest('.fields__cell-inner').scrollTop(0);
            if (parseInt(window_scroll) === 1) setNewHeight(line_id, field_id);
            return;
        }

        if (text_field.length > 0 && done_btn.length > 0 && (content.length > 0 || target.parent().find($('.fields__fast-edit--combobox')).length > 0)) {
            if (target.parent().find($('.fields__fast-edit--combobox')).length > 0) {
                if (!target.parent().hasClass('fields__special-text--html')) {
                    if (target.parent().hasClass('fields__special-text--hyperlink')) {
                        text_field.val(content.text());
                    } else {
                        var select = find_select_of_autocomplete(text_field);
                        if (parseInt(select.attr('disable_link')) === 0) {
                            if(content.find($('a')).find('.show_field_slave').length > 0){
                                text_field.val(content.find($('a')).text().replace(content.find($('a')).find('.show_field_slave').text(), ''));
                            }
                            else {
                                text_field.val(content.find($('a')).text().replace(content.find($('a')).find('.show-field-slave__item--inline').text(), ''));
                            }
                        } else {
                            if(content.find($('.autocomplete_val')).find('.show_field_slave').length > 0){
                                text_field.val(content.find($('.autocomplete_val')).text().replace(content.find($('.autocomplete_val')).find('.show_field_slave').text(), ''));
                            }
                            else {
                                text_field.val(content.find($('.autocomplete_val')).text().replace(content.find($('.autocomplete_val')).find('.show-field-slave__item--inline').text(), ''));
                            }
                        }
                        if (target.parent().hasClass('fields__special-text--link')) {
                            target.parent().find($('.autocomplete')).css('display', 'flex');
                        }
                    }
                }
            } else if (!target.parent().parent().hasClass('fields__special-text--html')) {

                if (target.parent().parent().hasClass('fields__special-text--hyperlink')) {
                    text_field.val(content.text());
                } else {
                    var select = find_select_of_autocomplete(text_field);
                    if (parseInt(select.attr('disable_link')) === 0) {
                        text_field.val(content.find($('a')).text());
                    } else {
                        text_field.val(content.find($('.autocomplete_val')).text());
                    }
                    if (target.parent().parent().hasClass('fields__special-text--link')) {
                        target.parent().parent().find($('.autocomplete')).css('display', 'flex');
                    }
                }
            } else {
                text_field.val(content.html());
                text_field.css('margin-top', 0);
            }
            content.hide();
            target.hide();
            text_field.show();
            done_btn.show();
            if (target.parent().hasClass('fields__special-text--html')) {
                autosize(text_field);
                var resize_btn = content.prev();

                if (resize_btn.length > 0) {
                    resize_btn.css('opacity', '0');
                }
            }
            if (target.parent().parent().hasClass('fields__special-text--html')) {
                text_field.css('margin-top', '');
            }

            text_field.click(); //Сразу открывать список
        }
        if (parseInt(window_scroll) === 1) {
            setNewHeight(line_id, field_id);
        }
    }
}

function closeAutoLinksCell($textarea) {
    if (!$textarea || !$textarea.length) return;
    if (!$textarea.is(':visible')) return;
    var field_id = $textarea.attr('field_id');
    var line_id  = $textarea.attr('line_id');
    var $wrap     = $textarea.closest('.fields__special-text--auto-links');
    var $display  = $wrap.find('.fields__simple-text--auto-links').first();
    var $editBtn  = $('#button-edit-' + line_id + '-' + field_id);
    var $doneBtn  = $('#button-done-' + line_id + '-' + field_id);

    $display.html(linkifyMultilineText($textarea.val()));
    $textarea.hide();
    $textarea.css('height', '');
    $doneBtn.hide();
    $display.show();
    $editBtn.show().html('');

    // ← вернуть прокрутку в начало, чтобы первая строка и карандаш не уезжали вверх
    $display.scrollTop(0);
    $wrap.scrollTop(0);
    $textarea.closest('.fields__cell-inner').scrollTop(0);
}

function linkifyMultilineText(value) {
    var escaped = $('<div>').text(value || '').html();
    var urlRe = /(?<![@\w])(https?:\/\/[^\s<]+|www\.[^\s<]+)/gi;
    escaped = escaped.replace(urlRe, function (m) {
        var href = /^https?:\/\//i.test(m) ? m : 'http://' + m;
        return '<a href="' + href + '" target="_blank" title="' + m + '">' + m + '</a>';
    });
    return escaped.replace(/\r?\n/g, '<br>');
}

function init_done_buttons(e) {
    let target = $(e.target);
    let field_id = target.attr('field_id');
    let line_id = target.attr('line_id');

    if (target.parent('.fields__special-text').find('.autocomplete__input').val() != '')
        target.parent('.fields__special-text').css('padding', '5px 0')

    if (line_id && field_id) {
        let text_field = $('#fast_edit_span_' + field_id + '_' + line_id);
        let edit_btn = $('#button-edit-' + line_id + '-' + field_id);
        let content = target.parent().children().first();
        let resizeTxtField = edit_btn.prev('.fields__simple-text-resize');

        if (target.parent().parent().hasClass('fields__special-text--auto-links')) {
            var al_val = text_field.val();
            if (al_val !== text_field.attr('cur_value')) {     // подстраховка сохранения
                save_value(field_id, line_id, al_val);
                text_field.attr('cur_value', al_val);
            }
            closeAutoLinksCell(text_field);
            minCustomColumnWidth(target.parents('.fields__row'), true);
            return;
        }

        if (text_field.length > 0 && edit_btn.length > 0 && content.length > 0 || (target.parent().hasClass('fields__special-text--html') && text_field.length < 2)) {
            var val = text_field.val();
            if (target.parent().parent().hasClass('fields__special-text--hyperlink')) {
                let protochol = ''
                // Если вначале уже написан протокол
                if (!/^http/.test(val)) {
                    protochol = (val.indexOf('@') + 1) ? 'mailto:' : 'http://'
                }

                content.attr('href', protochol + val);
                content.text(val);
            } else if (target.parent().parent().hasClass('fields__special-text--html')) {
                content.html(val);
                let resize_btn = content.prev();

                if (resize_btn.length > 0) {
                    resize_btn.css('opacity', '1');
                }
            } else if (target.parent().hasClass('fields__special-text--link')) {
                target.parent().parent().find($('.autocomplete')).hide();
                edit_fields_link(text_field, content);
                val = content.html();
            }
            text_field.hide();
            target.hide();
            content.parent().children().first().show();
            edit_btn.show().html('');

            if (text_field.parent().parent().find('.show_field_slave--hidden').length > 0) text_field.parent().parent().find('.show_field_slave--hidden').first().hide();
            if (text_field.parent().parent().find('.show_field_slave--inline').length > 0) text_field.parent().parent().find('.show_field_slave--inline').first().hide();

            if (content.parent().parent().hasClass('fields__special-text--html')) {
                resizeTxtField.parent().css('width', 'auto');
                if (edit_btn.parent().prev('.link-color.fields__resize-btn').html() == '&gt;&gt;') {
                    if (resizeTxtField.text().length > 39) resizeTxtField.css('padding-top', '');
                    if (resizeTxtField.height() > 32 && resizeTxtField.height() < 40) {
                        resizeTxtField.css('padding-top', '8%');
                    }
                } else {
                    resizeTxtField.css('padding-top', '5px');
                }
            }
        }
        if (parseInt(window_scroll) === 1) {
            setNewHeight(line_id, field_id);
        }
    }
    minCustomColumnWidth(target.parents('.fields__row'), true);
}

function edit_fields_link(input, content) {
    var $input = $(input);
    var $content = $(content);

    if ($input.length > 0 && $content.length > 0) {
        var text = $input.val();
        var select = find_select_of_autocomplete($input);
        var val = select.val();
        var option = select.find($('option[value="' + val + '"]'));
        var select_val = option.text();
        var content_text = $content.find($('.autocomplete_val'));
        const htmlValue = option.html();
        let content_text_block = '';
        let is_inline = $content.find('.show-field-slave__item--inline').length > 0 && select.attr('inline') == 1 ? true : false;

        if (content_text.length === 0) {
            if (parseInt(select.attr('disable_link')) === 0) {
                var table = $content.find('.table-id').val();
                content_text_block = $('<a class="autocomplete_val">');
                content_text_block.attr('href', 'view_line2.php?table=' + table + '&line=' + val);
            }
            else {
                content_text_block = $('<span class="autocomplete_val">');
            }
            content_text_block.attr('autocomplete-val', val).html(`<span>${htmlValue}</span>`);
            let wrapper = $('<span class="sub-slave_fields">').append(content_text_block);
            $content.append(wrapper);
        }

        if (select_val !== content_text.text() && content_text.length > 0 && option.length > 0 && val != lang.add_new_record) {
            if (parseInt(select.attr('disable_link')) === 0) {
                var href = content_text.attr('href');
                var table = getAttrVars(href)['table'];
                var new_href = 'view_line2.php?table=' + table + '&line=' + val;
                content_text.attr('href', new_href);
            }
            content_text.html(`<span class='main_value'>${htmlValue}</span>`).attr('autocomplete-val', val);
            let additional_attrs = $content.find($('.show_field_slave'));

            if (additional_attrs.length > 0) {
                additional_attrs.html('');
                if (option.val()) {
                    const select_data = option.attr('data');
                    if (select_data) {
                        const select_data_arr = select_data.split('</br>');
                        const frag = $(document.createDocumentFragment());
                        const imgIdent = '<img';

                        select_data_arr.forEach(function (val, idx) {
                            if (idx === 0 && val.indexOf(imgIdent) > -1) {
                                const imgCount = val.split(imgIdent).length - 1;

                                if (imgCount > 1) {
                                    let images = val.split('>');
                                    const firstImg = images[0].indexOf('<') !== -1 ? images[0].slice(images[0].indexOf('<')) + '>' : images[0] + '>';
                                    const imgVal = images.slice(1).join('>');

                                    content_text.html(firstImg + text);
                                    let additional_attr = $(`<span class="show-field-slave__item${is_inline ? '--inline' : ''}">`).append(imgVal);
                                    frag.append(additional_attr);
                                } else {
                                    content_text.html((val.indexOf('<') !== -1 ? val.slice(val.indexOf('<')): val) + `<span class="main_value">${text}</span>`);
                                }
                            } else {
                                let additional_attr = $(`<span class="show-field-slave__item${is_inline ? '--inline' : ''}">`).append(val);
                                frag.append(additional_attr);
                            }
                        });
                        additional_attrs.append(frag);
                    }
                }
            } else {
                if (option.val()) {
                    //$content.find('span.autocomplete_val').remove();
                    $content.css('white-space', 'pre-line');
                    const select_data = option.attr('data');
                    content_text_block = $content.find('.autocomplete_val');

                    if (select_data) {
                        const select_data_arr = select_data.split('</br>');
                        const frag = is_inline ? $('<span class="show-field-slave__item--inline"></span>') : $('<span class="show_field_slave"></span>');
                        const imgIdent = '<img';

                        content_text_block.html('');
                        content_text_block.append(is_inline && htmlValue.indexOf('<span class="main_value"') === -1 ? `<span class="main_value"><span class="main_value_title">${htmlValue}</span></span>` : htmlValue);
                        select_data_arr.forEach(function (item, idx) {
                            if (idx === 0 && item.indexOf(imgIdent) > -1) {
                                const imgCount = val.split(imgIdent).length - 1;

                                if (imgCount > 1) {
                                    let images = val.split('>');
                                    const firstImg = images[0].indexOf('<') !== -1 ? images[0].slice(images[0].indexOf('<')) + '>' : images[0] + '>';
                                    const imgVal = images.slice(1).join('>');

                                    content_text.html(firstImg + text);
                                    if(is_inline){
                                        frag.append(" " + imgVal);
                                    }
                                    else {
                                        let additional_attr = $(`<span class="show-field-slave__item${is_inline ? '--inline' : ''}">`).append(imgVal);
                                        frag.append(additional_attr);
                                    }
                                } else {
                                    content_text.html((item.indexOf('<') !== -1 ? item.slice(item.indexOf('<')): item) + `<span class="main_value">${text}</span>`);
                                }
                            } else {
                                if(is_inline){
                                    frag.append(" " + item);
                                }
                                else {
                                    let additional_attr = $(`<span class="show-field-slave__item${is_inline ? '--inline' : ''}">`).html(item);
                                    frag.append(additional_attr);
                                }
                            }
                        });
                        if(is_inline){
                            content_text.siblings('.show-field-slave__item--inline').remove()
                            content_text.find('.main_value').append(frag);
                        }
                        else {
                            // срабатывает один раз при редактировании в таблицы
                            content_text_block.next('.show-field-slave__item--inline').remove();
                            content_text_block.after(frag);
                        }
                        //$content.find('.autocomplete_val').remove();
                    }
                    //$content.prepend(content_text_block);
                }
            }
        } else {
            let additional_attrs = $content.find($('.show_field_slave'));
            if (additional_attrs.length > 0) {
                additional_attrs.html('');
                if (option.val()) {
                    const select_data = option.attr('data');
                    if (select_data) {
                        const select_data_arr = select_data.split('</br>');
                        const frag = $(document.createDocumentFragment());
                        const imgIdent = '<img';

                        select_data_arr.forEach(function (val, idx) {
                            if (idx === 0 && val.indexOf(imgIdent) > -1) {
                                const imgCount = val.split(imgIdent).length - 1;

                                if (imgCount > 1) {
                                    let images = val.split('>');
                                    const firstImg = images[0].indexOf('<') !== -1 ? images[0].slice(images[0].indexOf('<')) + '>' : images[0] + '>';
                                    const imgVal = images.slice(1).join('>');

                                    content_text.html(firstImg + text);
                                    let additional_attr = $(`<span class="show-field-slave__item${is_inline ? '--inline' : ''}">`).append(imgVal);
                                    frag.append(additional_attr);
                                } else {
                                    content_text.html((val.indexOf('<') !== -1 ? val.slice(val.indexOf('<')): val) + `<span class="main_value">${text}</span>`);
                                }
                            } else {
                                let additional_attr = $(`<span class="show-field-slave__item${is_inline ? '--inline' : ''}">`).append(val);
                                frag.append(additional_attr);
                            }
                        });
                        additional_attrs.append(frag);
                    }
                }
            } else {
                if (option.val()) {
                    //$content.find('span.autocomplete_val').remove();

                    const select_data = option.attr('data');
                    content_text_block = $content.find('.autocomplete_val');

                    if (select_data) {
                        const select_data_arr = select_data.split('</br>');
                        const frag = is_inline ? $('<span class="show-field-slave__item--inline"></span>') : $('<span class="show_field_slave"></span>');
                        const imgIdent = '<img';

                        // Очистка содержимого .autocomplete_val
                        content_text_block.html('');
                        content_text_block.append(is_inline && htmlValue.indexOf('<span class="main_value"') === -1 ? `<span class="main_value">${htmlValue}</span>` : htmlValue);
                        select_data_arr.forEach(function (item, idx) {
                            if (idx === 0 && item.indexOf(imgIdent) > -1) {
                                const imgCount = val.split(imgIdent).length - 1;

                                if (imgCount > 1) {
                                    let images = val.split('>');
                                    const firstImg = images[0].indexOf('<') !== -1 ? images[0].slice(images[0].indexOf('<')) + '>' : images[0] + '>';
                                    const imgVal = images.slice(1).join('>');

                                    content_text_block.html(firstImg + text);
                                    if(is_inline){
                                        frag.append(" " + imgVal);
                                    }
                                    else {
                                        let additional_attr = $(`<span class="show-field-slave__item${is_inline ? '--inline' : ''}">`).append(imgVal);
                                        frag.append(additional_attr);
                                    }
                                } else {
                                    content_text_block.html((item.indexOf('<') !== -1 ? item.slice(item.indexOf('<')): item) + `<span class="main_value">${text}</span>`);
                                }
                            } else {
                                if(is_inline){
                                    frag.append(" " + item);
                                }
                                else {
                                    let additional_attr = $(`<span class="show-field-slave__item${is_inline ? '--inline' : ''}">`).html(item);
                                    frag.append(additional_attr);
                                }
                            }
                        });
                        if(is_inline){
                            content_text_block.find('.main_value').append(frag);
                        }
                        else {
                            content_text_block.after(frag);
                        }
                        $content.find('div.autocomplete_val').remove();
                    }
                    $content.find('.sub-slave_fields').prepend(content_text_block);
                }
            }
        }
    }
}

/**
 * Метод, возвращающий id группировок таблицы
 * @returns {{}}
 */
function get_groups_fields() {
    var result = {};
    var group_rows = $('.fields__row--group');

    if (group_rows.length > 0) {
        group_rows.each(function (i) {
            var array = [];
            result[i + 1] = get_id_from_next_row($(this), array);
        });
    }

    return result;
}

/**
 * Метод, возвращающий массив id строк в одной группировке
 * @param row Строка таблицы
 * @param array {Array} Массив который нужно заполнить
 * @returns {Array}
 */
function get_id_from_next_row(row, array) {
    var next = row.next();

    if (next.length > 0) {
        if (!next.hasClass('fields__row--group') && next.hasClass('fields__row--simple')) {
            var id = next.attr('id').replace(/\D+/g, "");

            array.push(id);
            get_id_from_next_row(next, array);
        }
    }

    return array;
}

/**
 * Метод, возвращающий массив id записей
 * @returns {Array}
 */
function get_lines_id() {
    var result = [];
    var rows = $('.fields__row--simple');

    if (rows.length > 0) {
        rows.each(function () {
            var id = $(this).attr('id').replace(/\D+/g, "");

            result.push(id);
        });
    }

    return result;
}

function init_date() {
    $("#schedule_span_wrapper .datetimepicker").datetimepicker({
        showOn: "button",
        dateFormat: lang.date_js_format,
        timeFormat: "HH:mm",
        showAlways: true,
        buttonImage: "images/calbtn.png",
        buttonImageOnly: true,
        buttonText: lang.Calendar,
        showAnim: (('\v' == 'v') ? "" : "show")  // в ie не включаем анимацию, тормозит
    }).attr('placeholder', lang.datetime_placeholder);

    $('.fields__fast-edit--date').datepicker({
        showOn: "button",
        dateFormat: lang.date_js_format,
        showAlways: true,
        buttonImage: "images/calbtn.png",
        buttonImageOnly: true,
        buttonText: lang.Calendar,
        showAnim: (('\v' == 'v') ? "" : "show")  // в ie не включаем анимацию, тормозит
    }).attr('placeholder', lang.date_placeholder);

    $('.fields__fast-edit--datetime').datetimepicker({
        showOn: "button",
        dateFormat: lang.date_js_format,
        timeFormat: "HH:mm",
        showAlways: true,
        buttonImage: "images/calbtn.png",
        buttonImageOnly: true,
        buttonText: lang.Calendar,
        showAnim: (('\v' == 'v') ? "" : "show")  // в ie не включаем анимацию, тормозит
    }).attr('placeholder', lang.datetime_placeholder);

    $('.fields__date-field').mouseup(function (e) {
        e.stopPropagation();
    })
}

/**
 * Инициализация обработчика шифта по чекбоксам
 */
function init_shift_checkbox() {
    var checkboxes = $('.fields__row--simple').find('.custom-checkbox__wrap');
    checkboxes.each(function (index, checkbox) {
        $(checkbox).on("click contextmenu", function (event) {
            var checkedFieldId = $(this).prev().attr('value');
            var _all_lines_pp = all_lines_pp.map(function (item) {
                return +(item);
            });
            var checkedFieldKey = _all_lines_pp.indexOf(intval(checkedFieldId));
            if (event.shiftKey) {
                $('#sel' + checkedFieldId).prop('checked', !$('#sel' + checkedFieldId).prop('checked'));
                $('#sel' + checkedFieldId)[0].dispatchEvent(new Event('change'));
                if (checkedFieldKey > globalCheckShiftStatus) {
                    for (var i = globalCheckShiftStatus; i != checkedFieldKey; i++) {
                        $('#sel' + all_lines_pp[i]).prop('checked', +$('#sel' + checkedFieldId).prop('checked'));
                        if(+$('#sel' + checkedFieldId).prop('checked'));
                          $('#sel' + all_lines_pp[i])[0].dispatchEvent(new Event('change'))
                        onMouseOut(all_lines_pp[i]);
                    }
                }
                else {
                    for (var i = globalCheckShiftStatus; i != checkedFieldKey; i--) {
                        $('#sel' + all_lines_pp[i]).prop('checked', +$('#sel' + checkedFieldId).prop('checked'));
                        if(+$('#sel' + checkedFieldId).prop('checked'));
                          $('#sel' + all_lines_pp[i])[0].dispatchEvent(new Event('change'))
                        onMouseOut(all_lines_pp[i]);
                    }
                }
            }
            globalCheckShiftStatus = checkedFieldKey;
        });
    });
}
// Нигде не вызывается TODO: Разобраться почему и удалить
function get_value_control(field, term, num, k) {
    if (typeof field !== 'undefined') {
        var control = "";
        if (field.input_value.substring(0, 7) == "<option" && !(field.type_field == 4 && field.mult_value == 0 && (term == " LIKE " || term == " NOT LIKE ")))
            control = "<select class='form-control form-control-160' name='set_cond[" + num + "][value" + k + "]' id='cond_value" + k + "_" + num + "' onkeyup=\"if ((event.keyCode == 0xA)||(event.keyCode == 0xD)) document.getElementById('ext_search_form').submit();\">" + field.input_value + "</select>";
        else if (field.type_field == 2 || field.type_field == 12)
            control = "<input class='form-control form-control-160' type=text name='set_cond[" + num + "][value" + k + "]' id='cond_value" + k + "_" + num + "' " + (!k ? "onchange=\"if (!document.getElementById('cond_value2_" + num + "').value) if (this.value.substr(11,5)=='00:00') document.getElementById('cond_value2_" + num + "').value = this.value.substr(0,11)+'23:59'; else document.getElementById('cond_value2_" + num + "').value = this.value;\"" : "") + " onkeyup=\"if ((event.keyCode == 0xA)||(event.keyCode == 0xD)) document.getElementById('ext_search_form').submit();\">";
        else if (field.type_field == 5) {
            if (term == ' LIKE ' || term == ' NOT LIKE ') control = "<input class='form-control form-control-160' type=text name='set_cond[" + num + "][value" + k + "]' id='cond_value" + k + "_" + num + "' onkeyup=\"if ((event.keyCode == 0xA)||(event.keyCode == 0xD)) document.getElementById('ext_search_form').submit();\">";
            else control = "<select type=text id='cond_value" + k + "_" + num + "' class='combobox' row_k='" + k + "'></select>";
        }
        else
            control = "<input class='form-control form-control-160' type=text name='set_cond[" + num + "][value" + k + "]' id='cond_value" + k + "_" + num + "' onkeyup=\"if ((event.keyCode == 0xA)||(event.keyCode == 0xD)) document.getElementById('ext_search_form').submit();\">";
        return control;
    }
}

// ============ ДИАЛОГОВОЕ ОКНО ШАБЛОНОВ =================

function dial_form(op, id, type, warning, ignore, scheduled) {

    if (window.scheduled === undefined) {
        
    }
    else {
        if (scheduled != 1 || window.scheduled !== undefined) {

            acc = prev_dial_form(op, id);
            all_sels = get_all_checked_sel();

            if (acc > 0 && !ignore && Object.keys(all_sels).length > 0 && id != 100500) {
                $("#jalert").dialog('close');
                if (acc == 2) jalert(lang.Any_forms_not_access_rules);
                else if (acc == 1) jconfirm(lang.Forms_not_access_rules, function () {
                    $('#jalert').dialog('close');
                    dial_form(op, id, type, warning, 1);
                }, function () {
                    $('#jalert').dialog('close');
                });
                return false;
            }
        }
    }
    if (warning) {
        jalert(warning);
        return;
    }

    if (op == "search") {
        document.getElementById('search_template_id').value = id;
        document.getElementById('search_template_form').submit();
        return;
    }

    var form_sel = document.getElementById('form_sel'),
        form_type = document.getElementById('form_type'),
        sel_records = document.getElementById('sel_records'),
        last_target = sel_records.target;

    $('#dialog_' + op).dialog('close');

    //стандартная печать выбранных записей
    if (op == 'print' && type == 0 && id == 100500) {

        if (window_scroll == 1)
            alert(lang.warning_standard_template);
        all_elem = ($("form#sel_records :checkbox"));
        var count_all_items = all_elem.length;
        check_elem = ($("form#sel_records :checkbox:checked"));
        //если есть выбранные эелменты, печатаем их
        //в противном случае печатаем все на странице
        if (0 in check_elem) {
            var count_items = 0;
            for (i = 1; i < all_elem.length; i++) {
                check_info = all_elem[i];
                check_val = check_info.value;
                check_status = $("#sel" + check_val).prop("checked");
                if (!check_status) {
                    $("#tr" + check_val).addClass('no_print');
                    count_items++;
                } else {
                    $("#tr" + check_val).removeClass('no_print');
                }
            }
            $("#line_count").addClass('no_print');
            count_elem = count_all_items - count_items - 1;
            $("#line_count_print").html(lang.Selected_lines + ": " + count_elem);

            $("#act_arc_del").addClass('no_print');
            $("img.settings_t").addClass('no_print');
            $("td.total").eq(0).addClass('no_print');
            $(".pages").addClass('no_print');
            $("#footback_div_id").addClass('no_print');
            //$(".group_field_text").addClass('no_print');

            var check_boxes = $("div [id*='chk_div']");
            for (var j = 0; j < check_boxes.length; j++)
                check_boxes[j].setAttribute("class", "no_print");

            $("#f_row_virtual").addClass('no_print');
            window.print();
            return;
        }
        else {
            jalert(lang.warning_zero_lines);
            return false;
        }


    }


    if (id == -2) {
        var obj = {};
        obj.modal = true;
        obj.title = '<table cellpadding="0" cellspacing="0"><tr><td height="10"><p style="font-size:16px; font-weight:normal; color:#999; margin-top:3px; padding-left:8px;"> Отправка свободного шаблона ';
        if (op == 'sms') obj.title += 'смс';
        else obj.title += 'рассылки';
        obj.title += '</p></td></tr></table>';
        obj.width = 450;
        obj.draggable = false;
        obj.resizable = false;
        obj.open = function (event, ui) {
            $(this).parent().find('.ui-dialog-title').html(obj.title);
        };
        $("#dialog_free_" + op).dialog(obj);
        $('.ui-icon-closethick').remove();
        $('.ui-button-icon-space').remove();
        $('.ui-dialog-titlebar-close').removeClass('ui-button ui-corner-all ui-widget ui-button-icon-only');
        $('.ui-dialog-titlebar-close').text('');
        overlayHandler();
        $(window).on('resize', overlayHandler);
        $("div.ui-dialog").focus();
    } else {
        if (scheduled == 1) {
            var obj = {};
            obj.modal = true;
            var autocall = (op == 'autocall') ? 'обзвона' : 'отправки';
            obj.title = '<table cellpadding="0" cellspacing="0"><tr><td height="10"><p style="font-size:16px; font-weight:normal; color:#999; margin-top:3px; padding-left:8px;"> Выберите дату и время ' + autocall + '<span id=""></span> ';
            obj.title += '</p></td></tr></table>';
            obj.width = 450;
            obj.draggable = false;
            obj.resizable = false;
            obj.open = function (event, ui) {
                $(this).parent().find('.ui-dialog-title').html(obj.title);
            };
            $("#dialog_date").dialog(obj);
            $('.ui-icon-closethick').remove();
            $('.ui-button-icon-space').remove();
            $('.ui-dialog-titlebar-close').removeClass('ui-button ui-corner-all ui-widget ui-button-icon-only');
            $('.ui-dialog-titlebar-close').text('');
            overlayHandler();
            $(window).on('resize', overlayHandler);
            $("div.ui-dialog").focus();
            form_sel.value = id;
            form_type.value = type;
            var now_date = new Date();
            var str = (now_date.getDate() < 10 ? '0' + now_date.getDate().toString() : now_date.getDate().toString()) + '.' + (now_date.getMonth() + 1 < 10 ? '0' + (now_date.getMonth() + 1).toString() : (now_date.getMonth() + 1).toString()) + '.' + now_date.getFullYear().toString() + ' ' + (now_date.getHours() < 10 ? '0' + now_date.getHours().toString() : now_date.getHours().toString()) + ':' + (now_date.getMinutes() < 10 ? '0' + now_date.getMinutes().toString() : now_date.getMinutes().toString());
            document.getElementById('schedule_send_span').value = str;
        } else {
            if (id == -3) {
                if (op == 'send') {
                    document.getElementById('form_subj_send').value = document.getElementById('free_subj_send').value;
                    document.getElementById('form_text_send').value = document.getElementById('free_text_send').value;
                }
                if (op == 'sms') {
                    document.getElementById('form_text_sms').value = document.getElementById('free_text_sms').value;
                }
            }
            if (scheduled != 0 && scheduled !== undefined) {
                document.getElementById('form_scheduled_time').value = scheduled;
            } else {
                form_sel.value = id;
                form_type.value = type;
            }

            if (op == "print" && (type == -1 || type == 1 || type == 2))
                sel_records.target = "_blank";
            else
                sel_records.target = "_self";

            sel_records.submit();

            form_sel.value = "";
            form_type.value = "";
            sel_records.target = last_target;
        }
    }

}

// Отображение/скрытие расширенного поиска
function display_ext_search() {
    if (document.getElementById('ext_search_form').style.display === 'none') {
        document.getElementById('ext_search_form').style.display = '';
        document.getElementById('ext_search_icon').className = 'ext_search_close';
        if (document.getElementById('fix_search_form')) document.getElementById('fix_search_form').style.display = 'none';
        var search_combobox = $('.fields__search-edit .combobox');
        create_combobox(search_combobox);
    }
    else {
        document.getElementById('ext_search_form').style.display = 'none';
        document.getElementById('ext_search_icon').className = 'ext_search_open';
        if (document.getElementById('fix_search_form')) document.getElementById('fix_search_form').style.display = '';
    }
}

// Быстрый поиск
function start_fast_search() {
    if ((document.getElementById('fast_search_value').value == '') || (document.getElementById('fast_search_value').value == lang.Search)) {
        jalert(lang.alert_enter_search_text);
    } else if (checkInputValueForScript('fast_search_value')) {
        document.getElementById('fast_search_form').submit();
    }
}

function select_all() {
    var m_checked = 0;
    if (document.getElementById('sel_all').checked)
        m_checked = 1;

    var lid;
    for (var i = 0; i < all_lines_pp.length; i++) {
        lid = all_lines_pp[i];
        if (!lid) continue;
        document.getElementById('sel' + lid).checked = m_checked;
        $('#tr' + lid).find($('.fields__cell')).each(function (cell_index) {
            if (m_checked) {
                if (cell_index === 0) {
                    $(this).find($('div')).css('background-color', '#f4f0d1');
                }
                $(this).css('background-color', '#f4f0d1');
            } else {
                if (cell_index === 0) {
                    $(this).find($('div')).css('background-color', prevColor[lid][$(this).attr('field_id')]);
                }
                $(this).css('background-color', prevColor[lid][$(this).attr('field_id')]);
            }
        });
    }
}

function select_group(group_pp) {
    var m_checked = 0;
    if (document.getElementById('sel_group_' + group_pp).checked) m_checked = 1;
    var group_lines = groups_fields[group_pp];
    for (var i = 0; i < group_lines.length; i++) {
        var lid = group_lines[i];
        if (!lid) continue;
        document.getElementById('sel' + lid).checked = m_checked;
        $('#tr' + lid).find($('.fields__cell')).each(function (cell_index) {
            if (m_checked) {
                if (cell_index === 0) {
                    $(this).find($('div')).css('background-color', '#f4f0d1');
                }
                $(this).css('background-color', '#f4f0d1');
            } else {
                if (cell_index === 0) {
                    $(this).find($('div')).css('background-color', prevColor[lid][$(this).attr('field_id')]);
                }
                $(this).css('background-color', prevColor[lid][$(this).attr('field_id')]);
            }
        });
    }
}

function open_dialog(mode) {
    var obj = {};
    obj.modal = true;
    var mode_txt;
    if (mode == 'print') mode_txt = lang.select_print_template;
    else if (mode == 'send') mode_txt = lang.select_mail_template;
    else if (mode == 'sms') mode_txt = lang.select_sms_template;
    else if (mode == 'msg') mode_txt = lang.select_msg_template;
    else if (mode == 'search') mode_txt = lang.select_search_template;
    else if (mode == 'autocall') mode_txt = lang.select_autocall_template;

    if (mode == 'print' || mode == 'send' || mode == 'sms' || mode == 'msg') {
      obj.title = '<table cellpadding="0" cellspacing="0"><tr><td height="10"><p style="font-size:16px; font-weight:normal; color:#999; margin-top:3px; padding-left:18px;"> ' + mode_txt + '</p></td><td>' + (user.developer_mode ? '<a style="text-decoration:none; " href="forms.php?table=' + table_id + '&mode=' + mode + '&admin" target="_blank"><img alt="" src="images/settings_a.gif" name="d_par' + mode + '" border="0" onMouseOver="window.document.images[\'d_par' + mode + '\'].src=\'images/settings_b.gif\';" onMouseOut="window.document.images[\'d_par' + mode + '\'].src=\'images/settings_a.gif\';" style="margin-left:10px; margin-top:-7px;"/></a>' : '') + '</td></tr></table>';
    } else if (mode == 'search') {
      obj.title = '<table cellpadding="0" cellspacing="0"><tr><td height="10"><p style="font-size:16px; font-weight:normal; color:#999; margin-top:3px; padding-left:18px;"> ' + mode_txt + '</p></td><td><a style="text-decoration:none; " href="search_templates.php?table=' + table_id + '" target="_blank"><img alt="" src="images/settings_a.gif" name="d_par' + mode + '" border="0" onMouseOver="window.document.images[\'d_par' + mode + '\'].src=\'images/settings_b.gif\';" onMouseOut="window.document.images[\'d_par' + mode + '\'].src=\'images/settings_a.gif\';" style="margin-left:10px; margin-top:-7px;"/></a></td></tr></table>';
    } else {
      obj.title = '<table cellpadding="0" cellspacing="0"><tr><td height="10"><p style="font-size:16px; font-weight:normal; color:#999; margin-top:3px; padding-left:8px;"> ' + mode_txt + '</p></td></tr></table>';
    }
    obj.width = 350;
    obj.draggable = false;
    obj.resizable = false;
    obj.open = function (event, ui) {
        $(this).parent().find('.ui-dialog-title').html(obj.title);
    };
    $("#dialog_" + mode).dialog(obj);
    $('.ui-icon-closethick').remove();
    $('.ui-button-icon-space').remove();
    $('.ui-dialog-titlebar-close').removeClass('ui-button ui-corner-all ui-widget ui-button-icon-only');
    $('.ui-dialog-titlebar-close').text('');
    overlayHandler();
    $(window).on('resize', overlayHandler);
    $("div.ui-dialog").focus();
    return false;
}

function get_all_checked_sel() {
    var sels = {};
    $(".user_table :checked").each(function () {
        //по какой то причине попадают записи без ключа, что приводит к неправильному количеству выбранных записей
        //по этому вставляем проверку на наличие ключа
        if (this.id)
            sels[this.id] = $(this).val();
    });
    //когда ставим галочку выбрать все, она попадает в смисок выбранных
    //ее нужно выпилить, что б не вываливался алерт
    if (sels.sel_all)
        delete sels.sel_all;

    for (var key in sels) {
        var val = sels[key];
        if (val == 'on')
            delete sels[key];
    }

    return sels;
}

function insertTextAtCursor(text) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            var t_node = document.createElement("br");
            range.insertNode(t_node);
            range.setEndAfter(t_node);
            range.setStartAfter(t_node);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.pasteHTML(text);
        range.moveEnd('character', 0);
        range.select();

    }
}

function set_timed_focus_p(el) {
    timed_focus_el.focus();
}

// Клик мышкой по ячейке
function onTableMouseUp(event, line_id) {
    // Не пропускаем событие выше таблицы
    if (window.event) {
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }
    else {
        event.stopPropagation();
        event.cancelBubble = true;
        event.returnValue = false;
    }
    // Атрибут не открывать сроку
    if (dont_open_view > 0) {
        dont_open_view--;
        return false;
    }
    if ((document.selection && document.selection.createRange() && trim(document.selection.createRange().text) != '') ||
        (window.getSelection && window.getSelection() && trim(window.getSelection()) != '')
    ) { // Есть выделенный текст не открывать строку
        dont_open_view = 1;
        return false;
    }
    var t1;
    if (event.button > 1) {
        dont_open_view = 1;
        return false;
    }
    if (event.target) t1 = event.target;
    if (event.srcElement) t1 = event.srcElement;
    if (biz_proc) {
        if (biz_proc['action'] == 'line_enter') {
            allow_out_bizproc = 1;
        }
    }

    if (t1.nodeName != 'A' && !t1.className.includes('select2')) {
        var rel_table_link = (rel_table !== '') ? '&rel_table=' + rel_table : '',
            rel_line_link = (rel_table !== '') ? '&rel_line=' + rel_line : '',
            rel_field_link = (rel_table !== '') ? '&rel_field=' + rel_field : '',
            filters = '',
            archive_link = (parseInt(archive) !== 0) ? '&archive' : '',
            deleted_link = (parseInt(deleted) !== 0) ? '&deleted' : '',
            all_rec_link = (parseInt(all_rec) !== 0) ? '&all' : '',
            page_link = (parseInt(page) !== 0) ? '&page=' + page : '',
            biz_proc_link = '';

        if (parseInt(all_filters_on) !== 0) {
            filters = '&all_filters_on';
        } else if (filter_id && parseInt(filter_id) !== 0) {
            filters = '&filter=' + filter_id;
        }

        if (biz_proc) {
            if (biz_proc['action'] == 'line_enter') {
                var step = (biz_proc['autostep']) ? biz_proc['num'] + 1 : biz_proc['num'] + '&done';
                biz_proc_link = '&bizproc=' + cur_bizproc.id + '&step=' + step
            }
        }

        location.href = 'view_line' + config_vlm + '.php?table=' + table_id + rel_table_link + rel_line_link + rel_field_link + filters + archive_link + deleted_link + all_rec_link + page_link + '&line=' + line_id + biz_proc_link;
    }
    return false;
}

function checkAllPseudoSelect(elem,id){
    let search_text = ' ';
    if(elem.checked==true){
        $("#pseudo_select_options" + id + " input:checkbox").each(function (id) {
            if(id>0){
                this.checked = true;
                search_text +=`${this.value},`;
            }
        });
        search_text=search_text.slice(0,-1)
        document.getElementById("pseudo_select_text" + id).innerHTML = search_text;
        document.getElementById("fix_search_mult" + id).value = search_text;
    }else{
        $("#pseudo_select_options" + id + " input:checkbox").each(function () {
            this.checked = false;
        });
        document.getElementById("pseudo_select_text" + id).innerHTML = "&nbsp;";
        document.getElementById("fix_search_mult" + id).value = " ";
    }
    document.getElementById('fix_search_form').submit();
}

// Заполнение текста псевдо-селекта
function completePseudoSelect(fieldId, isLink) {
    var search_text = "";
    var search_count = 0;

    $("#pseudo_select_options" + fieldId + " input:checkbox").each(function () {
        if (this.checked) {
            if (search_text != "") search_text += ", ";
            search_text += $("[for=" + this.id + "]").html();
            search_count += 1;
        }
        else if (isLink != undefined) {
            $("[for=" + this.id + "]").parent().remove();
        }
    });

    if (search_text.length > 33)
        search_text = search_text.substring(0, 33);
    if (search_text != "")
        document.getElementById("fix_search_mult" + fieldId).value = "exist";
    else
        document.getElementById("fix_search_mult" + fieldId).value = "";

    if (isLink == undefined) {
        if (search_text == "")
            search_text = "&nbsp;";
        document.getElementById("pseudo_select_text" + fieldId).innerHTML = search_text;
    }
    else {
        if (search_count == 0) {
            document.getElementById("pseudo_select_options" + fieldId).style.display = "none";
            document.getElementById("mult_link_count" + fieldId).innerHTML = "";
            document.getElementById("fix_search_" + fieldId).value = "";
            document.getElementById("fix_search_" + fieldId + "_link_value").value = "";
        }
        else
            document.getElementById("mult_link_count" + fieldId).innerHTML = "+" + search_count;
    }
    var table_newdata = init_data();
    if (parseInt(table_newdata['fix_search_submit']) === 0) {
        document.getElementById('fix_search_form').submit();
    }
}

var select_val_index = 0;
// Выбор значения поля связи для мультипоиска
function addSelectVal(e) {
    var target = $(e.target);
    var combobox = target.parent().prev();
    var data_val = combobox.val();
    var fieldId = target.attr('field_id');
    var val = target.val();
    if (val == '') {
        return;
    }
    if (document.getElementById("fix_search_ch" + fieldId + "_" + data_val)) {
        return;
    }
    var oneOption = "<div class='pseudo_select__wrap pseudo_select__wrap--multi-link'><input style='margin: 0 5px;' type='checkbox' name='fix_search[" + fieldId + "][value][]' checked value='" + val + "' id='fix_search_ch" + fieldId + "_" + data_val + "' onclick='completePseudoSelect(" + fieldId + ", 1); event.cancelBubble=true' />";
    oneOption += "<label for='fix_search_ch" + fieldId + "_" + data_val + "' onclick='completePseudoSelect(" + fieldId + ", 1); event.cancelBubble=true'>" + val + "<br /><input type='hidden' name='fix_search[" + fieldId + "][value_link][]' value='" + data_val + "' /></label></div>";
    $("#pseudo_select_options" + fieldId).append(oneOption);
    completePseudoSelect(fieldId, 1);
}

// Сохранить шаблон поиска
function saveAsTemplate(step) {
    if (step == 1)
        jconfirm("<div style='text-align: center'>" + lang.Template_name + ":<br /><br /><input class='form-control form-control-160' type='text' size='50' id='search_template_name' onchange=\"document.getElementById('save_as_template').value = this.value\"/></div>", function () {
            saveAsTemplate(2);
        }, function () {
        });
    else {
        let templateName = document.getElementById("save_as_template").value;

        if (templateName == "")
            jalert(lang.Enter_temp_name);
        else
            document.getElementById('ext_search_form').submit();
    }
}

// Установка фокуса на элемент
function set_timed_focus(el) {
    timed_focus_el = el;
    window.setTimeout(set_timed_focus_p, 100);
}


function on_mouse_up_global() {
    if (dont_open_view > 0) {
        dont_open_view--;
    }
}

/**
 * Метод, инициализирующий дату в фикс. поиске
 */
function init_fix_search_date() {
    var datepickers = $('.fix-search__date');
    var datetimepickers = $('.fix-search__datetime');

    if (datepickers.length > 0) {
        datepickers.each(function () {
            $(this).datepicker({
                showOn: 'button',
                dateFormat: lang.date_js_format,
                showAlways: true,
                buttonImage: 'images/calbtn.png',
                buttonImageOnly: true,
                buttonText: lang.Calendar,
                showAnim: (('\v' == 'v') ? '' : 'show')
            }).attr('placeholder', lang.date_placeholder);
        });
    }

    if (datetimepickers.length > 0) {
        datetimepickers.each(function () {
            $(this).datetimepicker({
                showOn: 'button',
                dateFormat: lang.date_js_format,
                timeFormat: "HH:mm",
                showAlways: true,
                buttonImage: 'images/calbtn.png',
                buttonImageOnly: true,
                buttonText: lang.Calendar,
                showAnim: (('\v' == 'v') ? '' : 'show')
            }).attr('placeholder', lang.datetime_placeholder);
        });
    }
}

/**
 * Метод, инициализирующий связи в фикс поиске
 */
function init_fix_search_link() {
    set_events_to_ac();
    var links = $('#fix_search_form .autocomplete__input');
    links.each(function (index, obj) {
        var select = find_select_of_autocomplete($(obj));
        var field_id = select.attr('field_id');
        var autocomplete = $(obj);
        var autocomplete_btn = $(obj).next();
        var parent_link = select.attr('fixed-search-parent-field');
        var timeout;
        install_autocomplete_value(select);

        var fixedSearchOnAutocompleteClick = function () { };
        var fixedSearchBtnOnAutocompleteClick = function () { };

        setFixedSearchLinkAttr(select);

        if (parent_link && parent_link !== '') {
            $(obj).on('keyup', function (e) {
                fixed_search_find_link_fields(select);
                var word = '&q=';
                if (autocomplete.val() !== '') {
                    word += encodeURIComponent(autocomplete.val());
                }
                var filter_value = $(this).parent().prev().attr('fixed-search-parent-field');
                var parent_field = $("#fix_search_" + filter_value);
                var parent_prev_val = $(parent_field).next().find('.autocomplete__input').val();
                var parent_select_val;
                if (parent_field.val() === null || parent_field.val() === 'undefined' || parent_field.val() === '') {
                    parent_select_val = parent_field.attr('ac_value');
                } else {
                    parent_select_val = parent_field.val();
                }

                if ((parent_prev_val === null || parent_prev_val === undefined || parent_prev_val === '') && (word === '&q=')) {
                    word = '';
                    parent_select_val = undefined;
                } else if (parent_prev_val === null || parent_prev_val === undefined || parent_prev_val === '') {
                    parent_select_val = undefined;
                }

                var url_by_word = 'select_value.php?field=' + $(this).parent().prev().attr('field_id') + '&filter_value=' + parent_select_val + word;
                if (e.keyCode === 17 || e.keyCode === 18 || e.keyCode === 16 || e.keyCode === 27 || e.keyCode === 40 || e.keyCode === 37 ||
                    e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 9 || e.keyCode === 20 || e.keyCode === 13) {
                    return;
                }
                clearTimeout(timeout);
                timeout = setTimeout(function () {
                    autocomplete_ajax_request(select, url_by_word, false, true);
                }, 100);
            });

            fixedSearchOnAutocompleteClick = function () {

                var word = '&q=';
                if (autocomplete.val() !== '') {
                    word += encodeURIComponent(autocomplete.val());
                }

                var filter_value = $(this).parent().prev().attr('fixed-search-parent-field');
                var parent_field = $("#fix_search_" + filter_value);
                var parent_prev_val = $(parent_field).next().find('.autocomplete__input').val();

                if (parent_field.val() === null || parent_field.val() === 'undefined' || parent_field.val() === '') {
                    parent_select_val = parent_field.attr('first_link_init');
                } else {
                    parent_select_val = parent_field.val();
                }

                if ((parent_prev_val === null || parent_prev_val === undefined || parent_prev_val === '') && (word === '&q=')) {
                    word = '';
                    parent_select_val = undefined;
                } else if (parent_prev_val === null || parent_prev_val === undefined || parent_prev_val === '') {
                    parent_select_val = undefined;
                }
                var autocomplete_url = 'select_value.php?field=' + $(this).parent().prev().attr('field_id') + '&filter_value=' + parent_select_val;

                autocomplete_ajax_request(select, autocomplete_url, false, true);
            };
            fixedSearchBtnOnAutocompleteClick = function () {

                var filter_value = $(this).parent().prev().attr('fixed-search-parent-field');
                var parent_field = $("#fix_search_" + filter_value);
                var parent_prev_val = $(parent_field).next().find('.autocomplete__input').val();

                if (parent_field.val() === null || parent_field.val() === 'undefined' || parent_field.val() === '') {
                    parent_select_val = parent_field.attr('first_link_init');
                } else {
                    parent_select_val = parent_field.val();
                }

                if (parent_prev_val === null || parent_prev_val === undefined || parent_prev_val === '') {
                    parent_select_val = undefined;
                }
                var autocomplete_url = 'select_value.php?field=' + $(this).parent().prev().attr('field_id') + '&filter_value=' + parent_select_val;

                autocomplete_ajax_request(select, autocomplete_url, false, true, 0, '', {}, false);
                if ($(this).parent().parent().find('.combobox').val() === '') {
                    extSearchCheckVal(this);
                }
            };
            autocomplete.on('click', fixedSearchOnAutocompleteClick);
            autocomplete_btn.on('click', fixedSearchBtnOnAutocompleteClick);
        } else {

            $(obj).on('keyup', function (e) {
                var word = '&q=';
                if (autocomplete.val() !== '') {
                    word += encodeURIComponent(autocomplete.val());
                }

                var url_by_word = 'select_value.php?field=' + $(this).parent().prev().attr('field_id') + word;
                if (e.keyCode === 17 || e.keyCode === 18 || e.keyCode === 16 || e.keyCode === 27 || e.keyCode === 40 || e.keyCode === 37 ||
                    e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 9 || e.keyCode === 20 || e.keyCode === 13) {
                    return;
                }
                clearTimeout(timeout);
                timeout = setTimeout(function () {
                    autocomplete_ajax_request(select, url_by_word, false, true);
                }, 100);
            });

            fixedSearchOnAutocompleteClick = function () {
                var word = '&q=';
                if (autocomplete.val() !== '') {
                    word += encodeURIComponent(autocomplete.val());
                }
                if (word === '&q=') {
                    word = '';
                }
                var autocomplete_url = 'select_value.php?field=' + $(this).parent().prev().attr('field_id');
                autocomplete_ajax_request(select, autocomplete_url, false, true);
            };
            fixedSearchBtnOnAutocompleteClick = function () {
                var autocomplete_url = 'select_value.php?field=' + $(this).parent().prev().attr('field_id');
                autocomplete_ajax_request(select, autocomplete_url, false, true, 0, '', {}, false);
                if ($(this).parent().parent().find('.combobox').val() === '') {
                    extSearchCheckVal(this);
                }
            };
            autocomplete.on('click', fixedSearchOnAutocompleteClick);
            autocomplete_btn.on('click', fixedSearchBtnOnAutocompleteClick);
        }
    })
}

/**
 * Метод, инициализирующий стрелку-ссылку на верх страницы
 */
function init_table_anchor() {
    if ($("#fields_buttons_table").length > 0) {
        var anchor = $("#scrollTopAnchor");
        var docum = $(document);
        var button_field = $("#fields_buttons_table");
        var button_field_position_y = button_field.position().top;
        anchor.on("click", function () {
            $("html:not(:animated),body:not(:animated)").animate({
                scrollTop: 0
            }, 300, 'swing');
            return false;
        });
        docum.on("scroll", function () {
            if (docum.scrollTop() > button_field_position_y - 1) {
                anchor
                    .show();
            }
            else {
                anchor.hide();
            }
            return false;
        })
        if (docum.scrollTop() > button_field_position_y - 1) {
            anchor
                .show();
        }
        else {
            anchor.hide();
        }
    }
}

function addClassSecondCell() {
    secondColumn.each(function () {
        $(this).addClass('fields__second-cell');
    });
}

function rowGroupAppendCells() {
    var rowGroup = $('.fields__row--group');
    var fieldsCell = $('.fields__cell');

    if (rowGroup.length > 0) {
        var cellCount = rowHeader.find(fieldsCell).length;

        for (var i = 0; i < cellCount - 3; i++) {
            rowGroup.append('<div class="fields__cell"></div>');
        }
    }
}

function minCustomColumnWidth(row, after_edit_link_field = false, for_autosize = false, text_field = null) {
    if(after_edit_link_field){
        $(row).css('height', '');
        $(row).find('.fields__cell').each((k, cell) => {
            $(cell).css('height', '');
        });
    }
    if(for_autosize){
        if(text_field != null){
            $(row).find(secondColumn).height(text_field.height());
        }
        else {
            $(row).find(secondColumn).height(row.height());
        }
    }
    else {
        $(row).find(secondColumn).height(row.height() - PADDING_CELL_VERTICAL * 2 - BORDER_SIZE + 'px');
        $(row).find(checkboxColumn).height(row.height() - PADDING_CELL_VERTICAL * 2 - BORDER_SIZE + 'px');
        $(row).find(fieldsCell).eq(2).height(row.find(secondColumn).height());
    }
}

function customColumnWidth(after_edit_link_field = false) {
    if(after_edit_link_field){
        $('.fields__row--simple').each((i, el) => {
            $(el).css('height', '');
            $(el).find('.fields__cell').each((k, cell) => {
                $(cell).css('height', '');
            });
        });
    }
    if (row.length > 0) {
        const fieldsCell = $('.fields__cell');
        const secondColumnWidth = row.eq(0).find(secondColumn).width();
        const isNumber = fieldsCell.hasClass('fields__cell--number-header') || fieldsCell.hasClass('number__max_width-table');
        let headerRowWidth = 0;

        checkboxHeaderColumn.height(rowHeaderHeight - PADDING_CELL_VERTICAL * 2 + 'px');
        secondHeaderColumn.height(rowHeaderHeight - PADDING_CELL_VERTICAL * 2 + 'px');


        rowHeader.children(fieldsCell).each(function (i) {
            var headerColumnWidth = 0;

            if (rowHeader.children(fieldsCell).eq(i).width() <= $('.fields__row--simple').eq(0).find(fieldsCell).eq(i).width()) {
                var field = $('.fields__row--simple').eq(0).find(fieldsCell).eq(i);
                headerColumnWidth = field.width();
                if (i !== 0) field.width(headerColumnWidth);
            } else {
                headerColumnWidth = rowHeader.children(fieldsCell).eq(i).width();
            }

            if (splitColumns == '1')
            rowHeader.find(fieldsCell).eq(i).width(headerColumnWidth + 'px');

            cellWidth = headerColumnWidth > other_field_max_width ? other_field_max_width : (headerColumnWidth < other_field_min_width ? (isNumber ? (headerColumnWidth < num_field_min_width ? num_field_min_width : headerColumnWidth) : other_field_min_width) : headerColumnWidth);
            headerRowWidth += cellWidth + paddingCell * 2 + paddingExternal;

            if (i !== 0) {
                $('.fields__row--simple').eq(0).find(fieldsCell).eq(i).css({
                    'width': cellWidth + 'px',
                    'min-width': cellWidth + 'px',
                });
            }
        });

        rowHeader.width(headerRowWidth);
        rowHeader.css({
            'min-width': '-moz-available',
            'min-width': '-webkit-fill-available',
        });

        for (var i = 0; i < row.length; i++) {
            var thisRow = row.eq(i);
            thisRow.find(secondColumn).height(thisRow.height() - PADDING_CELL_VERTICAL * 2 - BORDER_SIZE + 'px');
            thisRow.find(checkboxColumn).height(thisRow.height() - PADDING_CELL_VERTICAL * 2 - BORDER_SIZE + 'px');
            thisRow.find(fieldsCell).eq(2).height(thisRow.find(secondColumn).height());
        }

        secondColumn.width(secondColumnWidth);
    }
}

//Устанавливаем рамки таблицы
function setfieldsBorder() {
    if (rowHeader.css('position') == 'fixed') {
        hiddenColumn.addClass('hidden-column--fixed');
    } else {
        hiddenColumn.removeClass('hidden-column--fixed');
    }
}

/**
 * Метод, срабатывающий при горизонтальной прокрутки таблицы
 */
function table_scrolling_horizontal() {
    $('.fields__wrap').scroll(function () {

        if (checkbox_mode == false) {
            setFixedHeaderHeight();
            $('.fields__row').each((i, el) => {
                let elDiv = $('<div class="first"></div>').addClass('').css('width', (addititonDivWidth + (i == 0 && rowHeader.css('position') === 'fixed' ? 32 : 0)) + 'px');

                if($(el).find('.first').length == 0){
                    $(el).prepend(elDiv);
                    if(splitColumns == '1'){
                        $(el).find('.fields__cell').eq(0).css({
                            'border-left': '1px solid rgba(0, 0, 0, 0.07)',
                            'border-right': '1px solid rgba(0, 0, 0, 0.07)',
                            'width': '32px'
                        });
                    }
                }
            });
            var documentScrollLeft = $('.fields__wrap').scrollLeft();

            let fromLeft =  (splitColumns == '1' ? 2 : -1);
            checkboxColumnWidth = 32;
            paddingCell = 0;

            if (lastScrollLeft !== documentScrollLeft) {

                if (rowHeader.css('position') === 'fixed') {
                    rowHeader.css('left', -documentScrollLeft);
                    checkboxHeaderColumn.css('left', documentScrollLeft + paddingExternal + 'px');
                } else {
                    checkboxHeaderColumn.css('left', paddingExternal + 'px');
                }
                if (documentScrollLeft !== 0) {
                    if (secondColumn.css('text-align') === 'right') {
                        secondColumn.css('justify-content', 'flex-end');
                    }
                    checkboxColumn.css({
                        'position': 'absolute',
                        'left': (paddingExternal) + 'px',
                        'z-index': 2,
                        'display': 'flex',
                        'align-items': 'center'
                    });
                    checkboxHeader.css({
                        'top': '3px'
                    });
                    checkboxHeaderColumn.css({
                        'position': 'absolute',
                        'left': (paddingExternal) + 'px',
                        'z-index': 1,
                        'box-shadow': 'inset 0 0 50px 30px rgba(50, 50, 50, 0.6)',
                        'display': 'flex',
                        'align-items': 'center',
                        'background-color': header_firts_cells,
                        'width': '32px'
                    });
                    if (secondHeaderColumn.css('text-align') === 'right') {
                        secondHeaderColumn.css('justify-content', 'flex-end');
                    }
                    fieldsTable.css({
                        'margin-left': '0',//((scrollWidth - clientWidth) < 100 ? ((scrollWidth - clientWidth) < 50 ? ($('.fields__wrap').find('div.fields__cell-group--title').length > 0 ? paddingExternal / 2 : (scrollWidth - clientWidth)) : (paddingExternal * 2 + paddingCell)) : (checkboxHeaderColumn.outerWidth() + secondHeaderColumn.outerWidth())) + 'px',
                        'min-width': 'auto'
                    });
                    secondColumn.css({
                        'position': 'absolute',
                        'left': (checkboxColumnWidth + paddingExternal + fromLeft) + 'px',
                        'z-index': 2,
                        'border-right': '1px solid rgba(0, 0, 0, 0.13)',
                        'display': 'flex',
                        'align-items': 'center',
                        'width': secondHeaderColumn.width(),
                    });
                    secondHeaderColumn.css({
                        'box-shadow': 'inset 0 0 50px 30px rgba(50, 50, 50, 0.6)',
                        'align-items': 'center',
                        'position': 'absolute',
                        'background-color': header_firts_cells
                    });
                    if (rowHeader.css('position') === 'fixed') { // Горизонтальный скролл с фиксированным header-ом
                        secondHeaderColumn.css('left', (checkboxColumnWidth + documentScrollLeft + paddingExternal + fromLeft) + 'px');
                        checkboxHeaderColumn.css('left', (documentScrollLeft + paddingExternal) + 'px');
                        secondHeaderColumn.next().css('margin-left', 0)//((paddingExternal + secondHeaderColumn.outerWidth() + checkboxHeaderColumn.outerWidth()) + 'px'));//(paddingExternal + secondHeaderColumn.outerWidth() + checkboxHeaderColumn.outerWidth() - ((scrollWidth - clientWidth) < 50 ? -3 : 7) ) + 'px');

                    } else {
                        secondHeaderColumn.css('left', (checkboxColumnWidth + paddingExternal + fromLeft) + 'px');
                        checkboxHeaderColumn.css('left', (paddingExternal) + 'px');
                    }
                } else {
                    $('.first').each((i, el) => {
                        $(el).remove();
                    });
                    secondHeaderColumn.next().css('margin-left', paddingExternal + 'px');
                    fieldsTable.css({
                        'margin-left': 0,
                        'min-width': '-moz-available'
                    });
                    secondColumn.css({
                        'position': 'relative',
                        'left': '',
                        'border-bottom': '',
                        'border-right': '',
                        'display': 'table-cell'
                    });
                    checkboxHeader.css({
                        'top': 3 + 'px'
                    });
                    checkboxColumn.css({
                        'position': 'relative',
                        'left': 0,
                        'display': 'table-cell'
                    });
                    checkboxHeaderColumn.css({
                        'position': 'relative',
                        'box-shadow': '',
                        'display': 'table-cell',
                        'background': ''
                    });
                    secondHeaderColumn.css({
                        'background': ''
                    });
                    secondHeaderColumn.css('box-shadow', '');
                    if (rowHeader.css('position') == 'fixed') {
                        checkboxHeaderColumn.css('left', (paddingExternal) + 'px');
                        secondHeaderColumn.css({
                            'position': 'relative',
                            'left': (checkboxColumnWidth + paddingCell) + 'px'
                        });
                    } else {
                        checkboxHeaderColumn.css('left', '');
                    }
                }
                lastScrollLeft = documentScrollLeft;
            }
        }
    });
}

/**
 * Метод, срабатывающий при скролле страницы, устанавливающий правила для таблицы
 */
function table_scrolling_vertical() {
    $('.fixed-table-inner').scrollLeft(lastScrollLeft);
    paddingCell = 5;
    const fromLeft =  (splitColumns == '1' ? 2 : -2);
    $('.fields__row').each((i, el) => {
        if($(el).find('.first').length != 0 && $(el).hasClass('fields__row--header')){
            $(el).find('.first').css('width', (addititonDivWidth + (i == 0 && rowHeader.css('position') === 'fixed' ? 32 : 0)) + 'px');
        }
    });
    if ( rowHeader.css('position') == 'fixed' && secondHeaderColumn.css('position') == 'static' ) {
        secondHeaderColumn.css('position','relative');
        secondHeaderColumn.prev('.fields__cell--checkbox').css('position','relative');
    }
    if(splitColumns == '1'){
        rowHeader.find('.fields__cell').eq(0).css({
            'border-left': '1px solid rgba(0, 0, 0, 0.07)',
            'border-right': '1px solid rgba(0, 0, 0, 0.07)',
            'width': '32px'
        });
    }
    if (rowHeader.css('position') == 'fixed' && secondHeaderColumn.css('position') == 'relative') {
        secondHeaderColumn.css({
            'left': checkboxColumnWidth + (splitColumns == '1' ? -2 : 0) + 'px'
        });

        checkboxHeaderColumn.css({
            'left': paddingExternal + 'px',
            'display': 'flex'
        });

        secondHeaderColumn.next().css({
            'margin-left': paddingExternal + 'px'
        });

        rowHeader.css({
            'display': 'flex'
        });
    } else if (rowHeader.css('position') == 'fixed' && secondHeaderColumn.css('position') == 'absolute') {
        secondHeaderColumn.css({
            'left': lastScrollLeft + paddingExternal + checkboxHeaderColumn.outerWidth() + (splitColumns != '1' ? -1 : 0) + 'px'
        });

        checkboxHeaderColumn.css({
            'left': lastScrollLeft + paddingExternal + 'px',
            'display': 'flex'
        });
        secondHeaderColumn.next().css({
            'margin-left': '0'//paddingExternal + secondHeaderColumn.outerWidth() + checkboxColumnWidth + 'px'
        });
        rowHeader.css({
            'display': 'flex',
        });
    } else if (rowHeader.css('position') != 'fixed' && secondHeaderColumn.css('position') == 'absolute') {
        secondHeaderColumn.css({
            'left': (checkboxColumnWidth + paddingExternal + fromLeft + (splitColumns == '1' ? -1 : 0)) + 'px'
        });
        secondHeaderColumn.next().css({
            //'margin-left': '32px'//paddingExternal + secondHeaderColumn.outerWidth() + checkboxColumnWidth + 'px'
        });
        fieldsTable.css('margin-left', '0px');//((scrollWidth - clientWidth) < 100 ? ((scrollWidth - clientWidth) < 50 ? ($('.fields__wrap').find('div.fields__cell-group--title').length > 0 ? paddingExternal / 2 : paddingExternal) : (paddingExternal * 2 + paddingCell)) : (checkboxColumnWidth + secondHeaderColumn.outerWidth())) + 'px');

        checkboxHeaderColumn.css({
            'left': paddingExternal + 'px',
            'display': 'flex'
        });
        rowHeader.css({
            'display': 'table-row'
        });
    } else if (rowHeader.css('position') != 'fixed' && secondHeaderColumn.css('position') == 'relative') {
        secondHeaderColumn.css({
            'left': 0
        });
        fieldsTable.css({
            'margin-left': 0
        });

        checkboxHeaderColumn.css({
            'left': 0,
            'display': 'table-cell'
        });
        rowHeader.css({
            'display': 'table-row'
        });
    }
    setfieldsBorder();
}

/**
 * Метод, инициализирующий быстрое редактирование множ. выбора
 */
function init_fast_edit_multi() {
    if (multi_select.length > 0) {
        var prev_multi_select;
        multi_select.each(function () {
            var parent = $(this).parents($('.fields_cell'));
            var text = $(this).find('.fields__multi-val-select-text');
            var dropdown = $(this).find('.fields__multi-val-select-dropdown');

            var checkAllButton = $(this).find('.fields__multi-val-select-dropdown .check-all');
            var checkAllStatus = true; //Все ли элементы чекнуты

            let checkInputs = dropdown.find('input[type="checkbox"]:not(.checkAll)');
            checkInputs.each(function (index, element) { //Проверяем, все ли элементы чекнуты
                let check = $(element).prop('checked')
                if (!check) {
                    checkAllStatus = false //Не все элементы чекнуты
                    return false;
                }
            })

            parent.css('overflow', 'visible');
            $(this).on('mouseup', function (event) {
                event.stopPropagation();
            });
            text.click(function () {
                const itemWidth = dropdown.prev().outerWidth() - 8;
                const cellNewHeight = dropdown.height() + 40; //

                if ($.type(prev_multi_select) !== 'undefined') {
                    var prev_dropdown = prev_multi_select.find('.fields__multi-val-select-dropdown');
                    var prev_text = prev_multi_select.find('.fields__multi-val-select-text');

                    if (prev_text.attr('id') !== $(this).attr('id')) {
                        prepare_data_for_save_multi(prev_dropdown, prev_text);
                    }
                }

                if (dropdown.css('display') === 'none') {
                    dropdown.show();
                    dropdown.parents('.fields__multi-val-select').css('height', cellNewHeight);
                    dropdown.css({ width: itemWidth });
                } else {
                    dropdown.parents('.fields__multi-val-select').css('height', '');
                    dropdown.hide();
                }
                prev_multi_select = $(this).parent();
                text.val(form_multi_select_value($(this).parent()));
                $(this).toggleClass('hidden-input--focus');

                minCustomColumnWidth(dropdown.parents('.fields__row'), true);
            });
            dropdown.on('click', function (event) {
                var target = $(event.target);
                if (target[0].nodeName === 'INPUT' || target[0].nodeName === 'LABEL') {
                    text.val(form_multi_select_value($(this).parent()));
                }

            });

            checkAllButton.on('click', function (event) { //Обработка клика по кнопке "Все"
                if (!checkAllStatus) {
                    dropdown.find('input[type="checkbox"]').prop('checked', true);
                    checkAllStatus = true;
                } else {
                    dropdown.find('input[type="checkbox"]').prop('checked', false);
                    checkAllStatus = false;
                }
            })
        });
        $(document).on('click', function (event) {
            if ($.type(prev_multi_select) !== 'undefined') {
                var text = prev_multi_select.find('.fields__multi-val-select-text');
                var dropdown = prev_multi_select.find('.fields__multi-val-select-dropdown');

                if ($(event.target).closest('.fields__multi-val-select').length) {
                    return;
                }

                prepare_data_for_save_multi(dropdown, text);
                event.stopPropagation();
                minCustomColumnWidth(dropdown.parents('.fields__row'), true);
            }
        });
    }
}

/**
 * Метод, формирующий значение строки множественного выбора по чекбоксам
 * @param obj element Множественный выбор
 * @returns string Готовое значение
 */
function form_multi_select_value(obj) {
    if (obj) {
        var dropdown = obj.find('.fields__multi-val-select-dropdown');
        var result = '';

        dropdown.find($('input:not(.checkAll)')).each(function () {
            if ($(this).prop('checked')) {
                result += $(this).next().html() + ', ';
            }
        });
        if (result !== '') {
            result = result.slice(0, -2);
        }
        return result;
    }
}

/**
 * Метод, подготовливающий параметры для запроса на сохранения и вызывает AJAX-запрос на сохранения поля
 * @param dropdown element Выпадающее меню
 * @param text element Текстовое поле
 */
function prepare_data_for_save_multi(dropdown, text) {
    var id = text.attr('id');
    var splited_id = id.split('_');
    var display_values = text.val().split(', ');
    var values = display_values.map(function (display_val) {
        return text.next().next().find($('input[display_val="' + display_val + '"]')).attr('val');
    });
    var result = (parseInt(text.attr('users')) === 0) ? JSON.stringify(values) : '-' + values.join('-') + '-';
    var is_users = parseInt(text.attr('users')) === 1;

    text.attr('mult-val', result);
    dropdown.hide();
    dropdown.parents('.fields__multi-val-select').css('height', '');
    text.removeClass('hidden-input--focus');
    save_value_multi(splited_id[3], splited_id[4], result, is_users);
}

// Получить css свойство объекта
function getElementComputedStyle(elem, prop) {
    if (typeof elem != "object") elem = document.getElementById(elem);

    // external stylesheet for Mozilla, Opera 7+ and Safari 1.3+
    if (document.defaultView && document.defaultView.getComputedStyle) {
        if (prop.match(/[A-Z]/)) prop = prop.replace(/([A-Z])/g, "-$1").toLowerCase();
        return document.defaultView.getComputedStyle(elem, "").getPropertyValue(prop);
    }

    // external stylesheet for Explorer and Opera 9
    if (elem.currentStyle) {
        var i;
        while ((i = prop.indexOf("-")) != -1) prop = prop.substr(0, i) + prop.substr(i + 1, 1).toUpperCase() + prop.substr(i + 2);
        return elem.currentStyle[prop];
    }

    return "";
}

/**
 * Метод, обновляющий данные в таблице при изменении полей быстрого редактированияи включенных вычесленияъ
 * @param resp
 */
function update_data(resp) {
    var resp_arr = resp.split('\n');
    for (keyVar in resp_arr) {  // разбивка на каждое поле которое изменилось
        var child_res_arr = resp_arr[keyVar].toString().split("|");
        var status = child_res_arr[0];

        if (status !== 'saved') {
            var field_id = child_res_arr[1];
            var line_id = child_res_arr[2];
            var new_value = Base64.decode(child_res_arr[3]);
            var cell = document.getElementById('td' + line_id + '.' + field_id); // TODO видимо это нужно доработать, т.к. таблица уже давно переделана на div

            if ($(cell).find($('.hidden-input')).length === 0) { // если поле состоит из обычного текста
                if ($(cell).find('.fields__simple-text.fields__value').length > 0) {
                    $(cell).find('.fields__simple-text.fields__value').html(new_value);
                } else if ($(cell).find('.fields__cell-inner div:not([style]):not([class])').length > 0){
                    //$(cell).find('.file-cell__title').html(new_value)
                } else if ($(cell).find('.field-image-value').length > 0){
                    //$(cell).find('.file-cell__title').html(new_value)
                } else {
                    $(cell).text(new_value)
                }
            } else if ($(cell).find($('div.hidden-input')).length > 0) { // если это поле обычный input
                var input = $(cell).find($('div.hidden-input'));
                input.text(new_value);
            }
        } else if (status === 'saved') {
            /*TODO: Нужно чтобы за анализ и отрисовку данных отвечал один функционал*/
            var field_id = child_res_arr[2];
            var line_id = child_res_arr[3];
            var cell = document.getElementById(`fast_edit_span_${field_id}_${line_id}`);
            if (!cell) return;

            const cellType = show_fields.fields[field_id].type_field
            // Если тип данных связь, ничего не делаем
            const isTypeLink = cellType === '5'
            if(isTypeLink)
                return;

            const new_value = Base64.decode(child_res_arr[4]);
            // Если селект или инпут менем велью
            const editableTags = ['INPUT', 'SELECT'];

            if (editableTags.includes(cell.tagName))
               cell.value = new_value;
            else
                cell.textContent = new_value;
        }
    }
}

// ширина при загрузке таблицы, для цветового текстового форматирования
function all_width_select_text_formatting() {
  let allGroundFormatter = document.querySelectorAll('.fields__select-formatter');

  if (allGroundFormatter.length) {
    for (ground of allGroundFormatter) {
      let wrapperGround = ground.closest('.fields__cell-inner');

      let selectWhenEdit = wrapperGround.querySelector('select.hidden-input--select');
      // для полей список
      // нередактируемые
      // редактируемые, множественные
      let selectNoEdit = $(wrapperGround).find('div.fields__value, div.fields__multi-val-select');

      if (selectWhenEdit) {
        width_select_text_formatting(selectWhenEdit);
      } else if (selectNoEdit.length > 0) {

        $(selectNoEdit).css({
          "z-index": '1',
        })

        // Округляем, чтобы не было разницы с редактируемым списком
        let widthSelectNoEdit = Math.ceil($(selectNoEdit).width());
        // Ширина для нередактируемых списков в таблице
        ground.style.width = `${widthSelectNoEdit}px`;

        $(ground).css({
          'padding-left': '7px',
          'padding-right': '7px',
        })

        let dataColor = ground.getAttribute('data-color');
        if (dataColor != '') {
          ground.style.backgroundColor = dataColor;
        }
      }

    }

  }
};

// ширина для цветового текстового форматирования
function width_select_text_formatting(currentSelect) {

  let optionSelectText = currentSelect.selectedOptions[0].textContent;

    let tempOption = document.createElement('option');
    tempOption.textContent = optionSelectText;

    let tempSelect = document.createElement('select');
    tempSelect.appendChild(tempOption);
    tempSelect.style.cssText = `
      visibility: hidden;
      position: fixed;
      padding: 0;
    `;

    // Добавляем в DOM
    currentSelect.after(tempSelect);

    // Находим обертку .fields__select-formatter
    let groundFormatter = currentSelect.previousElementSibling;
    let widthTempSelect = $(tempSelect).width();

    if (groundFormatter) {
      $(groundFormatter).css({
        'margin-left': '7px',
        'padding-left': '7px',
        'padding-right': '7px',
      })

      if (widthTempSelect > currentSelect.clientWidth) {
        groundFormatter.style.width = `${currentSelect.clientWidth - 10}px`; // Минус отступы, без учета border
      } else if (widthTempSelect == 0) {
        $(groundFormatter).css({
          'width': '0px',
          'padding': '0px',
        });
      } else {
        groundFormatter.style.width = `${widthTempSelect}px`;
      }

      let dataColor = groundFormatter.getAttribute('data-color');
      if (dataColor != '') {
        groundFormatter.style.backgroundColor = dataColor;
      }

    }

    tempSelect.remove();

}

// сохранить значение
function save_value(field_id, line_id, val) {
    var new_val = encodeURIComponent(val);
    const isUnique = fast_edit_uniq_check({ 
        fieldId: field_id,
        lineId: line_id,
        tableId: table_id,
        value: val,
    })
    if (isUnique) {
        ajaxObj.format = 0;
        ajaxObj.method = "POST";
        ajaxObj.failed_requests = 0;
        ajaxObj.call(`table=${table_id}&field=${field_id}&line=${line_id}&value=${new_val}&csrf=${csrf}`, saveCallback({ field_id, line_id }));
    }
}
function save_value_multi(field_id, line_id, full_value, is_users) {
    var users = '&users=';
    if (is_users) {
        users += '1';
    } else {
        users += '0';
    }
    $.ajax({
        method: "POST",
        url: "fields.php",
        data: "fast_edit_list=1&table=" + table_id + "&field=" + field_id + "&line=" + line_id + "&value=" + full_value + "&csrf=" + csrf + users,
        success: function () {
            colorFormat.setFormatColor({
                lineId: line_id
            });
        }
    });
}

function isHTMLString(str) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(str, "text/html");
  return Array.from(doc.body.childNodes).some(node => node.nodeType === 1);
}
const showErrorInfo = (req) => {
  if (document.getElementById(`fast_edit_span_${req.field_id}_${req.line_id}`)) {
    document.getElementById(`fast_edit_span_${req.field_id}_${req.line_id}`).style.background = 'red';
  }
  if (user.display_notification_on) {
    displayNotification(lang.Saving_error, 2)
  }
}

const showSuccessInfo = (req) => {
  if (document.getElementById(`fast_edit_span_${req.field_id}_${req.line_id}`)) {
    document.getElementById(`fast_edit_span_${req.field_id}_${req.line_id}`).style.background = '';
  }

  if (user.display_notification_on) {
    displayNotification(lang.save_value_notify, 1);
  }
}

function saveCallback(req) {
  return function (res) {
    if(isHTMLString(res)) {
      return showErrorInfo(req);
    };
    
    res = checkResp(res);
    const [ action, , , line_id ] = res.toString().split("|");
    colorFormat.setFormatColor({
      lineId: line_id
    });
    if (action == "saved") {
      showSuccessInfo(req);
    }
    colorFormat.setFormatColor({
      lineId: line_id
    });



    update_data(res);

    let update_strings_arr = res.toString().split('\r\n')
    UpdateFields(update_strings_arr, line_id);
  }
};

function UpdateFields(update_strings_arr, line_id) {
    let foundHide = update_strings_arr.find(item => item.includes('hide'));
    let foundShow = update_strings_arr.find(item => item.includes('show'));
    let foundCanEdit = update_strings_arr.find(item => item.includes('can_edit'));
    let foundNoEdit = update_strings_arr.find(item => item.includes('no_edit'));

    if (foundShow) {
        let foundShowArr = foundShow.split('|');
        foundShowArr.shift();
        foundShowArr.forEach( (item) => {
            let show_field_id = item;

            showHeaderCell(show_field_id)
            let field = document.querySelector(`[id="td${line_id}.${show_field_id}"]`);
            if(!field) return;

            field.classList.add('field_show')
            field.classList.remove('field_edit')
            field.classList.remove('field_hide')

            if (field.querySelector('.no_access')) {
              field.querySelector('.no_access').remove()
            }

            switch(show_fields.fields[item].type_field) {
              case '1': //число
                let saved_value_1;

                let input = field.querySelector('.fields__fast-edit--text')

                if (input) {
                  saved_value_1 = input.value
                }

                if (saved_value_1 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + show_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_1 = res.value
                        if (saved_value_1) {
                          input.value = saved_value_1
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  input.value = saved_value_1;
                }

                input.disabled = true

                break;
              case '3': //текст
                let saved_value_3;

                let textarea = field.querySelector('.fields__fast-edit--text')

                if (textarea) {
                  saved_value_3 = textarea.innerHTML
                }

                if (saved_value_3 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + show_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_3 = res.value
                        if (saved_value_3) {
                          textarea.value = saved_value_3
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  textarea.value = saved_value_3;
                }

                textarea.disabled = true;

                break;

              case '2': //дата
                let saved_value_2 ;

                let date_input = field.querySelector('input.fields__fast-edit')

                if (date_input) {
                  saved_value_2 = date_input.value
                }/* else {

                }*/

                if (saved_value_2 == 'Нет доступа' || saved_value_2 == '..') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + show_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_2 = res.value
                        if (saved_value_2) {
                          date_input.value = saved_value_2
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  date_input.value = saved_value_2;
                }

                date_input.disabled = true;
                break;

              case '4': //список
                let saved_value_4;

                let list_select = field.querySelector('.hidden-input--select')

                if (list_select) {
                  saved_value_4 = list_select.value
                } else {
                  list_select = field.querySelector('.fields__multi-val-select-text')
                  saved_value_4 = list_select.value
                }

                if (saved_value_4 == 'Нет доступа' || !saved_value_4) {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + show_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_4 = res.value
                        if (saved_value_4) {
                          list_select.value = saved_value_4
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  list_select.value = saved_value_4;
                }

                list_select.disabled = true;
                /*
                let start_4 = true
                show_fields.fields[item].list_values.forEach( (value) => {
                  if (start_4) {
                    let empty_option = document.createElement('option');
                    empty_option.value = '';
                    empty_option.innerHTML = '';
                    list_select.append(empty_option);
                    start_4 = false
                  }

                  let option = document.createElement('option')
                  option.value = value
                  option.innerHTML = value
                  if (value == saved_value_4) {
                    option.selected = true;
                  }
                  list_select.append(option)
                })
                */

                break;

              case '5': //связь

                let saved_value_5 = field.querySelector('.fields__simple-text.fields__simple-text--link')

                /*if (saved_value_5.querySelector('.no_access')) {
                    saved_value_5.querySelector('.no_access').remove()
                }*/

                /*let edit_button = field.querySelector('.fields__fast-edit-button--edit')
                edit_button.style.display = 'none'*/

                $.ajax({
                  url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + show_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        if (typeof res.value == 'object') {
                          let field_cell_inner = document.createElement('div')
                          field_cell_inner.classList.add('fields__cell-inner')
                          field_cell_inner.classList.add('fields__cell-inner--with-fixed')

                          let expand_button = document.createElement('button')
                          expand_button.classList.add('link-color')
                          expand_button.classList.add('fields__resize-btn')
                          expand_button.classList.add('fields__resize-btn--not-edit')
                          expand_button.setAttribute('field_id', show_field_id)
                          expand_button.setAttribute('line_id', line_id)
                          expand_button.setAttribute('title', 'Раскрыть текст') //заменить на lang
                          expand_button.setAttribute('style', 'display: inline-block;')
                          expand_button.setAttribute('type', 'button')
                          expand_button.setAttribute('onmousedown', 'dont_open_view=1')
                          expand_button.setAttribute('onclick', 'event.stopPropagation();dont_open_view=1')



                          field_cell_inner.append(expand_button)


                          let select = document.createElement('select')
                          select.classList.add('select2-plugin')
                          select.classList.add('select2-hidden-accessible')
                          select.classList.add('fields__simple-text--fixed')
                          select.id = `fast_edit_span_${show_field_id}_${line_id}`
                          select.setAttribute('multiple', 'true')
                          select.setAttribute('data-field-id', show_field_id)
                          select.setAttribute('data-table-id', show_fields.table.id)
                          select.setAttribute('data-line-id', line_id)
                          select.setAttribute('data-mode', 'common')

                          select.setAttribute('style', 'width: 100%;')
                          select.setAttribute('data-select2-id', `fast_edit_span_${show_field_id}_${line_id}`)
                          select.setAttribute('tabindex', '-1')
                          select.setAttribute('aria-hidden', 'true')

                          let prev_value = ''
                          let begin = true

                          for (const [key, value_item] of Object.entries(res.value)) {
                            let option = document.createElement('option')
                            option.setAttribute('value', key)
                            option.selected = true
                            option.innerHTML = value_item.text

                            select.append(option)

                            if (begin) {
                              prev_value += key
                              begin = false
                            } else {
                              prev_value += ',' + key
                            }

                          }
                          select.setAttribute('data-previously-value', prev_value)
                          //опции
                          field_cell_inner.append(select)
                          field.innerHTML = ''
                          field.append(field_cell_inner)
                          init_fields_additional()

                        } else {
                          if (field.querySelector('.fields__simple-text--link')) {
                            if ($(res.value)[1]) {
                              field.querySelector('.fields__simple-text--link').innerHTML = $(res.value)[1].innerHTML
                            } else {
                              field.querySelector('.fields__simple-text--link').innerHTML = res.value
                            }
                          } else {
                            if ($(res.value)[1]) {
                              field.innerHTML = $(res.value)[1].innerHTML
                            } else {
                              field.innerHTML = res.value
                            }
                          }
                        }


                    },
                    error: function(response) {
                        
                         
                    }
                });

                break;

              case '6': //файл
                let div_wrap = field.querySelector('.fields__cell-inner div:not([style]):not([class])')

                if (!div_wrap) {
                  div_wrap = field
                }

                $.ajax({
                  url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + show_field_id,
                  success: function (xhr) {
                      var res = JSON.parse(xhr);
                      div_wrap.innerHTML = ''
                      $(div_wrap).append(res.value)
                  },
                  error: function(response) {
                      
                       
                  }
                });

                break;

              case '7': //пользователь

                let saved_value_7;

                let user_select = field.querySelector('.hidden-input--select')

                if (user_select) {
                  saved_value_7 = user_select.value
                } else {
                  user_select = field.querySelector('.fields__multi-val-select-text')
                  saved_value_7 = user_select.value
                }

                if (saved_value_7 == 'Нет доступа' && user_select.querySelector('option:checked')) {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + show_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_7 = res.value
                        if (saved_value_7) {
                          user_select.querySelector('option:checked').selected = false
                          let needed_option = $(user_select).find('option:contains('+saved_value_7+')')[0]
                          needed_option.selected = true
                          //$(user_select).change()
                          //$(user_select).find('option:contains('+saved_value_7+')')
                          //user_select.value = saved_value_7
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else if (false) {

                } else {
                  user_select.value = saved_value_7;
                }

                user_select.disabled = true;


                /*
                let start_7 = true
                for (let key in show_fields.fields[item].s_list_values) {
                  if (start_7) {
                    let empty_option = document.createElement('option');
                    empty_option.value = '';
                    empty_option.innerHTML = '';
                    user_select.append(empty_option);
                    start_7 = false
                  }
                  let option = document.createElement('option')
                  option.value = key
                  option.innerHTML = show_fields.fields[item].s_list_values[key]
                  if (show_fields.fields[item].s_list_values[key] == saved_value_7) {
                    option.selected = true;
                  }
                  user_select.append(option)
                }
*/

                break;

              case '9': //изображение

                let image_wrap = field.querySelector('.field-image-value')

                if (!image_wrap) {
                  image_wrap = field
                }

                $.ajax({
                  url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + show_field_id,
                  success: function (xhr) {
                      var res = JSON.parse(xhr);
                      image_wrap.innerHTML = ''
                      $(image_wrap).append(res.value)
                  },
                  error: function(response) {
                      
                       
                  }
                });

                break;

              case '14': //группа
                let saved_value_14;

                let group_select = field.querySelector('.hidden-input--select')

                if (group_select) {
                  saved_value_14 = group_select.value
                }

                if (saved_value_14 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + show_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_14 = res.value
                        if (saved_value_14) {
                          group_select.value = saved_value_14
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  group_select.value = saved_value_14;
                }

                group_select.disabled = true;

                break;
            }

        })

    }
    if (foundNoEdit) {
        let foundNoEditArr = foundNoEdit.split('|');
        foundNoEditArr.shift();
        foundNoEditArr.forEach( (item) => {
            let no_edit_field_id = item;
            let field = document.querySelector(`[id="td${line_id}.${no_edit_field_id}"]`);

            field.classList.add('field_show')
            field.classList.remove('field_edit')
            field.classList.remove('field_hide')

            if (field.querySelector('.no_access')) {
              field.querySelector('.no_access').remove()
            }

            switch(show_fields.fields[item].type_field) {
              case '1': //число
                let saved_value_1;

                let input = field.querySelector('.fields__fast-edit--text')

                if (input) {
                  saved_value_1 = input.value
                }

                if (saved_value_1 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + no_edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_1 = res.value
                        if (saved_value_1) {
                          input.value = saved_value_1
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  input.value = saved_value_1;
                }

                input.disabled = true

                break;
              case '3': //текст
                let saved_value_3;

                let textarea = field.querySelector('.fields__fast-edit--text')

                if (textarea) {
                  saved_value_3 = textarea.innerHTML
                }

                if (saved_value_3 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + no_edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_3 = res.value
                        if (saved_value_3) {
                          textarea.value = saved_value_3
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  textarea.value = saved_value_3;
                }

                textarea.disabled = true;

                break;

              case '2': //дата
                let saved_value_2 ;

                let date_input = field.querySelector('input.fields__fast-edit')

                if (date_input) {
                  saved_value_2 = date_input.value
                }

                if (saved_value_2 == 'Нет доступа' || saved_value_2 == '..') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + no_edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_2 = res.value
                        if (saved_value_2) {
                          date_input.value = saved_value_2
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  date_input.value = saved_value_2;
                }

                date_input.disabled = true;
                break;

              case '4': //список
                let saved_value_4;

                let list_select = field.querySelector('.hidden-input--select')
                if (list_select) {
                  saved_value_4 = list_select.value
                } else {
                  list_select = field.querySelector('.fields__multi-val-select-text')
                  saved_value_4 = list_select.value
                }

                if (saved_value_4 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + no_edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_4 = res.value
                        if (saved_value_4) {
                          list_select.value = saved_value_4
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  list_select.value = saved_value_4;
                }

                list_select.disabled = true;

                break;

              case '5': //связь
                //let saved_value_5 = field.querySelector('.fields__simple-text.fields__simple-text--link')

                /*if (saved_value_5.querySelector('.no_access')) {
                    saved_value_5.querySelector('.no_access').remove()
                }*/

                /*let edit_button = field.querySelector('.fields__fast-edit-button--edit')
                edit_button.style.display = 'none'*/

                /*$.ajax({
                  url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + no_edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);


                        //let value = $(res.value)[1].innerHTML потом придумать что нибудь


                        //if (field.querySelector('.fields__simple-text--link').innerHTML == 'Нет доступа') {
                        //  field.querySelector('.fields__simple-text--link').innerHTML = ''
                        //}
                        //field.querySelector('.fields__simple-text--link').innerHTML = value

                    },
                    error: function(response) {
                        
                         
                    }
                });*/

                break;

              case '6': //файл
                let file_delete = field.querySelector('.file-cell__btn_delete')
                if (file_delete) {
                  file_delete.style.display = 'none';
                }


                let file_add_div = field.children[2]
                if (file_add_div) {
                  file_add_div.style.display = 'none';
                }

                break;
                /**/
              case '7': //пользователь

                let saved_value_7;

                let user_select = field.querySelector('.hidden-input--select')

                if (user_select) {
                  saved_value_7 = user_select.value
                } else {
                  user_select = field.querySelector('.fields__multi-val-select-text')
                  saved_value_7 = user_select.value
                }

                if (saved_value_7 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + no_edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_7 = res.value
                        if (saved_value_7) {
                          user_select.value = saved_value_7
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  user_select.value = saved_value_7;
                }

                user_select.disabled = true;

                break;

              case '9': //изображение
                let image_file_delete = field.querySelectorAll('.delete_image_button_x')
                if (image_file_delete) {
                  image_file_delete.forEach( (item) => {
                    item.style.display = 'none'
                  })
                }

                let image_file_add_div = field.children[2]
                if (image_file_add_div) {
                  image_file_add_div.style.display = 'none';
                }

                break;

              case '14': //группа
                let saved_value_14;

                let group_select = field.querySelector('.hidden-input--select')

                if (group_select) {
                  saved_value_14 = group_select.value
                }

                if (saved_value_14 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + no_edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_14 = res.value
                        if (saved_value_14) {
                          group_select.value = saved_value_14
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  group_select.value = saved_value_14;
                }

                group_select.disabled = true;

                break;
            }

        })

    }
    if (foundHide) {
        let foundHideArr = foundHide.split('|');
        foundHideArr.shift();
        foundHideArr.forEach( (item) => {
            let hide_field_id = item;
            let field = document.querySelector(`[id="td${line_id}.${hide_field_id}"]`);
            if(!field) return;

            field.classList.remove('field_show')
            field.classList.remove('field_edit')
            field.classList.add('field_hide')
            switch(show_fields.fields[item].type_field) {
              case '1': //число

                let input = field.querySelector('.fields__fast-edit--text')

                input.value = 'Нет доступа'

                input.disabled = true

                break;
              case '3': //текст
                let textarea = field.querySelector('textarea')

                textarea.value = 'Нет доступа'
                textarea.disabled = true;

                break;

              case '2': //дата
                let date_input = field.querySelector('input.fields__fast-edit')

                date_input.value = 'Нет доступа'

                date_input.disabled = true;
                break;

              case '4': //список
                let list_select = field.querySelector('.hidden-input--select')

                //list_select.value = 'Нет доступа'

                let selected_option
                let no_access_option
                if (list_select) {
                  selected_option = list_select.querySelector('option[selected]')

                  if (selected_option) {
                    selected_option.classList.add('hidden_value')
                    selected_option.selected = false
                  }


                  no_access_option = document.createElement('option')
                  no_access_option.classList.add('no_access_option')
                  no_access_option.innerHTML = 'Нет доступа'
                  no_access_option.selected = true

                  list_select.append(no_access_option)
                } else {
                  list_select = field.querySelector('.fields__multi-val-select-text')
                  //list_select.value = 'Нет доступа'
                }



                list_select.disabled = true;

                break;

              case '5': //связь

                if (field.querySelector('.autocomplete_val')) {
                  field.querySelector('.autocomplete_val').innerHTML = 'Нет доступа'
                }

                break;


              case '6': //файл
                field.innerHTML = 'Нет доступа'

                break;

              case '7': //пользователь

                let user_select = field.querySelector('.hidden-input--select')

                let selected_option_7
                let no_access_option_7
                if (user_select) {
                  selected_option_7 = user_select.querySelector('option[selected]')

                  if (selected_option_7) {
                    selected_option_7.classList.add('hidden_value')
                    selected_option_7.selected = false
                  }


                  no_access_option_7 = document.createElement('option')
                  no_access_option_7.classList.add('no_access_option')
                  no_access_option_7.innerHTML = 'Нет доступа'
                  no_access_option_7.selected = true

                  user_select.append(no_access_option_7)
                } else {
                  user_select = field.querySelector('.fields__multi-val-select-text')
                  //user_select.value = 'Нет доступа'
                }



                user_select.disabled = true;


                break;

              case '9': //изображение

                field.innerHTML = 'Нет доступа'

                break;

              case '14': //группа

                let group_select = field.querySelector('.hidden-input--select')

                let selected_option_14 = group_select.querySelector('option[selected]')

                if (selected_option_14) {
                  selected_option_14.classList.add('hidden_value')
                  selected_option_14.selected = false
                }


                let no_access_option_14 = document.createElement('option')
                no_access_option_14.classList.add('no_access_option')
                no_access_option_14.innerHTML = 'Нет доступа'
                no_access_option_14.selected = true

                group_select.append(no_access_option_14)

                group_select.disabled = true;

                break;
            }
        })

    }
    if (foundCanEdit) {
        let foundCanEditArr = foundCanEdit.split('|');
        foundCanEditArr.shift();
        foundCanEditArr.forEach( (item) => {
            let edit_field_id = item;
            showHeaderCell(edit_field_id)
            let field = document.querySelector(`[id="td${line_id}.${edit_field_id}"]`);

            field.classList.remove('field_show')
            field.classList.add('field_edit')
            field.classList.remove('field_hide')

            if (field.querySelector('.no_access')) {
              field.querySelector('.no_access').remove()
            }
            if (field.querySelector('.fields__cell-inner')) {
              field.querySelector('.fields__cell-inner').style.display = 'table-cell';
            } else if (field.firstElementChild) {
              field.firstElementChild.style.display = 'initial';
            }

            switch(show_fields.fields[item].type_field) {
              case '1': //число
                let saved_value_1;

                let input = field.querySelector('.fields__fast-edit--text')

                if (input) {
                  saved_value_1 = input.value
                }

                if (!saved_value_1 || saved_value_1 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_1 = res.value
                        if (saved_value_1 || saved_value_1 == '') {
                          input.value = saved_value_1
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  input.value = saved_value_1;
                }

                input.disabled = false

                break;
              case '3': //текст
                let saved_value_3;

                let textarea = field.querySelector('.fields__fast-edit--text')

                if (textarea) {
                  saved_value_3 = textarea.innerHTML
                }

                if (!saved_value_3 || saved_value_3 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_3 = res.value
                        if (saved_value_3 || saved_value_3 == '') {
                          textarea.value = saved_value_3
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  textarea.value = saved_value_3;
                }

                textarea.disabled = false;

                break;

              case '2': //дата
                let saved_value_2 ;

                let date_input = field.querySelector('input.fields__fast-edit')

                if (date_input) {
                  saved_value_2 = date_input.value
                }

                if (!saved_value_2 || saved_value_2 == 'Нет доступа' || saved_value_2 == '..') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_2 = res.value
                        if (saved_value_2 || saved_value_2 == '') {
                          date_input.value = saved_value_2
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  date_input.value = saved_value_2;
                }

                date_input.disabled = false;
                break;

              case '4': //список
                let saved_value_4;

                let list_select = field.querySelector('.hidden-input--select')

                if (list_select) {
                  saved_value_4 = list_select.value
                } else {
                  list_select = field.querySelector('.fields__multi-val-select-text')
                  saved_value_4 = list_select.value
                }

                if (!saved_value_4 || saved_value_4 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_4 = res.value
                        if (saved_value_4) {
                          list_select.value = saved_value_4
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  list_select.value = saved_value_4;
                }

                list_select.disabled = false;


                break;

              case '5': //связь
                let saved_value_5 = field.querySelector('.fields__simple-text.fields__simple-text--link')

                /*if (saved_value_5.querySelector('.no_access')) {
                    saved_value_5.querySelector('.no_access').remove()
                }*/

                /*let edit_button = field.querySelector('.fields__fast-edit-button--edit')
                edit_button.style.display = 'initial'*/

                //$.ajax({
                //  url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + edit_field_id,
                //    success: function (xhr) {
                //        var res = JSON.parse(xhr);


                        //let value = $(res.value)[1].innerHTML потом придумать что нибудь


                        /*if (field.querySelector('.fields__simple-text--link').innerHTML == 'Нет доступа') {
                          field.querySelector('.fields__simple-text--link').innerHTML = ''
                        }*/
                        //field.querySelector('.fields__simple-text--link').innerHTML = value

              //      },
              //      error: function(response) {
              //          
              //           
              //      }
              //  });

                break;


              case '6': //файл

                let file_delete = field.querySelector('.file-cell__btn_delete')
                if (file_delete) {
                  file_delete.style.display = 'initial';
                }

                let file_add_div = field.children[2]
                if (file_add_div) {
                  file_add_div.style.display = 'initial';
                }

                break;

              case '7': //пользователь

                let saved_value_7;

                let user_select = field.querySelector('.hidden-input--select')

                if (user_select) {
                  saved_value_7 = user_select.value
                } else {
                  user_select = field.querySelector('.fields__multi-val-select-text')
                  saved_value_7 = user_select.value
                }

                if (!saved_value_7 || saved_value_7 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_7 = res.value
                        if (saved_value_7) {
                          user_select.value = saved_value_7
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  user_select.value = saved_value_7;
                }

                user_select.disabled = false;


                break;
                /*
              case '9': //изображение
                let saved_value_9 = field.querySelector('.fancybox-item.image-link')

                if (field.querySelector('.fields__value')) {
                  field.querySelector('.fields__value').innerHTML = ''
                } else {
                  field.innerHTML = ''
                }

                $.ajax({
                  url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + edit_field_id,
                  success: function (xhr) {
                      var res = JSON.parse(xhr);

                      $(res.value).each( (key) => {
                          if (field.querySelector('.fields__value')) {
                            field.querySelector('.fields__value').append($(res.value)[key])
                          } else {
                            field.prepend($(res.value)[key])
                          }
                      })
                  },
                  error: function(response) {
                      
                       
                  }
                });

                let image_file_input = document.createElement('input')
                image_file_input.setAttribute('onchange', `addFile('${edit_field_id}', '${line_id}', '${show_fields.table.id}')`)
                image_file_input.setAttribute('type', 'file')
                image_file_input.setAttribute('accept', 'image/*')
                image_file_input.style.cssText = 'display:none;'
                image_file_input.id = `file_input_${edit_field_id}_${line_id}`

                field.append(image_file_input)

                let image_file_add_wrap = document.createElement('div')
                let image_br = document.createElement('br')
                let image_file_add_button = document.createElement('a')
                image_file_add_button.setAttribute('href', '#')
                image_file_add_button.setAttribute('onclick', `addNewFile(${edit_field_id}, ${line_id})`)
                image_file_add_button.classList.add('file_input__a')
                image_file_add_button.innerHTML = 'Добавить'

                image_file_add_wrap.append(image_br)
                image_file_add_wrap.append(image_file_add_button)

                field.append(image_file_add_wrap)

                break;
              */
              case '14': //группа
                let saved_value_14;

                let group_select = field.querySelector('.hidden-input--select')

                if (group_select) {
                  saved_value_14 = group_select.value
                }

                if (!saved_value_14 || saved_value_14 == 'Нет доступа') {
                  $.ajax({
                    url: 'update_value.php?display_value&table=' + show_fields.table.id + '&line=' + line_id + '&field=' + edit_field_id,
                    success: function (xhr) {
                        var res = JSON.parse(xhr);
                        saved_value_14 = res.value
                        if (saved_value_14) {
                          group_select.value = saved_value_14
                        }
                    },
                    error: function(response) {
                        
                         
                    }
                  });
                } else {
                  group_select.value = saved_value_14;
                }

                group_select.disabled = false;

                break;
            }
        })

    }
}

function showHeaderCell(field_id) {
  let header_cell = document.querySelector(`.fields__cell--header.col_${field_id}`)
//   header_cell.style.display = 'table-cell'
}

function checkResp(resp) {
    var inserted, changed, saved, deleted, message;

    (resp.indexOf('message') !== -1) ? message = resp.indexOf('message') : message = 9999999;
    (resp.indexOf('inserted') !== -1) ? inserted = resp.indexOf('inserted') : inserted = 9999999;
    (resp.indexOf('changed') !== -1) ? changed = resp.indexOf('changed') : changed = 9999999;
    (resp.indexOf('saved') !== -1) ? saved = resp.indexOf('saved') : saved = 9999999;
    (resp.indexOf('deleted') !== -1) ? deleted = resp.indexOf('deleted') : deleted = 9999999;

    var sortedArr = [message, inserted, changed, saved, deleted].sort(compareNumeric);

    switch (sortedArr[0]) {
        case message:
            resp = resp.substr(resp.indexOf('message'));
            break
        case inserted:
            resp = resp.substr(resp.indexOf('inserted'));
            break;
        case changed:
            resp = resp.substr(resp.indexOf('changed'));
            break;
        case saved:
            resp = resp.substr(resp.indexOf('saved'));
            break;
        case deleted:
            resp = resp.substr(resp.indexOf('deleted'));
            break;
        default:
    }
    return resp;
}

//Функция для сортировки массива
function compareNumeric(a, b) {
    return a - b;
}

function setNewHeight(line_id, field_id) {
    /*var id = line_id + "." + field_id; //Вернуть при необходимости
    var currentRow = $('#tr' + line_id);
    currentRow.css('height', '');
    currentRow.find('.fields__cell:nth-child(2)').css('height', '');
    currentRow.find('.fields__cell:first-child').css('height', '');
    var currentCell = document.getElementById('td' + id);
    var newColumnHeight = currentRow.height();

    var secondSellHeight = currentRow.find('.fields__cell:nth-child(2)').height();

    if (secondSellHeight > newColumnHeight) {
        newColumnHeight = secondSellHeight;
    }

    var cellPaddingTop = parseInt(getComputedStyle(currentCell).paddingTop);
    var cellPaddingBottom = parseInt(getComputedStyle(currentCell).paddingBottom);

    currentRow.find('.fields__cell:first-child').css('height', (newColumnHeight - BORDER_SIZE) + 'px');
    currentRow.find('.fields__cell:nth-child(2)').css('height', (newColumnHeight - BORDER_SIZE) + 'px');
    currentRow.css('height', newColumnHeight + cellPaddingTop + cellPaddingBottom);*/
}

function close_text(line_id, field_id) {
    var id = line_id + "." + field_id;

    document.getElementById('rv' + id).style.display = 'block';
    document.getElementById('fv' + id).style.display = 'none';

    if (document.getElementById('td' + id).style.width) document.getElementById('td' + id).style.whiteSpace = '';
    else document.getElementById('td' + id).style.whiteSpace = 'nowrap';
    var currentCell = document.getElementById('td' + id);
    var cellPaddingTop = parseInt(getComputedStyle(currentCell).paddingTop);
    var cellPaddingBottom = parseInt(getComputedStyle(currentCell).paddingBottom);
    var currentRow = $('#tr' + line_id);

    currentRow.find('.fields__cell:first-child').css('height', (prevColumnHeight[id] - cellPaddingBottom - cellPaddingTop) + 'px');
    currentRow.find('.fields__cell:nth-child(2)').css('height', (prevColumnHeight[id] - cellPaddingBottom - cellPaddingTop) + 'px');
    currentRow.find('.fields__cell:nth-child(3)').css('height', (prevColumnHeight[id] - cellPaddingBottom - cellPaddingTop) + 'px');

    setNewHeight(line_id, field_id);
}

function on_document_click(event) {
    if (ignore_document_click) {
        ignore_document_click = 0;
        return false;
    }
    if (document.getElementById('fields__dropdown-menu')) document.getElementById('fields__dropdown-menu').style.display = 'none';
}

function createPrevColorArr() {
    $('.fields__row--simple').each(function () {
        var row_id = $(this).attr('id').replace(/\D+/g, "");
        prevColor[row_id] = {};
        $(this).find($('.fields__cell')).each(function () {
            prevColor[row_id][$(this).attr('field_id')] = $(this).css('background-color');
        });
    });
}

/**
 * Предназначен только для таблицы для фиксированного поиска
 */
function set_events_to_ac() {
    var comboboxes = $('#fix_search_form .combobox');

    if (comboboxes.length > 0) {
        var table_huata = init_data();
        comboboxes.each(function (i, combobox) {
            var ac = $(combobox).next().find($('.autocomplete__input'));
            ac.attr('field_id', $(combobox).attr('field_id'));
            ac.attr('name', $(combobox).attr('ac_name'));
            if ($(combobox).hasClass('combobox--multiple')) {
                ac.on('change blur', addSelectVal);
            } else if (parseInt(table_huata['fix_search_submit']) === 0) {
                // значение из select по атрибуту ac_value
                var ac_first_val = $(combobox).attr('ac_value'),
                    child_field_id;
                ac.on('change blur', function () {
                    // $(this) является инпутом autocomplete
                    child_field_id = $(`#fix_search_${$(this).attr('field_id')}`).attr('fixed-search-child-field');
                    if (ac_first_val !== $(this).val()) {
                        if ($(this).val() == " ") {
                          $(this).val('');
                        }
                        $(`input[name*='fix_search[${child_field_id}][value]']`).val('');
                        document.getElementById('fix_search_form').submit();
                    } else {
                        return;
                    }
                });
            }
        });
    }
}

function onMouseOver(line) {
    var id = parseInt(line);
    if (id) {
        var row = $("#tr" + line);

        row.addClass('back_tr');
        $('.fields__resize-btn-container').addClass('back_tr');
    }
}

// Вставляем стандартный перевод строки
function insert_next_line(element) {
    insertTextAtCursor("<br>");
}

// Показать опции псевдо-селекта
function viewPseudoSelectOptions(fieldId) {
    if (document.getElementById("pseudo_select_options" + fieldId).style.display != "flex") {
        $(".pseudo_select_options").css("display", "none");
        if ($("#pseudo_select_options" + fieldId + " input").length != 0)
            document.getElementById("pseudo_select_options" + fieldId).style.display = "flex";
    }
    else
        document.getElementById("pseudo_select_options" + fieldId).style.display = "none";
}

function onMouseOut(line) {
    var id = parseInt(line);
    if (id) {
        var row = $("#tr" + line);
        row.removeClass('back_tr');
        $('.fields__resize-btn-container').removeClass('back_tr');
    }
}
// подстройка фиксированного header под ширину таблицы
function setFixedHeaderWidth(is_fixed = false) {
    let border = (i == 0 || i == 1) ? 1 : 0;
    let widthArr = [];

    if (splitColumns == '1') border += 1; // включена опция "Разделять столбцы линией"

    if($('.fields__wrap').find('div.fields__cell-group--title').length > 0){
        row.eq(1).find(fieldsCell).each(function (i, cel) {
            widthArr[i] = $(cel).width() + border;
        });
    }
    else {
        row.eq(0).find(fieldsCell).each(function (i, cel) {
            widthArr[i] = $(cel).width() + border;
        });
    }
    $('.fields__row--header').find('.fields__cell--header').each((i, cell) => {
        if (!is_fixed) {
          if (i !== 0) {
            const width = widthArr[i];
            let totalWidth = widthArr.length < 5 ? width : (width > other_field_max_width ? other_field_max_width : (width < other_field_min_width ? other_field_min_width : width));
            if ($(cell).hasClass('fields__cell--number-header') || is_fixed) {
                totalWidth = width;
            }
            if (document.querySelector('.fields__row--header.fields__row--fixed')) {
              $(cell).css({
                'width': totalWidth,
                'max-width': totalWidth + 'px',
                'min-width': totalWidth + 'px',
              });
            }

          }
        } else {
          const width = widthArr[i];
          let totalWidth = widthArr.length < 5 ? width : (width > other_field_max_width ? other_field_max_width : (width < other_field_min_width ? other_field_min_width : width));
          if ($(cell).hasClass('fields__cell--number-header') || is_fixed) {
              totalWidth = width;
          }
          if (document.querySelector('.fields__row--header.fields__row--fixed')) {
            $(cell).css({
              'width': totalWidth,
              'max-width': totalWidth + 'px',
              'min-width': totalWidth + 'px',
            });
          }
        }

    });
}

function setFixedCellWidth() {
    let arr = [];
    let cellWidthArr = [];
    const border = splitColumns == '1' ? 1 : 0;
    let cell = $(row).hasClass('fields__row--group') ? row.eq(1) : row.eq(0);
    const rowWidth = cell.width();

    cell.find(fieldsCell).each(function (i, cell) {
        arr[i] = $(cell).width() + border;
    });
    cell.find('.fields__cell-inner').each(function (id, elem) {
        cellWidthArr[id] = $(elem).width();
    });

    $('.fields__row--info.fields__row--simple').each((i, row) => {
        $(row).css({ 'width': rowWidth });
        $(row).find('.fields__cell-inner').each((idx, inner) => {
            if(idx !== 0 && !$(inner).hasClass('fields__cell-number')){
                $(inner).css({ 'width': cellWidthArr[idx], 'max-width': other_field_max_width });
            }
        });
    });
}

function findColumnFieldId(elem) {
    var column_id = elem.attr('id');
    return parseInt(column_id.substr(7, column_id.length - 1));
}

function setFixedHeaderHeight() {
    rowHeader.find(fieldsCell).eq(0).height(rowHeader.height);
    rowHeader.find(fieldsCell).eq(n_second_column - 1).height(rowHeader.height);
    rowHeader.find(fieldsCell).eq(n_second_column).height(rowHeader.find(fieldsCell).eq(n_second_column - 1).height());
}

function setFixedSearchLinkAttr(select) {
    var field = select.attr('field_id');

    select.parent().find('.autocomplete__input').on('blur', function (event) {
        if (select.val() !== 'null') {
            if (select.attr('ac_value') !== select.val()) {
                select.attr('ac_value', select.val());
                if (select.attr('fixed-search-child-field')) {
                    fixed_search_find_link_fields(select)
                }
            }
        } else {
          if (select.attr('ac_value') !== select.val()) {
            select.attr('ac_value', '');
            // Попытка воссоздать поведение как в расширенных
            // Убрать если втечении года не откамичено
            //select.val(select.find('option:selected').text());
          }
        }
    })
}

function fixed_search_find_link_fields(element) {
    var child_field_link = element.attr('fixed-search-child-field');
    if (child_field_link) {
        var child_field = $('#fix_search_' + element.attr('fixed-search-child-field'));
        if (child_field) {
            child_field.parent().find('.autocomplete__input').val('');
            fixed_search_find_link_fields(child_field);
        }
    }
}

function setExtSearchLinkAttr(field, num) {
    var cond_obj = {};

    var condition = 'cond_field_' + num;
    var field = $('#' + condition).val();
    var joined_search_arr;
    const row = $('#cond_value_' + num).attr('row_k');

    if (typeof subtables_scope === 'undefined') {
        joined_search_arr = search_fields;
    } else {
        joined_search_arr = $.extend({}, search_fields, subtables_scope);
    }
    if (joined_search_arr['i' + field]) {

        cond_obj.field = field;

        if (joined_search_arr['i' + field].child_link_field) {
            cond_obj.child_link_field = joined_search_arr['i' + field].child_link_field;

        }
        if (joined_search_arr['i' + field].parent_link_field) {
            cond_obj.parent_link_field = joined_search_arr['i' + field].parent_link_field;
        }
    }

    if (cond_obj.field !== undefined) {
        if (cond_obj.child_link_field) {
            $('#span_cond_value_' + num).find('.autocomplete__input').attr('ext-search-data-child-field', cond_obj.child_link_field);
        }
        if (cond_obj.parent_link_field) {
            $('#span_cond_value_' + num).find('.autocomplete__input').attr('ext-search-data-parent-field', cond_obj.parent_link_field);
        }

        $('#span_cond_value_' + num).find('.autocomplete__input').attr('ext-search-data-field', cond_obj.field);
        $('#span_cond_value_' + num).find('.autocomplete__input').attr('ext-search-data-condition', num);
        $('#span_cond_value_' + num).find('.autocomplete__input').attr('name', 'set_cond[' + num + '][value' + row + ']');
        $('#span_cond_value_' + num).find('.autocomplete__input').attr('ext-search-prev-val', $('#cond_value_' + num).val());

        $('#span_cond_value_' + num).find('.autocomplete__input').on('blur', function (event) {
            this.value = (this.value === " ") ? "" : this.value;
            this.innerHTML = (this.value === "") ? this.innerHTML = '' : this.innerHTML;
            var prev_val = $(this).attr('ext-search-prev-val');
            if ((prev_val !== $(this).val()) || ((prev_val === $(this).val()) && ((prev_val === '') || (prev_val === '&nbsp')))) {
                $(this).attr('ext-search-prev-val', $(this).val());
                ext_search_find_link_fields(this);
            }
        })
    }
}

function ext_search_find_link_fields(element) {
    var child_field_link = $(element).attr('ext-search-data-child-field');
    if (child_field_link) {
        var child_field = $("input[ext-search-data-field='" + $(element).attr('ext-search-data-child-field') + "']");
        if (child_field) {
            child_field.val('');
            ext_search_find_link_fields(child_field[0]);
        }
    }
}
function extSearchCheckVal(element) {
    var select = $(element).parent().parent().find('.combobox');
    var select_options = $(element).parent().parent().find('.combobox option');
    var element_val = $(element).prev().val();
    select_options.each(function () {
        if ($(this).text() === element_val) {
            select.val($(this).val());
            return;
        }
    });
}

function calcHeightFooter() {
    /*
        Блок для вычисления высоты футера в зависимости от максимального контента справки, чтобы не дергалась
     */

    const legHeadHeight = $('#leg_head').height()
    const legLineHeight = 1
    const legBodyHeight = Math.max($('#leg_table').height(), $('#leg_color').height(), $('#leg_filter').height(), $('#leg_button').height())
    const footerItemOne = $('.fields__row-top-count')[1]
    const footerItemTwo = $('.fields__row-count').height()
    const ftHeight = $('#legend_full').height() + 140;
    const sumHeight = $(footerItemOne).height() + footerItemTwo + legHeadHeight + legLineHeight + legBodyHeight + 100;

    $('footer.fields__footer').height((sumHeight < 200) ? ftHeight : sumHeight)
}

function addFakeField() {
    if($('#f_row').children().length == 2){
        $('.fields__row').each((i, el) => {
            let fake_element = null;
            if($(el).hasClass('fields__row--group') || $(el).hasClass('fields__row--header')){
                fake_element = $('<div class="fake"></div>');
            }
            else {
                fake_element = $('<div class="fields__cell"></div>');
                fake_element.on('mouseup', function(e) {
                    // Находим предыдущий элемент в DOM
                    const $prevElement = $(this).prev();
                    
                    if ($prevElement.length) {
                        // Симулируем клик на предыдущем элементе
                        $prevElement.trigger('mouseup');
                    } else {
                    }
                })
            }

            $(el).append(fake_element);
        });
    }
}

/*==EVENTS==*/

// Ловим клики по всему документу
if (document.addEventListener)
    // Firefox, Google Chrome, Safari, Opera
    document.addEventListener("mouseup", on_mouse_up_global, false);
else if (document.attachEvent)
    // IE
    document.attachEvent("onmouseup", on_mouse_up_global);

document.onclick = on_document_click;

function init_fields_data(table_id, line_id) {
    $.ajax({
        method: 'GET',
        url: 'get_value.php?&show_fields&table=' + table_id + '&line=' + line_id,
        success: function (data) {
            show_fields = JSON.parse(data);
        },
        error: function () {
        }
    });
}

function setAddLinkFieldsBlockPoints(e) {
  if ($(e.target).hasClass('fields__fast-edit-button__multiple-link--add')) {
    var offsetPos = $(e.target).parents('.fields__row').position();
    var offset = $(e.target).parents('.fields__cell').offset();
    var rowHeight = $(e.target).parents('.fields__row').height();
    var inputWidth = $(e.target).parents('.fields__cell').find('.select2-container').width();
    var overlayBlock = $(e.target).parents('.fields__cell').find('.user-data__row-wrap');

    var summWidth = overlayBlock.width() + offset.left;
    var triangleElem = overlayBlock.children('.user-data__add-link-triangle')[0];

    // Проверка, выходит ли блок за пределы видимости окна браузера пользователя
    if ((offset.left + overlayBlock.width() + inputWidth) > $(window).width()) {
        addLinkFieldsBlockPoints.left = 0 - overlayBlock.width() + inputWidth;
        triangleElem.style.left = '85%';
    } else {
        addLinkFieldsBlockPoints.left = 0;
        triangleElem.style.left = '5%';
    }

    addLinkFieldsBlockPoints.top = 50;
  } else {
    if ($(this).parents('.user-data__value--add').length !== 0) return;

    // Записываем глобальный id поля
    globalActiveFieldId = $(this).parent().prev().attr('field_id');
    globalActiveLineId = $(this).parent().prev().attr('line_id');
    // Клик по таблице
    isTableTarget = 1;

    // Вычисляем положение popup формы добавления полей
    var offsetPos = $(this).parents('.fields__row').position();
    var offset = $(this).parents('.fields__cell').offset();
    var rowHeight = $(this).parents('.fields__row').height();
    var inputWidth = $(this).width();
    var overlayBlock = $(this).parents('.fields__cell').find('.user-data__row-wrap');

    var summWidth = overlayBlock.width() + offset.left;
    var triangleElem = overlayBlock.children('.user-data__add-link-triangle')[0];

    // Проверка, выходит ли блок за пределы видимости окна браузера пользователя
    if (summWidth > $(window).width()) {
        let summLeft = offset.left - overlayBlock.width() + inputWidth;
        addLinkFieldsBlockPoints.left = summLeft;
        triangleElem.style.left = '85%';
    } else {
        addLinkFieldsBlockPoints.left = offset.left - 20; // 20 - подгон
        triangleElem.style.left = '5%';
    }

    addLinkFieldsBlockPoints.top = offsetPos.top + rowHeight - 35; // 35 - подгон
  }
}

$('#sel_records').delegate('.autocomplete__input', 'click', setAddLinkFieldsBlockPoints);

$('#ext_search_form').delegate('.autocomplete__input', 'click', function (e) {
    globalActiveFieldId = $(this).parent().prev().attr('field_id');
    isTableTarget = 1;
});

$('#fields_buttons_table').delegate('.autocomplete__input', 'click', function (e) {
    globalActiveFieldId = $(this).parent().prev().attr('field_id');
    isTableTarget = 1;
});

$('div[id^=add_link_block]').off('click');

/**
 * Метод, инициализирующий уникальные поля
 * @returns {{}}
 */
function init_uniq_fields() {
    var result = {};

    $('.fields__cell--header[data-uniq]').each(function (i, item) {
        result[item.dataset.field_id] = {
            'type_field': item.dataset.type_field,
            'name_field': item.dataset.name_field
        }
    });

    return result;
}

/**
 * Метод устанавливает цвет текста, для полей с опцией префикса или постфикса
 * Срабатывает для полей с форматированием
 */
function colorPrefixAndPostfix() {
  let fields = $('.fields__cell.custom-color');
  fields.each(function(i, elem) {
    let fontColor = $(elem).css('color');
    let prefix = $(elem).find('.fields__text-prefix');
    prefix.css('color', fontColor);
    let postfix = $(elem).find('.fields__text-postfix');
    postfix.css('color', fontColor);
  })
}

/**
 * Метод для полей число в табличном виде
 * Убирает 0 при фокусировке
 */
function removeZeroVal(input) {
  const value = (input.value || '').replace(/ /g, '');

  // целая часть
  let whole_part = Number(value.indexOf(',') != '-1' ? value.substr(0, value.indexOf(',')) : value);
  // дробная часть
  let fraction = Number(value.indexOf(',') != '-1' ? value.substr(value.indexOf(',') + 1) : value);

  if (whole_part == 0 && fraction == 0) {
    input.value = '';
  }
}

/**
 * Метод для полей число в табличном виде
 * Добавляет 0 при расфокусировке
 */
function addZeroVal(input) {
  if (input.value != '') return;
  input.value = '0';
}

document.addEventListener('DOMContentLoaded', function() {
  var customSelectWrappers = document.querySelectorAll('.custom-select-wrapper');
  customSelectWrappers.forEach(function(wrapper) {
    var customSelect = wrapper.querySelector('.custom-select');
    var selectName = customSelect.getAttribute('data-select-name');
    var hiddenInput = wrapper.querySelector('.hidden-select-value');
    var selectSelected = customSelect.querySelector('.select-selected');
    var selectItems = customSelect.querySelector('.select-items');

    initializeSelectedText(selectSelected, selectItems, hiddenInput);

    customSelect.addEventListener('mouseenter', function(e) {
      selectItems.classList.remove('select-hide');
      selectSelected.classList.add('select-visible');
    });

    customSelect.addEventListener('mouseleave', function(e) {
      selectItems.classList.add('select-hide');
      selectSelected.classList.remove('select-visible');
    });

    var selectItemsDivs = selectItems.querySelectorAll('.select-item');
    selectItemsDivs.forEach(function(item) {
      item.addEventListener('click', function(e) {
        updateSelectedValue(this, selectSelected, hiddenInput, selectItems);
        onSelectChange(selectName, hiddenInput.value);
      });
    });
  });

  // Закрытие выпадающего списка при клике вне его
  document.addEventListener('click', function(e) {
    if (!e.target.matches('.select-selected, .select-item')) {
      var openedDropdowns = document.querySelectorAll('.select-items:not(.select-hide)');
      openedDropdowns.forEach(function(openedDropdown) {
        openedDropdown.classList.add('select-hide');
      });
    }
  });
});

/**
 * Инициализирует текст выбранного элемента выпадающего списка
 * @param {HTMLElement} selectSelected - элемент, отображающий выбранное значение
 * @param {HTMLElement} selectItems - контейнер с элементами списка
 * @param {HTMLElement} hiddenInput - скрытый input, хранящий выбранное значение
 */
function initializeSelectedText(selectSelected, selectItems, hiddenInput) {
  var selectedValue = hiddenInput.value;
  var selectedItem = selectItems.querySelector(`[data-value="${selectedValue}"]`);
  if (selectedItem) {
    selectSelected.textContent = selectedItem.textContent;
    selectedItem.classList.add('same-as-selected');
  }
}

/**
 * Обновляет выбранное значение и текст в выпадающем списке
 * @param {HTMLElement} item - выбранный элемент списка
 * @param {HTMLElement} selectSelected - элемент, отображающий выбранное значение
 * @param {HTMLElement} hiddenInput - скрытый input, хранящий выбранное значение
 * @param {HTMLElement} selectItems - контейнер с элементами списка
 */
function updateSelectedValue(item, selectSelected, hiddenInput, selectItems) {
  var prevSelected = selectItems.querySelector('.same-as-selected');
  if (prevSelected) {
    prevSelected.classList.remove('same-as-selected');
  }
  item.classList.add('same-as-selected');
  selectSelected.textContent = item.textContent;
  hiddenInput.value = item.getAttribute('data-value');
  selectItems.classList.add('select-hide');
}

/**
 * Обрабатывает изменение выбранного значения выпадающего списка
 * @param {string} selectName - имя выпадающего списка
 * @param {string} selectedValue - выбранное значение
 */
function onSelectChange(selectName, selectedValue) {
  let urlParams = new URLSearchParams(window.location.search);

  urlParams.delete('archive');
  urlParams.delete('deleted');
  urlParams.delete('all');

  if (selectName === 'filter') {
    urlParams.delete('filter');
  }

  // Добавляем новый параметр в зависимости от выбранного значения
  if (selectName === 'type') {
    if (selectedValue !== 'active') {
      urlParams.set(selectedValue, '');
    }
  } else if (selectName === 'filter') {
    urlParams.set('filter', selectedValue);
  }

  window.location.search = urlParams.toString();
}

/**
 * Применяет отступы к элементам .fields__value и .fields__simple-text, если в том же контейнере .fields__cell-inner
 * присутствуют элементы .fields__text-prefix или .fields__text-postfix.
 */
function applyPaddingToFields() {
  $('.fields__cell-inner').each(function() {
      var $container = $(this);
      var hasPrefix = $container.find('.fields__text-prefix').length > 0;
      var hasPostfix = $container.find('.fields__text-postfix').length > 0;

      if (hasPrefix) {
          $container.find('.fields__value, .fields__simple-text').css({'padding-left': '7px'});
      }
      if (hasPostfix) {
          $container.find('.fields__value, .fields__simple-text').css({'padding-right': '7px'});
      }
  });
}

function activeResizeBtn($this_parent) {
    $this_parent.closest('.fields__cell-inner').find('.fields__resize-btn-container .fields__resize-btn').trigger('click');
}

/**
 * Применяет отступы к элементам .fields__value и .fields__simple-text, если в том же контейнере .fields__cell-inner
 * присутствуют элементы .fields__text-prefix или .fields__text-postfix.
 */
function applyPaddingToFields() {
  $('.fields__cell-inner').each(function() {
      var $container = $(this);
      var hasPrefix = $container.find('.fields__text-prefix').length > 0;
      var hasPostfix = $container.find('.fields__text-postfix').length > 0;

      if (hasPrefix) {
          $container.find('.fields__value, .fields__simple-text').css({'padding-left': '7px'});
      }
      if (hasPostfix) {
          $container.find('.fields__value, .fields__simple-text').css({'padding-right': '7px'});
      }
  });
}

function activeResizeBtn($this_parent) {
    $this_parent.closest('.fields__cell-inner').find('.fields__resize-btn-container .fields__resize-btn').trigger('click');
}
