{include file="./index_top.tpl"}
<script type="text/javascript">
    // значения для системной подсказки
    var help_section = 'Settings';
    var help_sub_section = 'Tips';
    var dateFieldsCount = '{$date_fields_count}';
    var hasDateFields = parseInt(dateFieldsCount);

    const isShowAdditionalButton = !!({$additional|default:'false'});
    const additionalButtons = Object.values({$all_buttons});
    const selectedAdditionalButton = {$additional_id|default:0};

    cpkNewCol = "{$lang.cp_new_color}";
    cpkCurCol = "{$lang.cp_cur_color}";
    {literal}
    /**
     Состояние, аналогичное React, для отслеживания и обновления значения.
      * 
      * @param any initialValue - Начальное значение состояния.
    * @returns Array Массив, содержащий:
    *  - Функция для получения текущего значения состояния.
    *  - Функция для обновления состояния.
    *  - Функция для подписки на изменение состояния.
    */
    const useState = (initialValue) => {
      let value = initialValue; // Храним текущее состояние
      const listeners = new Set(); // Множество слушателей изменений состояния

      // Функция для обновления состояния
      const setState = (newValue) => {
        // Если передано как функция, вызываем её с текущим значением
        if (typeof newValue === 'function') {
          value = newValue(value);
        } 
        // Если передан объект, создаем новый объект для предотвращения мутации
        else if (typeof newValue === 'object' && newValue !== null) {
          value = JSON.parse(JSON.stringify(newValue)); // Создаем новый объект (глубокое копирование)
        } else {
          // Для примитивных значений просто присваиваем
          value = newValue;
        }
        
        // Уведомляем всех подписчиков о новом значении
        listeners.forEach((listener) => listener(value));
      };

      // Функция для подписки на изменения состояния
      const onStateChange = (listener) => {
        listeners.add(listener);
        return () => listeners.delete(listener); // Возвращаем функцию для отмены подписки
      };
      // Возвращаем массив с функцией для получения значения, функцией для его обновления и функцией подписки
      return [() => value, setState, onStateChange]; 
    };
    /**
     * Динамический рендер элементов настройки ДД в информере
     * @todo Добавить комментарии к компонентам
    */
  {/literal}
</script>
<script language="JavaScript" type="text/javascript">
    var under_mouse_object = 0;
    var last_focus = 0;

    function insert_field(area) {
        message = document.getElementById(area);
        ins_field = document.getElementById('ins_field_' + area);
        if (document.selection) {
            message.focus();
            document.selection.createRange().text = ins_field.value;
        }
        else {
            message.value = message.value.substr(0, message.selectionStart) + ins_field.value + message.value.substr(message.selectionEnd);
        }
    }
    {literal}
    function strtotime(str, now) {
        // http://kevin.vanzonneveld.net
        // +   original by: Caio Ariede (http://caioariede.com)
        // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +      input by: David
        // +   improved by: Caio Ariede (http://caioariede.com)
        // +   improved by: Brett Zamir (http://brett-zamir.me)
        // +   bugfixed by: Wagner B. Soares
        // +   bugfixed by: Artur Tchernychev
        // +      input by: wookie
        // %        note 1: Examples all have a fixed timestamp to prevent tests to fail because of variable time(zones)
        // *     example 1: strtotime('+1 day', 1129633200);
        // *     returns 1: 1129719600
        // *     example 2: strtotime('+1 week 2 days 4 hours 2 seconds', 1129633200);
        // *     returns 2: 1130425202
        // *     example 3: strtotime('last month', 1129633200);
        // *     returns 3: 1127041200
        // *     example 4: strtotime('2009-05-04 08:30:00');
        // *     returns 4: 1241418600
        var i, l, match, s, parse = '';

        str = (str + '').replace(/\s{2,}|^\s|\s$/g, ' ').replace(/[\t\r\n]/g, ''); // unecessary spaces and chars

        if (str === 'now') {
            return now === null || isNaN(now) ? new Date().getTime() / 1000 | 0 : now | 0;
        } else if (!isNaN(parse = Date.parse(str))) {
            return parse / 1000 | 0;
        } else if (now) {
            now = new Date(now * 1000); // Accept PHP-style seconds
        } else {
            now = new Date();
        }

        str = str.toLowerCase();

        var __is = {
            day: {
                'sun': 0,
                'mon': 1,
                'tue': 2,
                'wed': 3,
                'thu': 4,
                'fri': 5,
                'sat': 6
            },
            mon: [
                'jan',
                'feb',
                'mar',
                'apr',
                'may',
                'jun',
                'jul',
                'aug',
                'sep',
                'oct',
                'nov',
                'dec'
            ]
        };

        var process = function (m) {
            var ago = (m[2] && m[2] === 'ago');
            var num = (num = m[0] === 'last' ? -1 : 1) * (ago ? -1 : 1);

            switch (m[0]) {
                case 'last':
                case 'next':
                    switch (m[1].substring(0, 3)) {
                        case 'yea':
                            now.setFullYear(now.getFullYear() + num);
                            break;
                        case 'wee':
                            now.setDate(now.getDate() + (num * 7));
                            break;
                        case 'day':
                            now.setDate(now.getDate() + num);
                            break;
                        case 'hou':
                            now.setHours(now.getHours() + num);
                            break;
                        case 'min':
                            now.setMinutes(now.getMinutes() + num);
                            break;
                        case 'sec':
                            now.setSeconds(now.getSeconds() + num);
                            break;
                        case 'mon':
                            if (m[1] === "month") {
                                now.setMonth(now.getMonth() + num);
                                break;
                            }
                            // fall through
                        default:
                            var day = __is.day[m[1].substring(0, 3)];
                            if (typeof day !== 'undefined') {
                                var diff = day - now.getDay();
                                if (diff === 0) {
                                    diff = 7 * num;
                                } else if (diff > 0) {
                                    if (m[0] === 'last') {
                                        diff -= 7;
                                    }
                                } else {
                                    if (m[0] === 'next') {
                                        diff += 7;
                                    }
                                }
                                now.setDate(now.getDate() + diff);
                                now.setHours(0, 0, 0, 0); // when jumping to a specific last/previous day of week, PHP sets the time to 00:00:00
                            }
                    }
                    break;

                default:
                    if (/\d+/.test(m[0])) {
                        num *= parseInt(m[0], 10);

                        switch (m[1].substring(0, 3)) {
                            case 'yea':
                                now.setFullYear(now.getFullYear() + num);
                                break;
                            case 'mon':
                                now.setMonth(now.getMonth() + num);
                                break;
                            case 'wee':
                                now.setDate(now.getDate() + (num * 7));
                                break;
                            case 'day':
                                now.setDate(now.getDate() + num);
                                break;
                            case 'hou':
                                now.setHours(now.getHours() + num);
                                break;
                            case 'min':
                                now.setMinutes(now.getMinutes() + num);
                                break;
                            case 'sec':
                                now.setSeconds(now.getSeconds() + num);
                                break;
                        }
                    } else {
                        return false;
                    }
                    break;
            }
            return true;
        };

        match = str.match(/^(\d{2,4}-\d{2}-\d{2})(?:\s(\d{1,2}:\d{2}(:\d{2})?)?(?:\.(\d+))?)?$/);
        if (match !== null) {
            if (!match[2]) {
                match[2] = '00:00:00';
            } else if (!match[3]) {
                match[2] += ':00';
            }

            s = match[1].split(/-/g);

            s[1] = __is.mon[s[1] - 1] || s[1];
            s[0] = +s[0];

            s[0] = (s[0] >= 0 && s[0] <= 69) ? '20' + (s[0] < 10 ? '0' + s[0] : s[0] + '') : (s[0] >= 70 && s[0] <= 99) ? '19' + s[0] : s[0] + '';
            return parseInt(this.strtotime(s[2] + ' ' + s[1] + ' ' + s[0] + ' ' + match[2]) + (match[4] ? match[4] / 1000 : ''), 10);
        }

        var regex = '([+-]?\\d+\\s' + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?' + '|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday' + '|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday)' + '|(last|next)\\s' + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?' + '|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday' + '|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday))' + '(\\sago)?';

        match = str.match(new RegExp(regex, 'gi')); // Brett: seems should be case insensitive per docs, so added 'i'
        if (match === null) {
            return false;
        }

        for (i = 0, l = match.length; i < l; i++) {
            if (!process(match[i].split(' '))) {
                return false;
            }
        }

        return now.getTime() / 1000 | 0;
    }

    /**
     * Добавляет указанный интервал времени к дате.
     *
     * @param {Date} date - Исходная дата, к которой необходимо добавить интервал.
     * @param {number} value - Количество единиц времени, которые нужно добавить (может быть отрицательным для вычитания).
     * @param {string} unit - Тип интервала (например, 'year', 'month', 'day', 'hour', 'minute').
     *                        Поддерживаемые значения: 'year', 'month', 'day', 'hour', 'minute'.
     * @returns {Date} - Новый объект Date с добавленным интервалом.
     */
    const addIntervalToDate = (date, value, unit) => {
      const newDate = new Date(date)
      if(unit.includes('year')) 
        newDate.setFullYear(newDate.getFullYear() + value);
      if(unit.includes('month')) 
        newDate.setMonth(newDate.getMonth() + value);
      if(unit.includes('day')) 
        newDate.setDate(newDate.getDate() + value);
      if(unit.includes('hour')) 
        newDate.setHours(newDate.getHours() + value);
      if(unit.includes('minute')) 
        newDate.setMinutes(newDate.getMinutes() + value);
      return newDate;
    }

    /**
     * Форматирует дату в строку формата "YYYY-MM-DD HH:mm:ss".
     *
     * @param {Date} date - Дата, которую нужно отформатировать.
     * @returns {string} - Строка, представляющая дату в формате "YYYY-MM-DD HH:mm:ss".
     */
    const formatDate = (date) => {
      const pad = (num) => (num < 10 ? '0' : '') + num;
      return (
        date.getFullYear() +
        '-' +
        pad(date.getMonth() + 1) +
        '-' +
        pad(date.getDate()) +
        ' ' +
        pad(date.getHours()) +
        ':' +
        pad(date.getMinutes()) +
        ':' +
        pad(date.getSeconds())
      );
    }
    /**
     * Функция высшего порядка для получения диапазона дат на основе типа даты.
     *
     * @param {Object} dateObject - Объект, содержащий ключевые даты начала и конца для различных типов.
     * @param {number} dateObject.endWeek - Конец недели в виде UNIX-метки времени (в секундах).
     * @param {number} dateObject.beginHalfMonth - Начало половины месяца в виде UNIX-метки времени (в секундах).
     * @param {number} dateObject.endHalfMonth - Конец половины месяца в виде UNIX-метки времени (в секундах).
     * @param {number} dateObject.beginMonth - Начало месяца в виде UNIX-метки времени (в секундах).
     * @param {number} dateObject.endMonth - Конец месяца в виде UNIX-метки времени (в секундах).
     * @param {number} dateObject.beginYear - Начало года в виде UNIX-метки времени (в секундах).
     * @param {number} dateObject.endYear - Конец года в виде UNIX-метки времени (в секундах).
     * @returns {Function} - Функция, принимающая параметр `selector`, который определяет, какая дата будет выбрана,
     *                       и возвращает массив из двух объектов `Date` (начало и конец интервала).
     */
    const getDateFromDateObject = (dateObject) => (selector) => {
      const dateType = $('#cond_value_' + selector).val();
      const {
        beginWeek,
        endWeek,
        beginHalfMonth,
        endHalfMonth,
        beginMonth,
        endMonth,
        beginYear,
        endYear,
      } = dateObject
      
      if (dateType === 'week()') 
        return [
          new Date(beginWeek * 1000),
          new Date(endWeek * 1000),
        ]
      if (dateType === 'half_month()') 
        return [
          new Date(beginHalfMonth * 1000),
          new Date(endHalfMonth * 1000),
        ]
      if (dateType === 'month()') 
        return [
          new Date(beginMonth * 1000),
          new Date(endMonth * 1000),
        ]
      if (dateType === 'year()') 
        return [
          new Date(beginYear * 1000),
          new Date(endYear * 1000),
        ]
      if (dateType === 'fix_date') 
        return [
          new Date(strtotime($('#cond_date_' + selector).val()) * 1000),
          new Date(strtotime($('#cond_date_' + selector).val()) * 1000),
        ]

      return [
        new Date(),
        new Date(),
      ]
    }
    {/literal}
    {literal}
    /**
     * Создаёт функцию для получения диапазона дат на основе типа даты.
     *
     * @const {Function} getDate - Функция, возвращающая диапазон дат на основе предоставленного типа даты.
     * @param {Object} dateObject - Объект с ключевыми временными интервалами.
     * @param {number} dateObject.beginWeek - UNIX-метка времени начала недели (в секундах).
     * @param {number} dateObject.endWeek - UNIX-метка времени конца недели (в секундах).
     * @param {number} dateObject.beginHalfMonth - UNIX-метка времени начала половины месяца (в секундах).
     * @param {number} dateObject.endHalfMonth - UNIX-метка времени конца половины месяца (в секундах).
     * @param {number} dateObject.beginMonth - UNIX-метка времени начала месяца (в секундах).
     * @param {number} dateObject.endMonth - UNIX-метка времени конца месяца (в секундах).
     * @param {number} dateObject.beginYear - UNIX-метка времени начала года (в секундах).
     * @param {number} dateObject.endYear - UNIX-метка времени конца года (в секундах).
     */
    {/literal}
    const getDate = getDateFromDateObject({
      beginWeek: {$begin_week},
      endWeek: {$end_week},
      beginHalfMonth: {$begin_half_month},
      endHalfMonth: {$end_half_month},
      beginMonth: {$begin_month},
      endMonth: {$end_month},
      beginYear: {$begin_year},
      endYear: {$end_year},
    })

    {literal}
    /**
     * Вычисляет новую дату на основе переданного интервала, периода и операции.
     *
     * @param {Object} params - Параметры для вычисления новой даты.
     * @param {Array<Date>} params.date - Массив с начальной и конечной датами ([begin, end]).
     * @param {number|string} params.interval - Значение интервала для добавления или вычитания.
     * @param {string} params.period - Тип интервала (например, 'year', 'month', 'day', 'hour', 'minute').
     * @param {string} params.operation - Операция, определяющая, добавить или вычесть интервал ('+ interval' или '- interval').
     * @returns {Array<Date>} - Новый массив дат ([newBegin, newEnd]) с учётом интервала и операции.
     */
    const getNewDate = ({
      date: [begin, end],
      interval,
      period,
      operation,
    }) => {
      if(!interval || !period)
        return [begin, end];
      if (operation.includes('+ interval'))
        return [
          addIntervalToDate(begin, +interval, period),
          addIntervalToDate(end, +interval, period),
        ];

      if (operation.includes('- interval')) 
        return [
          addIntervalToDate(begin, -interval, period),
          addIntervalToDate(end, -interval, period),
        ];

      return [begin, end];
    }
    /**
     * Формирует строку с новой датой на основе параметров интервала, периода и операции.
     *
     * @param {string} selector - строка условия для извлечения данных из DOM.
     * @returns {string} - Строка, представляющая новую дату или диапазон дат.
     *                     Формат зависит от типа даты:
     *                     - Для `curdate()`: возвращается только дата в формате "YYYY-MM-DD".
     *                     - Для других типов (`week()`, `half_month()`, `month()`, `year()`):
     *                       возвращается строка в формате "since_from {startDate} since_to {endDate}".
     *                     - По умолчанию возвращается строка в формате "YYYY-MM-DD HH:mm:ss".
     */
    const getNewDateStr = (selector) => {
      const interval = $('#cond_interval_' + selector).val();
      const period = $('#cond_period_' + selector).val();
      const operation = $('#cond_oper_' + selector).val();

      const [date0, date0_end] = getDate(selector);
      
      const [date1, date1_end] = getNewDate({
        date: [date0, date0_end],
        interval,
        period,
        operation,
      })
      const [date2, date2_end] = [formatDate(date1), formatDate(date1_end)]
      const dateType = $('#cond_value_' + selector).val();
      if (
        dateType !== 'week()' 
        && dateType !== 'half_month()'
        && dateType !== 'month()'
        && dateType !== 'year()'
      ) 
        return date2;
      if (dateType === 'curdate()') 
        return date2.split(' ')[0];
      
      return `${lang['since_from']} ${date2} ${lang['since_to']} ${date2_end}`
    }

    {/literal}
    {literal}
      /**
       * @deprecated
       * 
       * Используйте set_date_promt функцию ниже
      */
    {/literal}
    function set_date_promt1(num) {
        if ($('#cond_value_' + num).val() == 'curdate()' || $('#cond_value_' + num).val() == 'now()' || $('#cond_value_' + num).val() == 'week()' || $('#cond_value_' + num).val() == 'half_month()' || $('#cond_value_' + num).val() == 'month()' || $('#cond_value_' + num).val() == 'year()' || ($('#cond_value_' + num).val() == 'fix_date' && $('#cond_date_' + num).val())) {
            var date_type = $('#cond_value_' + num).val();
            switch (date_type) {
                case 'week()':
                    var date0 = {$begin_week};
                    var date0_end = {$end_week};
                    break
                case 'half_month()':
                    var date0 = {$begin_half_month};
                    var date0_end = {$end_half_month};
                    break
                case 'month()':
                    var date0 = {$begin_month};
                    var date0_end = {$end_month};
                    break
                case 'year()':
                    var date0 = {$begin_year};
                    var date0_end = {$end_year};
                    break
                case 'fix_date':
                    var date0 = strtotime($('#cond_date_' + num).val());
                    var date0_end = strtotime($('#cond_date_' + num).val());
                    break
                default:
                    var date0 = strtotime('now');
                    var date0_end = strtotime('now');
                    break
            }
            if ($('#cond_oper_' + num).val() == " + interval ") {
                if ($('#cond_interval_' + num).val() && $('#cond_period_' + num).val()) {
                    var inter0 = '+' + $('#cond_interval_' + num).val() + ' ' + $('#cond_period_' + num).val();
                    inter1 = strtotime(inter0, date0);
                    var date1 = new Date(inter1 * 1000);
                    inter_end = strtotime(inter0, date0_end);

                    if ((date_type == 'month()') && ($('#cond_period_' + num).val() == ' month'))
                        var date1_end = new Date(date1.getFullYear(), date1.getMonth(), new Date(date1.getFullYear(), date1.getMonth() + 1, 0).getDate(), 23, 59, 59);
                    else
                        var date1_end = new Date(inter_end * 1000);
                } else {
                    return false;
                }
            } else if ($('#cond_oper_' + num).val() == " - interval ") {
                if ($('#cond_interval_' + num).val() && $('#cond_period_' + num).val()) {
                    var inter0 = '-' + $('#cond_interval_' + num).val() + ' ' + $('#cond_period_' + num).val();
                    inter1 = strtotime(inter0, date0);
                    var date1 = new Date(inter1 * 1000);
                    inter_end = strtotime(inter0, date0_end);

                    if ((date_type == 'month()') && ($('#cond_period_' + num).val() == ' month'))
                        var date1_end = new Date(date1.getFullYear(), date1.getMonth(), new Date(date1.getFullYear(), date1.getMonth() + 1, 0).getDate(), 23, 59, 59);
                    else
                        var date1_end = new Date(inter_end * 1000);
                } else {
                    return false;
                }
            } else {
                var date1 = new Date(date0 * 1000);
                var date1_end = new Date(date0_end * 1000);
            }

            if ((date1.getDate()).toString().length == 2) {
                var toDay = (date1.getDate()).toString();
            } else {
                var toDay = '0' + (date1.getDate()).toString();
            }

            if ((date1.getMonth() + 1).toString().length == 2) {
                var month = (date1.getMonth() + 1).toString();
            } else {
                var month = '0' + (date1.getMonth() + 1).toString();
            }

            if ((date1.getHours()).toString().length == 2) {
                var Hours = (date1.getHours()).toString();
            } else {
                var Hours = '0' + (date1.getHours()).toString();
            }

            if ((date1.getMinutes()).toString().length == 2) {
                var Minutes = (date1.getMinutes()).toString();
            } else {
                var Minutes = '0' + (date1.getMinutes()).toString();
            }

            if ((date1.getSeconds()).toString().length == 2) {
                var Seconds = (date1.getSeconds()).toString();
            } else {
                var Seconds = '0' + (date1.getSeconds()).toString();
            }

            var date2 = date1.getFullYear().toString() + '-' + month + '-' + toDay + ' ' + Hours + ':' + Minutes + ':' + Seconds;
            
            if ((date1_end.getDate()).toString().length == 2) {
                var toDay = (date1_end.getDate()).toString();
            } else {
                var toDay = '0' + (date1_end.getDate()).toString();
            }

            if ((date1_end.getMonth() + 1).toString().length == 2) {
                var month = (date1_end.getMonth() + 1).toString();
            } else {
                var month = '0' + (date1_end.getMonth() + 1).toString();
            }

            if ((date1_end.getHours()).toString().length == 2) {
                var Hours = (date1_end.getHours()).toString();
            } else {
                var Hours = '0' + (date1_end.getHours()).toString();
            }

            if ((date1_end.getMinutes()).toString().length == 2) {
                var Minutes = (date1_end.getMinutes()).toString();
            } else {
                var Minutes = '0' + (date1_end.getMinutes()).toString();
            }

            if ((date1_end.getSeconds()).toString().length == 2) {
                var Seconds = (date1_end.getSeconds()).toString();
            } else {
                var Seconds = '0' + (date1_end.getSeconds()).toString();
            }

            var date2_end = date1_end.getFullYear().toString() + '-' + month + '-' + toDay + ' ' + Hours + ':' + Minutes + ':' + Seconds;

            switch (date_type) {
                case 'week()':
                case 'half_month()':
                case 'month()':
                case 'year()':
                    var date3 = lang['since_from'] + ' ' + date2 + ' ' + lang['since_to'] + ' ' + date2_end;
                    break
                default:
                    var date3 = date2;
                    break
            }

            if ($('#cond_value_' + num).val() == 'curdate()') {
                pos_time = date2.indexOf(' ');
                date3 = date2.substr(0, pos_time + 1);
            }
            var term = $('#cond_term_' + num).val();
            switch (term) {
                case '=':
                    var field_str = date3;
                    break
                case '!=':
                    var field_str = lang['none'] + ' ' + date3;
                    break
                case '>':
                    var field_str = lang['later_than'] + ' ' + date3;
                    break
                case '<':
                    var field_str = lang['earlier_than'] + ' ' + date3;
                    break
                case '>=':
                    var field_str = date3 + ' ' + lang['or_later'];
                    break
                case '<=':
                    var field_str = date3 + ' ' + lang['or_earlier'];
                    break
                case ' like ':
                    var field_str = lang['contains'] + ' ' + date3;
                    break
                case ' not like ':
                    var field_str = lang['does_not_contain'] + ' ' + date3;
                    break
            }
            $('#date_promt_' + num).html(field_str + " <span class='help_bt' style='height:16px' title='" + lang.now_tip + "'>");
        }
        else {
            $('#date_promt_' + num).html('');
        }

        if ($('#cond_value_' + num).val() == 'fix_date') {
            $('#date_value_' + num).css("display", "");
        } else {
            $('#date_value_' + num).css("display", "none");
        }

        $('.dtpicker').datetimepicker({
            showOn: 'button',
            dateFormat: 'yy-mm-dd',
            timeFormat: 'HH:mm:ss',
            showAlways: true,
            buttonImage: 'images/calbtn.png',
            buttonImageOnly: true,
            buttonText: 'Calendar',
            showAnim: (('\v' == 'v') ? '' : 'show'),  // в ie не включаем анимацию, тормозит
        }).css('width', '120px');

        const condFieldId = $('#cond_field_' + num).val();
        const condTermVal = $('#cond_term_' + num).val();
        const field = search_fields[condFieldId];
        const fieldType = parseInt(field.type_field);
        const fieldMultVal = parseInt(field.mult_value);
        const isTermFocused = $('#cond_term_' + num).is(':focus');

        if (condTermVal === '=' && isTermFocused) checkFieldForMultiValAndShowTooltip(fieldType, fieldMultVal, 1);
        if (condTermVal === '!=' && isTermFocused) checkFieldForMultiValAndShowTooltip(fieldType, fieldMultVal, 2);
        init_chosen();
    }
    function set_date_promt(num) {
        if ($('#cond_value_' + num).val() == 'curdate()' || $('#cond_value_' + num).val() == 'now()' || $('#cond_value_' + num).val() == 'week()' || $('#cond_value_' + num).val() == 'half_month()' || $('#cond_value_' + num).val() == 'month()' || $('#cond_value_' + num).val() == 'year()' || ($('#cond_value_' + num).val() == 'fix_date' && $('#cond_date_' + num).val())) {
            var date3 = getNewDateStr(num);
            var term = $('#cond_term_' + num).val();
            switch (term) {
                case '=':
                    var field_str = date3;
                    break
                case '!=':
                    var field_str = lang['none'] + ' ' + date3;
                    break
                case '>':
                    var field_str = lang['later_than'] + ' ' + date3;
                    break
                case '<':
                    var field_str = lang['earlier_than'] + ' ' + date3;
                    break
                case '>=':
                    var field_str = date3 + ' ' + lang['or_later'];
                    break
                case '<=':
                    var field_str = date3 + ' ' + lang['or_earlier'];
                    break
                case ' like ':
                    var field_str = lang['contains'] + ' ' + date3;
                    break
                case ' not like ':
                    var field_str = lang['does_not_contain'] + ' ' + date3;
                    break
            }
            $('#date_promt_' + num).html(field_str + " <span class='help_bt' style='height:16px' title='" + lang.now_tip + "'>");
        }
        else {
            $('#date_promt_' + num).html('');
        }

        if ($('#cond_value_' + num).val() == 'fix_date') {
            $('#date_value_' + num).css("display", "");
        } else {
            $('#date_value_' + num).css("display", "none");
        }

        $('.dtpicker').datetimepicker({
            showOn: 'button',
            dateFormat: 'yy-mm-dd',
            timeFormat: 'HH:mm:ss',
            showAlways: true,
            buttonImage: 'images/calbtn.png',
            buttonImageOnly: true,
            buttonText: 'Calendar',
            showAnim: (('\v' == 'v') ? '' : 'show'),  // в ie не включаем анимацию, тормозит
        }).css('width', '120px');

        const condFieldId = $('#cond_field_' + num).val();
        const condTermVal = $('#cond_term_' + num).val();
        const field = search_fields[condFieldId];
        const fieldType = parseInt(field.type_field);
        const fieldMultVal = parseInt(field.mult_value);
        const isTermFocused = $('#cond_term_' + num).is(':focus');

        if (condTermVal === '=' && isTermFocused) checkFieldForMultiValAndShowTooltip(fieldType, fieldMultVal, 1);
        if (condTermVal === '!=' && isTermFocused) checkFieldForMultiValAndShowTooltip(fieldType, fieldMultVal, 2);
        init_chosen();
    }

    // ============ МАСТЕР УСЛОВИЙ ============ //

    var fields_id = [ {foreach $search_fields as $one_field}{$one_field.id}, {/foreach} ]; // массив id полей для правильной сортировки search_fields при его проходе (см. get_fields_options)

    var search_fields = {
        {foreach $search_fields as $one_field}'{$one_field.id}': {
            'id': '{$one_field.id}',
            'table_id': '{$one_field.table_id}',
            'name_field': '{$one_field.name_field|replace:'\\':'\\\\'|replace:"'":"\'"}',
            'type_field':'{$one_field.type_field}',
            'type_value':'{$one_field.type_value_js}',
            'default_value':'{$one_field.default_value_js}',
            'main':'{$one_field.main}',
            'unique':'{$one_field.unique}',
            'mult_value':'{$one_field.mult_value}',
            'pp':'{$one_field.pp}',
            'int_name':'{$one_field.int_name}',
            'view':'{$one_field.view}',
            'view_tb':'{$one_field.view_tb}',
            'view_edit':'{$one_field.view_edit}',
            'view_add':'{$one_field.view_add}',
            'read':'{$one_field.read}',
            'write':'{$one_field.write}',
            'child_link_field':'{$one_field.child_link_field}',
            'parent_link_field':'{$one_field.parent_link_field}',
            's_field_id':'{$one_field.s_field_id}',
            's_table_id':'{$one_field.s_table_id}',
            's_field_filter_id':'{$one_field.s_field_filter_id}',
            'view_html':'{$one_field.view_html}',
            'input_value':"{$one_field.input_value}"
        },
        {/foreach}
    };

    function get_fields_options() {
        var fields_options = "";
        for (var key in fields_id) {
            fields_options += "<option value=" + fields_id[key] + ">" + search_fields[fields_id[key]].name_field + "</option>";
        }
        return fields_options;
    }

    // Получение всех полей с типом Дата
    function get_fields_options_type_date() {
        let date_fields_options = "";

        for (var key in fields_id) {
            if (search_fields[fields_id[key]].type_field == 2) {
                date_fields_options += "<option value=" + fields_id[key] + ">" + search_fields[fields_id[key]].name_field + "</option>";
            }
        }
        return date_fields_options;
    }

    function set_names_to_select_options (minute, hour, day, month, year) {
        var minutes_option = $('#cond_show_period option[value=" minute"]');
        var hours_option = $('#cond_show_period option[value=" hour"]');
        var days_option = $('#cond_show_period option[value=" day"]');
        var months_option = $('#cond_show_period option[value=" month"]');
        var year_option = $('#cond_show_period option[value=" year"]');

        minutes_option.text(minute);
        hours_option.text(hour);
        days_option.text(day);
        months_option.text(month);
        year_option.text(year);
    }

    function set_right_name_to_select_option (input_elem) {
        var cur_input = $(input_elem);
        var input_val = cur_input.val();
        var last_symbol = input_val.slice(-1);
        var last_two_symbols = input_val.slice(-2);

        if (last_symbol == 1 && last_two_symbols != 11) {
            set_names_to_select_options('минуту', 'час', 'день', 'месяц', 'год');
        } else {
            if ((last_symbol > 4 && last_symbol < 10) || last_symbol == 0 || (last_two_symbols > 10 && last_two_symbols < 15)) {
                set_names_to_select_options('минут', 'часов', 'дней', 'месяцев', 'лет');
            } else {
                set_names_to_select_options('минуты', 'часа', 'дня', 'месяца', 'года');
            }
        }
    }

    function set_right_names (value) {
        var last_symbol = value.slice(-1);
        var last_two_symbols = value.slice(-2);

        if (last_symbol == 1 && last_two_symbols != 11) {
            set_names_to_select_options('минуту', 'час', 'день', 'месяц', 'год');
        } else {
            if ((last_symbol > 4 && last_symbol < 10) || last_symbol == 0 || (last_two_symbols > 10 && last_two_symbols < 15)) {
                set_names_to_select_options('минут', 'часов', 'дней', 'месяцев', 'лет');
            } else {
                set_names_to_select_options('минуты', 'часа', 'дня', 'месяца', 'года');
            }
        }
    }

    function get_term_options(field) {
        var term_options = "";
        if (field.type_field == 1 || field.type_field == 2 || field.type_field == 8 || field.type_field == 10 || field.type_field == 12)
            term_options = "<option value='='>{$lang['=']}</option><option value='!='>{$lang['!=']}</option><option value='>'>{$lang['>']}</option><option value='<'>{$lang['<']}</option><option value='>='>{$lang['>=']}</option><option value='<='>{$lang['<=']}</option>";
        if (field.type_field == 3 || (field.type_field == 4 && field.mult_value == 1) || (field.type_field == 5 && field.mult_value == 1) || field.type_field == 6 || (field.type_field == 7 && field.mult_value == 1) || field.type_field == 9 || (field.type_field == 14 && field.mult_value == 1))
            term_options = "<option value='='>{$lang['=']}</option><option value='!='>{$lang['!=']}</option><option value=' like '>{$lang['LIKE']}</option><option value=' not like '>{$lang['NOT LIKE']}</option>";
        if ((field.type_field == 4 && field.mult_value == 0) || (field.type_field == 5 && field.mult_value == 0) || (field.type_field == 7 && field.mult_value == 0) || (field.type_field == 14 && field.mult_value == 0) || field.type_field == 11 || field.type_field == 13 || field.type_field == -2)
            term_options = "<option value='='>{$lang['=']}</option><option value='!='>{$lang['!=']}</option>";
        if (term_options) term_options += "<option value='{ldelim}changed{rdelim}'>{ldelim}{$lang.changed}{rdelim}</option>";
        return term_options;
    }

    function get_value_control(field, term, num) {
        var control = "";
        if (field.input_value.substring(0, 7) == "<option")
            control = "<select class='form-control form-control-160' name='cond_set[" + num + "][value]' id='cond_value_" + num + "' onChange='set_date_promt(" + num + "); set_expert();'>" + field.input_value + "</select>";
        else if (field.type_field == 5)
            control = "<select id='cond_value_" + num + "' class='combobox' name='cond_set[" + num + "][value_link]'></select>";
        else
            control = "<input class='form-control form-control-160' type=text name='cond_set[" + num + "][value]' id='cond_value_" + num + "' onChange='set_expert()'>";
        return control;
    }

    function get_union_options(num) {
        var union_options = "";
        union_options = ((num == last_num) ? "<option value=''></option>" : "") + "<option value=' and '>{$lang.and}</option><option value=' or '>{$lang.or}</option>";
        return union_options;
    }

    /**
     * Индексация для автокомплита
     * @type Number
     */
    var global_ac_index = 0;

    function set_search_controls(num, cond_field, cond_term, cond_value, cond_value_link, cond_date, cond_oper, cond_interval, cond_period, cond_union, open_bracket, close_bracket) {
        if (!cond_field) cond_field = +$('#cond_field_' + num).val();
        if (!cond_term && $('#cond_term_' + num).val()) cond_term = $('#cond_term_' + num).val();
        field = search_fields[cond_field];
        const fieldType = parseInt(field.type_field);
        const fieldMultVal = parseInt(field.mult_value);
        const termFocused =  $('#cond_term_' + num).is(':focus');
        const condFocused =  $('#cond_field_' + num).is(':focus');

        $('#cond_field_' + num).html(get_fields_options());
        $('#cond_field_' + num).val(cond_field);
        $('#cond_term_' + num).html(get_term_options(field));
        $('#cond_term_' + num).val(cond_term ? (termFocused ? cond_term : (fieldMultVal === 1 ? (condFocused ? ' like ' : cond_term) : cond_term)) : (fieldMultVal === 1 ? ' like ' : '='));
        $('#span_cond_value_' + num).html(get_value_control(field, cond_term, num));
        $('#cond_start_field').html(get_fields_options_type_date());

        const condTermVal = $('#cond_term_' + num).val();
        if (condTermVal === '=') checkFieldForMultiValAndShowTooltip(fieldType, fieldMultVal, 1);
        if (condTermVal === '!=') checkFieldForMultiValAndShowTooltip(fieldType, fieldMultVal, 2);

        if (fieldType == 5) {
            create_ac_by_cond('#cond_value_' + num, global_ac_index, cond_value_link, cond_field, '{$table_id}', '{$filter_id}', set_expert);
            global_ac_index++;
        }
        if (fieldType == -1) {
            $('#cond_term_' + num).css("display", "none");
        } else {
            $('#cond_term_' + num).css("display", "");
        }
        if ($('#cond_term_' + num).val() == "{ldelim}changed{rdelim}" || fieldType == -1) {
            $('#span_cond_value_' + num).css("display", "none");
        } else {
            $('#span_cond_value_' + num).css("display", "");
        }
        if (fieldType == 2 || fieldType == 12) {
            $('#date_interval_' + num).css("display", "");
        } else {
            $('#date_interval_' + num).css("display", "none");
        }
        if ((fieldType == 2 || fieldType == 12) && cond_value == 'fix_date') {
            $('#date_value_' + num).css("display", "");
        } else {
            $('#date_value_' + num).css("display", "none");
        }
        if ((fieldType == 2 || fieldType == 12) && !cond_value) {
            $('#cond_value_' + num).val("0000-00-00 00:00:00");
        } else if (fieldType == 13 && !cond_value) {
            $('#cond_value_' + num).val(0);
        } else {
            $('#cond_value_' + num).val(cond_value);
        }
        $('#cond_oper_' + num).html("<option value=''></option><option value=' + interval '>+</option><option value=' - interval '>-</option>");
        $('#cond_period_' + num).html("<option value=''></option><option value=' day'>" + lang.days + "</option><option value=' month'>" + lang.months + "</option><option value=' year'>" + lang.years + "</option><option value=' hour'>" + lang.hours + "</option><option value=' minute'>" + lang.minutes + "</option>");
        $('#cond_date_' + num).val(cond_date);
        $('#cond_oper_' + num).val(cond_oper);
        $('#cond_interval_' + num).val(cond_interval);
        $('#cond_period_' + num).val(cond_period);
        $('#cond_union_' + num).html(get_union_options(num));
        $('#cond_union_' + num).val(cond_union);
        $('#cond_ob_' + num).val(+open_bracket ? 1 : 0);
        $('#cond_cb_' + num).val(+close_bracket ? 1 : 0);
        $('#span_ob_' + num).css('color', +open_bracket ? 'black' : '#ddd');
        $('#span_cb_' + num).css('color', +close_bracket ? 'black' : '#ddd');
        $('#span_ob_' + num).prop('title', +open_bracket ? lang.Disable_bracket: lang.Enable_bracket);
        $('#span_cb_' + num).prop('title', +open_bracket ? lang.Disable_bracket: lang.Enable_bracket);
        set_date_promt(num);
    }

    function add_cond(num, cond_field, cond_term, cond_value, cond_value_link, cond_date, cond_oper, cond_interval, cond_period, cond_union, open_bracket, close_bracket) {
        last_num = num;
        var new_cond = "<div id='cond_" + num + "' class='edit-tip__cond-row'><img alt='{$lang.delete}' title='{$lang.Delete_condition}' src='images/b_drop.png' border=0 style='cursor:pointer; vertical-align:middle; padding-bottom:3px' onclick='del_cond(" + num + ")'> <span id='span_ob_" + num + "' class='brackets' style='cursor:pointer' onclick='set_bracket(\"ob_" + num + "\"); set_expert();'><b>(</b></span> <input type='hidden' name='cond_set[" + num + "][open_bracket]' id='cond_ob_" + num + "'> <select class='form-control form-control-250' name='cond_set[" + num + "][field]' id='cond_field_" + num + "' onChange='set_search_controls(" + num + "); set_expert();'></select> <select class='form-control' name='cond_set[" + num + "][term]' id='cond_term_" + num + "' style='width:150px' onChange='set_search_controls(" + num + "); set_date_promt(" + num + "); set_expert()'></select> <span id='span_cond_value_" + num + "'><input class='form-control' type=text id='cond_value_" + num + "'></span> <span id='date_value_" + num + "'><input class='form-control dtpicker' type=text name='cond_set[" + num + "][date]' id='cond_date_" + num + "' onchange='set_date_promt(" + num + "); set_expert();'></span> <span id='date_interval_" + num + "'><select class='form-control' name='cond_set[" + num + "][oper]' id='cond_oper_" + num + "' style='width:36px' onChange='set_date_promt(" + num + "); set_expert();'></select> <input class='form-control' type=text name='cond_set[" + num + "][interval]' id='cond_interval_" + num + "' style='text-align:right; width:30px;' onChange='set_date_promt(" + num + "); set_expert();'> <select class='form-control' name='cond_set[" + num + "][period]' id='cond_period_" + num + "' style='width:80px' onChange='set_date_promt(" + num + "); set_expert();'></select></span> <span id='span_cb_" + num + "' class='brackets' style='cursor:pointer' onclick='set_bracket(\"cb_" + num + "\"); set_expert();'><b>)</b></span> <input type='hidden' name='cond_set[" + num + "][close_bracket]' id='cond_cb_" + num + "'> <select class='form-control' name='cond_set[" + num + "][union]' id='cond_union_" + num + "' style='width:53px' onChange='if (last_num==" + num + ") add_cond(" + (num + 1) + "); set_expert();'></select> &nbsp; <span id='date_promt_" + num + "' style='color:gray'></span></div>";
        if (num == 1) {
            $("#wizard_set").html(new_cond);
        }
        else {
            prev_cond_union = $('#cond_union_' + (num - 1)).val();
            $('#cond_union_' + (num - 1)).html(get_union_options((num - 1)));
            $('#cond_union_' + (num - 1)).val(prev_cond_union);
            $("#cond_" + (num - 1)).after(new_cond);
        }
        set_search_controls(num, cond_field, cond_term, cond_value, cond_value_link, cond_date, cond_oper, cond_interval, cond_period, cond_union, open_bracket, close_bracket)
    }

    function set_bracket(id) {
        var bracket = ($('#cond_' + id).val() == '1') ? 0 : 1;
        $('#cond_' + id).val(bracket);
        $('#span_' + id).css('color', bracket ? 'black' : '#ddd');
        $('#span_' + id).prop('title', bracket ? lang.Disable_bracket: lang.Enable_bracket);
    }

    function del_cond(num) {
        $('#cond_' + num).remove();
        if (num == last_num) {
            for (var i = num - 1; i > 0; i--) {
                if (document.getElementById('cond_' + i)) {
                    last_num = i;
                    $('#cond_union_' + i).html(get_union_options(i));
                    break;
                }
            }
        }
        if (!$('#wizard_set').html()) add_cond(1);
        set_expert();
    }

    function set_expert() {
        var condition = "";
        var and_count = 0;
        var or_count = 0;

        for (var num = 1; num <= last_num; num++) {
            if (document.getElementById('cond_' + num) && $('#cond_field_' + num).val() != '0') {
                if ($('#cond_field_' + num).val() == '-1') {
                    var one_cond = '{ldelim}new_record{rdelim}';
                } else {
                    var cond_field = +$('#cond_field_' + num).val();
                    var cond_term = $('#cond_term_' + num).val();
                    var cond_value = $('#cond_value_' + num).val();
                    var cond_date = $('#cond_date_' + num).val();
                    var cond_oper = $('#cond_oper_' + num).val();
                    var cond_interval = $('#cond_interval_' + num).val();
                    var cond_period = $('#cond_period_' + num).val();

                    if (search_fields[cond_field].type_field == 5 && search_fields[cond_field].mult_value == 1) {
                        cond_value = '-' + cond_value + '-';
                    }
                    if (cond_term == "{ldelim}changed{rdelim}") {
                        cond_value = '';
                    }
                    if (cond_value == 'null') cond_value = '0';

                    if ($('#cond_field_' + num).val() == '-2')
                        cond_field = "'{ldelim}current{rdelim}'"
                    else
                        cond_field = "`" + search_fields[cond_field].name_field + "`";
                    if (cond_term == " like " || cond_term == " not like ") cond_value = "%" + cond_value + "%";
                    if (cond_value == "fix_date")
                        cond_value = "'" + cond_date + "'";
                    else if (cond_value != "curdate()" && cond_value != "now()" && cond_value != "week()" && cond_value != "month()" && cond_value != "year()" && cond_term != "{ldelim}changed{rdelim}") {
                        cond_value = "'" + cond_value.replace(/\\/g, "\\\\").replace(/'/g, "\\'") + "'";
                    }
                    if (cond_value == "curdate()")
                        var one_cond = "left(" + cond_field + ",10)" + cond_term + cond_value + cond_oper + cond_interval + cond_period;
                    else if (cond_value == "week()") {
                        if (cond_term == "=")
                            var one_cond = "(" + cond_field + ">='{ldelim}begin_week{rdelim}' " + cond_oper + cond_interval + cond_period + " and " + cond_field + "<='{ldelim}end_week{rdelim}'" + cond_oper + cond_interval + cond_period + ")";
                        else if (cond_term == "!=")
                            var one_cond = "(" + cond_field + "<='{ldelim}begin_week{rdelim}' " + cond_oper + cond_interval + cond_period + " or " + cond_field + ">='{ldelim}end_week{rdelim}'" + cond_oper + cond_interval + cond_period + ")";
                        else if (cond_term == ">")
                            var one_cond = cond_field + ">'{ldelim}end_week{rdelim}'" + cond_oper + cond_interval + cond_period;
                        else if (cond_term == "<")
                            var one_cond = cond_field + "<'{ldelim}begin_week{rdelim}'" + cond_oper + cond_interval + cond_period;
                        else if (cond_term == ">=")
                            var one_cond = cond_field + ">='{ldelim}begin_week{rdelim}'" + cond_oper + cond_interval + cond_period;
                        else if (cond_term == "<=")
                            var one_cond = cond_field + "<='{ldelim}end_week{rdelim}'" + cond_oper + cond_interval + cond_period;
                    }
                    else if (cond_value == "month()") {
                        if (cond_term == "=")
                            var one_cond = "(" + cond_field + ">='{ldelim}begin_month{rdelim}' " + cond_oper + cond_interval + cond_period + " and " + cond_field + "<=DATE_FORMAT(LAST_DAY('{ldelim}end_month{rdelim}'" + cond_oper + cond_interval + cond_period + "),'%Y-%m-%d 23:59:59'))";
                        else if (cond_term == "!=")
                            var one_cond = "(" + cond_field + "<='{ldelim}begin_month{rdelim}' " + cond_oper + cond_interval + cond_period + " or " + cond_field + ">=DATE_FORMAT(LAST_DAY('{ldelim}end_month{rdelim}'" + cond_oper + cond_interval + cond_period + "),'%Y-%m-%d 23:59:59'))";
                        else if (cond_term == ">")
                            var one_cond = cond_field + ">DATE_FORMAT(LAST_DAY('{ldelim}end_month{rdelim}'" + cond_oper + cond_interval + cond_period + "),'%Y-%m-%d 23:59:59')";
                        else if (cond_term == "<")
                            var one_cond = cond_field + "<'{ldelim}begin_month{rdelim}'" + cond_oper + cond_interval + cond_period;
                        else if (cond_term == ">=")
                            var one_cond = cond_field + ">='{ldelim}begin_month{rdelim}'" + cond_oper + cond_interval + cond_period;
                        else if (cond_term == "<=")
                            var one_cond = cond_field + "<=DATE_FORMAT(LAST_DAY('{ldelim}end_month{rdelim}'" + cond_oper + cond_interval + cond_period + "),'%Y-%m-%d 23:59:59')";
                    }
                    else if (cond_value == "year()") {
                        if (cond_term == "=")
                            var one_cond = "(" + cond_field + ">='{ldelim}begin_year{rdelim}' " + cond_oper + cond_interval + cond_period + " and " + cond_field + "<='{ldelim}end_year{rdelim}'" + cond_oper + cond_interval + cond_period + ")";
                        else if (cond_term == "!=")
                            var one_cond = "(" + cond_field + "<='{ldelim}begin_year{rdelim}' " + cond_oper + cond_interval + cond_period + " or " + cond_field + ">='{ldelim}end_year{rdelim}'" + cond_oper + cond_interval + cond_period + ")";
                        else if (cond_term == ">")
                            var one_cond = cond_field + ">'{ldelim}end_year{rdelim}'" + cond_oper + cond_interval + cond_period;
                        else if (cond_term == "<")
                            var one_cond = cond_field + "<'{ldelim}begin_year{rdelim}'" + cond_oper + cond_interval + cond_period;
                        else if (cond_term == ">=")
                            var one_cond = cond_field + ">='{ldelim}begin_year{rdelim}'" + cond_oper + cond_interval + cond_period;
                        else if (cond_term == "<=")
                            var one_cond = cond_field + "<='{ldelim}end_year{rdelim}'" + cond_oper + cond_interval + cond_period;
                    }
                    else
                        var one_cond = cond_field + cond_term + cond_value + cond_oper + cond_interval + cond_period;

                    if ((cond_value == "now()" || cond_value == "curdate()") && cond_term.substring(0, 1) == '<')
                        one_cond = "(" + one_cond + " and " + cond_field + "!='0000-00-00 00:00:00')";
                }
                var cond_union = $('#cond_union_' + num).val();
                var open_bracket = $('#cond_ob_' + num).val() == '1' ? '(' : '';
                var close_bracket = $('#cond_cb_' + num).val() == '1' ? ')' : '';
                condition += open_bracket + one_cond + close_bracket + cond_union;
                and_count += (cond_union == ' and ') ? 1 : 0;
                or_count  += (cond_union == ' or ' ) ? 1 : 0;
            }
        }

        if (hasDateFields > 0) {
            var cond_show_date = $('#cond_show_date').val();
            var cond_show_oper = $('#cond_show_oper').val();
            var cond_show_period = $('#cond_show_period').val();
            let startFieldVal = $('#cond_start_field').val() ? $('#cond_start_field').val() : 0;
            let firstOption = $('#cond_start_field option:first');
            var start_field = startFieldVal;
            var all_fields = {$search_fields|json_encode};
            var cur_field = all_fields.filter(field => field['id'] == parseInt(start_field))[0];

            var adddingSymbol = (cond_show_oper == 'after') ? '-' : '+';
            var isSmallPeriod = (cond_show_period == ' minute' || cond_show_period == ' hour');

            if (!startFieldVal) {
                if (firstOption && firstOption.length > 0) {
                    startFieldVal = firstOption.val();
                    $('#cond_start_field').val(startFieldVal);
                }
            }
            var cond_start_field = search_fields[startFieldVal].name_field;

            cond_show_date = parseInt(cond_show_date);

            if (isSmallPeriod) {
                var startFrom = '`' + cond_start_field + '` <= now() ';
                var minutes = cond_show_period == ' hour' ? 60 * cond_show_date : cond_show_date;
                var periodNumber = 30 + (cond_show_oper == 'after' ? 1 : -1) * minutes;
                var periodInterval = periodNumber ? (periodNumber > 0 ? ' -' : ' +') + ' interval ' + Math.abs(periodNumber) +  ' minute' : '';
                var additionalCondForSmallPeriod = ' and `' + cond_start_field + '` > now()' + periodInterval;
            } else {
                var startFrom = 'date(`' + cond_start_field + '`) = curdate() ';
                var additionalCondForSmallPeriod = '';
            }

            var cond_show = startFrom +
                adddingSymbol +
                ' interval ' +
                cond_show_date +
                cond_show_period +
                additionalCondForSmallPeriod;
        }

        if (condition.substring(condition.length - 5) == " and ") condition = condition.substring(0, condition.length - 5);
        if (condition.substring(condition.length - 4) == " or ") condition = condition.substring(0, condition.length - 4);

        if (hasDateFields > 0) {
            if (!$('input:radio[value=hide_cond]').prop('checked')) {
                if (condition.length < 1){
                    condition += cond_show;
                    and_count++;
                } else {
                    cond_show = " and " + cond_show;
                    condition += cond_show;
                    and_count++;
                }
            }
        }

        $("#condition").val(condition);
        if (and_count == 0 || or_count == 0) {
            $('.brackets').css('visibility', 'hidden');
        } else {
            $('.brackets').css('visibility', 'visible');
        }
    }

    function clear_expert () {
        var expert_val = $('#condition').val();

        set_expert();
        expert_val = expert_val.replace(expert_val.substring('`Дата вывода уведомления`'), '');
        set_expert();
    }

    function check_cond_field () {
        if ($('input:radio[value=hide_cond]').prop('checked')) {
            $('#cond_show_time').css('display', 'none');
        } else {
            $('#cond_show_time').css('display', '');
        }
    };

    function check_brackets() {
        var open_brackets = 0;
        var close_brackets = 0;
        for (var num = 1; num <= last_num; num++) {
            if (document.getElementById('cond_' + num) && $('#cond_field_' + num).val() != 0 && !$('#cond_field_' + num).prop("disabled")) {
                open_brackets += +$('#cond_ob_' + num).val();
                close_brackets += +$('#cond_cb_' + num).val();
                if (close_brackets && !open_brackets) break;
            }
        }
        if (open_brackets != close_brackets) {
            return false;
        } else {
            return true;
        }
    }

    $(function () {
      var last_num = 0;
      {foreach from=$cond_set item=cond key=num}
        {if $cond.field}
          add_cond({$num}, {$cond.field}, '{$cond.term}', '{$cond.value|replace:"'":"\'"}', '{$cond.value_link}', '{$cond.date}', '{$cond.oper}', '{$cond.interval}', '{$cond.period}', '{$cond.union}', '{$cond.open_bracket}', '{$cond.close_bracket}');
        {else if $cond_set|count_cb == 1}
          add_cond(1);
        {/if}
      {foreachelse}
        add_cond(1);
      {/foreach}
    });

    function check_sound_files() {
        if ($('#wav_file').val() == '') {
            jalert('{$lang.Not_selected_file} wav.');
            return false;
        }
        if ($('#mp3_file').val() == '') {
            jalert('{$lang.Not_selected_file} mp3.');
            return false;
        }
        if ($('#wav_file').val().substr(-3) != 'wav' || $('#mp3_file').val().substr(-3) != 'mp3') {
            jalert('{$lang.Incorrect_file_type}.');
            return false;
        }
        return true;
    }

    function play_sound() {
        AudioObj = new Audio("sounds/" + document.getElementById('notify_sound').value + ".wav");
        if ((AudioObj.canPlayType("audio/mpeg") != "no") && (AudioObj.canPlayType("audio/mpeg") != ""))
            AudioObj = new Audio("sounds/" + document.getElementById('notify_sound').value + ".mp3");
        AudioObj.play();
    }

    function set_show_time() {
        let cond_text = 'до';

        if ( $('#cond_show_oper').val() == 'after' ) {
            cond_text = 'после';
        }
        $('#cond_show_timeout span').text(cond_text);
    }

    function checkCurOption () {
        let hideCondOption = $('#hide_cond');
        let showCondOption = $('#show_cond');
        let showDateRow = $('#cond_show_time');
        let orCount = $("#condition").val().split(' or ').length - 1;
        let andCount = $("#condition").val().split(' and ').length - 1;
        let allCondCount = orCount + andCount;
        let conditionText = $("#condition").val();
        let expertOption = $('#show_expert_mode');
        let masterOption = $('#show_master_mode');
        let expertText = $("#condition").val();

        if ($('#cond_field_1').val() == 0 && conditionText.replace(/\s/g, '').length > 1 && conditionText.indexOf('interval') > -1) {
            if (masterOption.prop('checked')) {
                setCurrentValuesToOption(conditionText);
            } else {
                setSettingsForReminder(allCondCount, showCondOption, hideCondOption, showDateRow, expertText);
            }
        } else {
            setSettingsForReminder(allCondCount, showCondOption, hideCondOption, showDateRow, expertText);
        }
    }

    function setSettingsForReminder(condCount, showCondOption, hideCondOption, dateRow, expertText) {
        let condSum = 0;

        for (let i = 0; i < (condCount + 1); i++) {
            if ($('#cond_field_' + i) != undefined) {
                condSum++;
            }
        }

        if (expertText.lastIndexOf('minute') > expertText.lastIndexOf('day') &&
            expertText.lastIndexOf('minute') > expertText.lastIndexOf('month') && 
            expertText.lastIndexOf('minute') > expertText.lastIndexOf('year')
        ) {
            if (condCount != 0 && ((condCount + 1) == condSum)) {
                let lastConditon = expertText.split(' and ')[expertText.split(' and ').length - 2];
                setCurrentValuesToOption(lastConditon);
            }
        } else {
            if ((condCount + 1) == condSum) {
                let lastConditon = expertText.split(' and ')[expertText.split(' and ').length - 1];
                setCurrentValuesToOption(lastConditon);
            }
        }
    }

    function setCurrentValuesToOption(lastConditon) {
        let conditionValueField = lastConditon.split('=')[0].replace('`', '').replace('`', '');
        let curValue = '';

        $('#cond_start_field option').each(function() {
            if (this.text == conditionValueField) {
                curValue = this.value;
            }
        });
        $('#cond_start_field').val(curValue);

        if (lastConditon.split('+').length > 1) {
            $('#cond_show_oper').val('before');
            $('#cond_show_timeout span').text('до');
        } else {
            $('#cond_show_oper').val('after');
            $('#cond_show_timeout span').text('после');
        }

        if (lastConditon && lastConditon.length > 0 && lastConditon.split('interval ').length > 1){
            let timeValue = lastConditon.split('interval ')[1].split(' ')[1];
            let timeCountValue = lastConditon.split('interval ')[1].split(' ')[0];
            let startDateFieldName = lastConditon.split('`')[1];

            $('#cond_show_period').val(' ' + timeValue);
            $('#cond_show_date').val(timeCountValue);
            setTextToStartFieldName(startDateFieldName);
            set_right_names(timeCountValue);
        } else {
            setTextToStartFieldName('');
        }
    }

    function setTextToStartFieldName(fieldValue) {
        let startField = $('#cond_start_field');
        let fisrtOptionVal = $('#cond_start_field option:first').val();

        $('#cond_start_field option').each(function(index, item) {
            if (fieldValue === $(item).text()) {
                startField.val($(item).val());
            }
        });

        if (!startField.val()) startField.val(fisrtOptionVal);
    }

    function showCondTime() {
        let timeCondLine = $('#cond_show_time');
        let timeCondOption = $('#cond_time_option');
        let hideCondBtn = $('#hide_cond');
        let isClosed = hideCondBtn.prop('checked');

        timeCondOption.show();
        if (timeCondLine && timeCondLine.length > 0 && !isClosed) {
            timeCondLine.show();
        }
    }

    function hideCondTime() {
        let timeCondLine = $('#cond_show_time');
        let timeCondOption = $('#cond_time_option');

        timeCondOption.hide();
        timeCondLine.hide();
    }

    $(document).ready(function() {
        checkCurOption();
    });
    function check_all(type, obj) {
        {if $parent}
            par = 1;
        {else}
            par = 0;
        {/if}

        if ($(obj).attr("o_value") == "2") {
            $(obj).attr("src", "images/check_on_m.png");
            $(obj).attr("o_value", "1");
            on_off = "on";
        }
        else if ($(obj).attr("o_value") == "1") {
            $(obj).attr("src", "images/check_off_m.png");
            $(obj).attr("o_value", "0");
            on_off = "off";
        }
        else if (par) {
            $(obj).attr("src", "images/check_dis_off_m.png");
            $(obj).attr("o_value", "2");
            on_off = "dis_on";
        }
        else {
            $(obj).attr("src", "images/check_on_m.png");
            $(obj).attr("o_value", "1");
            on_off = "on";
        }

        $('[id^="par_' + type + '_"]').each(function () {
            $(this).attr("src", "images/check_" + on_off + "_m.png");
            if ($(this).attr("o_value") == 3 && on_off == "dis_on")  $(this).attr("src", "images/check_dis_off_m.png");
        });
        $('[id^="' + type + '_"]').each(function () {
            if (on_off == 'on') {
                $(this).val('1');
            }
            else if (on_off == 'dis_on') {
                if ($(this).attr('o_value') == '2') $(this).val('2');
                if ($(this).attr('o_value') == '3') $(this).val('3');
            }
            else {
                $(this).val('0');
            }
            if ($(this).val() != $(this).attr('data-o_value')) {
                $(this).parent().css('backgroundColor', 'rgb(255, 255, 153)');
            }
            else {
                $(this).parent().css('backgroundColor', 'transparent');
            }
        });
    }
    function add_settings() {
        if (document.getElementById('open_add_set').innerHTML == (lang.Additional + '...')) {
            document.getElementById('open_add_set').innerHTML = lang.Hide;
            document.getElementById('additional_settings').style.display = '';
        }
        else {
            document.getElementById('open_add_set').innerHTML = lang.Additional + '...';
            document.getElementById('additional_settings').style.display = 'none';
        }
    }


    /**
     * Проверить заполненность блока условий td#wizard_set
     * @returns { boolean }
     */
    function check_condition_block_is_full() {
        let filled = false;
        $('#wizard_set div.edit-tip__cond-row').each((index, item) => {
            let cond_field = $(item).find('select[id^=cond_field_]');
            if (cond_field.val() != '0') {
                filled = true;
            }
        });

        if ($('input[name=mode]:checked').val() == 'expert') {
        filled = $('#condition').val().length > 0;
        }

        return filled;
    }

    /**
     * Всплытие уведомлений о незаполненных блоках настроек
     * @returns { boolean }
     */
    function onAlertFieldsTip() {
        // Текс уведомления в jalert()
        let listOfText = [];

        // не заполнен блок "Имя"
        if (!document.getElementById('name').value.replace(/ /g,'')) {
            listOfText.push('{$lang.Name_is_empty}');
            document.getElementById('name').style.backgroundColor = 'rgb(255, 224, 224)';
        }

        // не заполнен блок "Указать условия"
        if ((!check_condition_block_is_full() || !document.getElementById('condition').value.replace(/ /g,'')) && !document.getElementById('show_cond').checked) {
            listOfText.push('{$lang.Please_enter_the_cond}');
            document.getElementById('condition').style.backgroundColor = 'rgb(255, 224, 224)';
        }

        // не заполнен блок "Сообщение"
        if (!document.getElementById('message').value.replace(/ /g,'')) {
            listOfText.push('{$lang.Please_enter_the_message}');
            document.getElementById('message').style.backgroundColor = 'rgb(255, 224, 224)';
        }

        if (!check_brackets()) {
            listOfText.push('{$lang.Incorrect_brackets_alert}');
        }

        if (!document.getElementById('push_title').value.replace(/ /g,'') && push_on.checked) {
            listOfText.push('{$lang.not_filed_field} {$lang.Title}');
        }

        if (listOfText.length > 0) {
            jalert(listOfText.join("\n"));
            return false;
        } else {
            return true;
        }
    }


    function displayAnimationTab() {
        let tab = document.querySelector('#animation_on_tab_fields');
        if (tab.classList.contains('active')) {
            tab.classList.remove('active');
        } else {
            tab.classList.add('active');
        }
    }

    function addNewFavicon() {
        let title = document.querySelector('#animation_favicon_file_title');
        let file_input = document.querySelector('#animation_favicon_file');
        let value = file_input.files[0].name;
        title.innerHTML = value;
    }

    function openFaviconFileSelect() {
        let file_input = document.querySelector('#animation_favicon_file');
        file_input.click();
    }

    function deleteFavicon(fileName) {
        $('#view_animation_favicon').hide();
        $('#add_animation_favicon').show();
        $.post('edit_tip.php', 'del_favicon=' + encodeURI(fileName) + '&tip_id={$tip_id}&csrf={$csrf}');
    }
</script>

<style>
#animation_on_tab_fields {
    display: none;
}
#animation_on_tab_fields.active {
    display: table-row-group;
}
</style>
<br>
<div align=center>
    {if $no_save_mode}<img src="images/lock.svg" style="width:20px; padding-right:5px;" title="{$lang.Element_no_edit_msg}">{/if}
    {if $tip_id eq -1}{$lang.Create_tip}{else}{$lang.Edit_tip} "{$name}"{/if} {$lang.of_table} "{$name_table}"
    {if $tip_id != -1 && !$blocked}
        <div style="left: 10px; top: 2px; float: none;"
            onclick="switchOnObject('{$tip_id}')"
            class="switch-btn {if !$disabled}switch-on{/if}"
            id="switch-on-btn_{$tip_id}"></div>
        <script>
            let ajaxObj = new XMLHTTP("edit_tip.php");
            ajaxObj.format = 0;
            ajaxObj.method = "POST";
            function switchOnObject(tip_id) {
                $('#switch-on-btn_'+tip_id).toggleClass('switch-on');
                $('#switch-on-btn_'+tip_id).trigger('on.switch');
                ajaxObj.call('tip_id='+tip_id+'&sel=disable&enbl='+($('#switch-on-btn_'+tip_id).hasClass('switch-on')?1:0)+'&csrf={$csrf}',()=>{});
            }
        </script>
    {/if}
</div>
<br>
{if $message}
    <div style="text-align:center;font-size: 13px;">
        <span id="edit_config__info-maessage" style="color:green">{$message}</span><br><br>
    </div>
{/if}
{if $error}
    <div style="text-align:center;font-size: 13px;">
        <span id="edit_config__info-maessage" style="color:red">{$error}</span><br><br>
    </div>
{/if}
{if $blocked}
    <div style="text-align:center;font-size: 13px;">
        <a href="edit_tip.php?table={$table_id}">{$lang.Return}</a>
    </div>
{else}
<form action="edit_tip.php?table={$table_id}&tip={$tip_id}" method=post id="tip_form" enctype="multipart/form-data">
    <input type=hidden name=back_url value="{$base64_back_url}">
    <input type=hidden name=csrf value="{$csrf}">
    <table border=0 cellpadding=3>
        <tr>
            <td align="right" style="width: 360px;">{$lang.Name}<span class='help_bt' h_id='Name'></span>:</td>
            <td align="left"><input class="form-control form-control-250" type=text size=50 name="name" id="name" value="{$name}"></td>
        </tr>
        <tr>
            <td></td>
        </tr>
        <tr id="wizard_mode" {if $mode=="expert"}style="display:none"{/if}>
            <td align=right>{$lang.Add_conditions}<span class='help_bt' h_id='Add_conditions'></span>:</td>

            <td id="wizard_set" style="padding-left: 21px;"></td>
        </tr>
        <tr id="expert_mode" {if $mode=="wizard"}style="display:none"{/if}>
            <td align=right>{$lang.Add_conditions}<span class='help_bt' h_id='Add_conditions'></span>:</td>
            <td><textarea class="form-control" name="cond_value" id="condition" cols=100 rows=5
                          {if $user.group_id!=1}readonly="1"{/if}>{$cond_value}</textarea></td>
        </tr>
        <tr>
            <td></td>
        </tr>
        {if $date_fields_count > 0}
            <tr id="cond_time_option">
                <td align='right' style='width:195px;'>
                    {$lang.Tip_show_date}:<span class='help_bt' h_id='Cond_show_date'></span>:
                </td>
                <td>
                    <input type="radio" name="display_cond" value="hide_cond" id="hide_cond" {if !$display_cond}checked {/if}
                        onclick="document.getElementById('cond_show_time').style.display='none';
                        clear_expert();">&nbsp;{$lang.No}
                    &nbsp;&nbsp;
                    <input type="radio" name="display_cond" value="show_cond" id="show_cond" {if $display_cond}checked {/if}
                        onclick="document.getElementById('cond_show_time').style.display=''; set_expert();
                        set_date_promt(1); set_right_name_to_select_option(document.getElementById('cond_show_date'));">&nbsp;{$lang.Yes}
                    &nbsp;&nbsp;
                </td>
            </tr>
            <tr id="cond_show_time" {if !$display_cond}style="display:none;"{/if}>
                <td align=right></td>
                <td>
                    <span id="date_interval_1" style="">
                        <select class="form-control dont_use_chosen" name="cond_set[1][show_oper]" id="cond_show_oper" style="width:36px" 
                                onchange="set_date_promt(1); set_expert(); set_show_time();">
                            <option value="before">за</option>
                            <option value="after">через</option>
                        </select>
                        <input class="form-control show-cond-date" type="text" name="cond_set[1][show_date]" id="cond_show_date" 
                               onchange="set_expert(); set_right_name_to_select_option(this);" onkeyup="set_right_name_to_select_option(this);" value="1">
                        <select class="form-control dont_use_chosen" name="cond_set[1][show_period]" id="cond_show_period" style="width:80px" 
                                onchange="set_expert();">
                            <option value=" minute">минуту</option>
                            <option value=" hour">час</option>
                            <option value=" day">день</option>
                            <option value=" month">месяц</option>
                            <option value=" year">год</option>
                        </select>
                        <div class="form-control cond_show_timeout" id="cond_show_timeout">
                        <span>до</span>
                        </div>
                        <select class="form-control" name="cond_set[1][show_start_field]" id="cond_start_field" style="width:250px"
                                onchange="set_date_promt(1); set_expert();">
                        </select>
                    </span>
                </td>
            </tr>
            <tr>
                <td></td>
            </tr>
        {/if}
        <tr>
            <td align=right>{$lang.Message}<span class='help_bt' h_id='Message'></span>:</td>
            <td><textarea class="form-control" name="message" id="message" cols=60 rows=8>{$tip_message}</textarea></td>
        </tr>
        <tr>
            <td align=right>
                {$lang.Insert_field_template}<span class='help_bt' h_id='Insert_field_template'></span>:
            </td>
            <td>
                <select class="form-control form-control-250" id="ins_field_message">{$sel_ins_field}</select>
                <input class="btn btn-default btn-sm" type=button value=OK onclick="insert_field('message')">
            </td>
        </tr>
        <tr>

        <tr>
            <td></td>
        </tr>

        <tbody id="main_set"{if !$main_tip} style="display: none"{/if}>
            <tr>
            <td align=right style="white-space: nowrap">
                {$lang.Action_to_perform}
                <span class='help_bt' h_id='tip_solution'></span>:
            </td>
            <td><textarea class="form-control" name="solution" id="solution" cols=60 rows=15>{$solution}</textarea></td>
            </tr>
            <tr>
                <td
                    {$lang.Insert_field_template}:<span class='help_bt' h_id='Insert_field_template'></span>
                </td>
                <td>
                    <select class="form-control form-control-250" id="ins_field_solution">{$sel_ins_field}</select>
                    <input class="btn btn-default btn-sm" type=button value=OK onclick="insert_field('solution')">
                </td>
            </tr>
        </tbody>
        <tr>
            <td></td>
            <td colspan="3">
                <a href="" id="open_add_set" style="width: 110px;display: inline-block">{if $display_add_set}{$lang.Hide}{else}{$lang.Additional}{/if}</a>
                <a href="" id="config_access_rules" style="width: 110px;display: inline-block">{$lang.Access_rules}</a>
                {if $config.protect_of_elements && $user.id == 1}<a href="" id="protect_switch" style="width: 60px;display: inline-block">{$lang.Protect}</a>{/if}
                {if $tip_id > 0}<a href="edit_log.php?st_date=00&f_text=edit_tip.php?table%3D{$table_id}%26tip%3D{$tip_id}>" target="_blank" style="padding-left:10px">{$lang.Log}</a>{/if}
            </td>
        </tr>
        <tbody id="additional_settings" style="{if !$display_add_set}display:none;{/if} position: relative;">
            <tr>
                    <td align="right" style="width: 360px;">
                        {$lang.animation_on_tab}<span class='help_bt' h_id='animation_on_tab'></span>:
                    </td>
                    <td align="left">
                        <input type="checkbox" name="animation_on_tab" id="animation_on_tab" onclick="displayAnimationTab()" {if $animation_on_tab == 1}checked{/if}>
                    </td>  
            </tr>
            <tr id="animation_on_tab_fields" class="{if $animation_on_tab == 1}active{/if}">
            <td colspan="2" align="center">
                <td style="padding: 40px 0;">
                <td>
                    <table style=" position: absolute; margin-left: 194px; top: 27px;">
                        <tr>
                          <td align="right" style="padding-right:10px;">
                            {$lang.animation_title}<span class='help_bt' h_id='animation_title'></span>:
                          </td>
                          <td align="left">
                            <input class="form-control form-control-250" type="text" size="50" 
                           name="animation_title" id="animation_title" 
                           value="{$animation_title}">
                            </td>
                        </tr>
                        <tr>
                            <td>
                            </td>
                        </tr>
                        <tr>
                            <td align="right" style="padding-right:10px;">
                              {$lang.animation_favicon_file}<span class='help_bt' h_id='animation_favicon_file'></span>:
                            </td>
                            <td align="left">
                              <span id="view_animation_favicon" {if !$animation_favicon}style="display:none"{/if}>
                                <a href="images/favicons/{$animation_favicon}" target="_blank">{$animation_favicon}</a>
                                <img alt="{$lang.delete}" title="{$lang.Delete_file}" 
                                     src="images/b_drop.png" style="cursor:pointer" 
                                     onclick="deleteFavicon('{$animation_favicon}')">
                              </span>
                              <span id="add_animation_favicon" {if $animation_favicon}style="display:none"{/if}>
                                <input onchange="addNewFavicon()" id="animation_favicon_file" 
                                       name="animation_favicon_file" type="file" 
                                       accept=".ico, image/png" style="display:none;">
                                <a href="" onclick="openFaviconFileSelect(); return false;" 
                                   class="file_input__a">{$lang.Add}</a>
                                <span id="animation_favicon_file_title"></span>
                              </span>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td align=right>{$lang.Add_conditions}<span class='help_bt' h_id='Add_conditions'></span>:</td>
                <td>
                    <input type=radio name="mode" value="wizard" id="show_master_mode" {if $mode=="wizard"}checked{/if}
                        onclick="document.getElementById('wizard_mode').style.display='';
                        document.getElementById('expert_mode').style.display='none';
                        check_cond_field(); showCondTime();">{$lang.wizard_mode}
                    &nbsp;&nbsp;
                    <input type=radio name="mode" value="expert" id="show_expert_mode" {if $mode=="expert"}checked{/if}
                        onclick="document.getElementById('expert_mode').style.display='';
                        document.getElementById('wizard_mode').style.display='none';
                        set_expert(); check_cond_field(); hideCondTime();"
                       {if !$all_modules.pro_tariff && $mode != "expert"}disabled title="{$lang.Pro_tariff_func_message}"{/if}>
                    <span {if !$all_modules.pro_tariff && $mode != "expert"}style="color: #999;"{/if}>{$lang.expert_mode}</span>
                    &nbsp;&nbsp;
                </td>
            </tr>
            <tr>
                <td align=right>
                    {$lang.Click_through}<span class='help_bt' h_id='Tip_click_through'></span>:
                </td>
                <td>
                    <select class="form-control form-control-250" name="type_link">
                        <option value="0" {if $type_link == 0}selected{/if}>{$lang.not_to_make}</option>
                        <option value="1" {if $type_link == 1}selected{/if}>{$lang.to_current_line}</option>
                        <option value="2" {if $type_link == 2}selected{/if}>{$lang.to_parent_line}</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td></td>
            </tr>
            <tr>
                <td align=right>{$lang.BackgroundColor}<span class='help_bt' h_id='BackgroundColor'></span>:</td>
                <td>
                    <input type='text' id="bg_color" class="colorSelector" value="{if $bg_color}{$bg_color}{else}#ffff99{/if}" />
                    <input type=hidden id='input_bg_color' name='bg_color'
                        value='{if $bg_color}{$bg_color}{else}#ffff99{/if}'>
                    <script>
                        colorpickerSetings.change = function(color) {
                            $('#input_bg_color').val(color.toHexString());
                        };
                        $('#bg_color').spectrum(colorpickerSetings);
                    </script>
                </td>
            </tr>
            <tr>
                <td></td>
            </tr>
            <tr>
                <td align=right>
                    {$lang.Actions}<span class='help_bt' h_id='Tip_actions'></span>:
                </td>
                <td>
                    <table style="margin-left:-6px">
                        <tr>
                            <td>
                                <span class='help_bt' h_id='Show_in_header'></span>
                                <input type=checkbox name="head_on"
                                    {if $head_on or $tip_id==-1}checked{/if}
                                    onclick="if (this.checked) { document.getElementById('notify_on_chk').disabled=false; document.getElementById('notify_on_chk').checked=true; document.getElementById('notify_set').style.display=''; } else { document.getElementById('notify_on_chk').disabled=true; document.getElementById('notify_on_chk').checked=false; document.getElementById('notify_set').style.display='none'; }">
                            </td>
                            <td colspan=2>{$lang.Show_in_header}</td>
                        </tr>
                        <tr>
                            <td>
                                <span class='help_bt' h_id='notify_on'></span>
                                <input id="notify_on_chk" type=checkbox name="notify_on"
                                    {if ($notify_on and $head_on) or $tip_id==-1}checked{/if}{if !$head_on and $tip_id!=-1} disabled{/if}
                                    onclick="document.getElementById('notify_set').style.display = this.checked?'':'none';"/>
                            </td>
                            <td colspan=2>{$lang.notify_on|lower}</td>
                        </tr>
                        <tbody id="notify_set" {if !$notify_on and $tip_id!=-1}style="display:none"{/if}>
                        <tr>
                            <td style="text-align: right;"><span class='help_bt' h_id='notify_sound'></span></td>
                            <td colspan="2">{$lang.Notify_sound}:
                                <select class="form-control form-control-100" name="notify_sound" id="notify_sound" onchange="$('#play_button').css('visibility',this.value?'visible':'hidden')">
                                    {$sel_sound}
                                </select>
                                <img src="images/play.png" style="margin-bottom:-4px; cursor:pointer;" onclick="play_sound()" id="play_button"> &nbsp;&nbsp;
                                <a href="" onclick="$('#add_files_set').show(); return false;">{$lang.Add}</a>
                                <span id="add_files_set" style="display:none">: &nbsp;&nbsp;
                                    <b>wav</b> <input type=file name="wav_file" id="wav_file"
                                                    onchange="if (this.value.substr(-3)!='wav') jalert('{$lang.Extension_file_need} wav.');">
                                    <b>mp3</b> <input type=file name="mp3_file" id="mp3_file"
                                                    onchange="if (this.value.substr(-3)!='mp3') jalert('{$lang.Extension_file_need} mp3.');">
                                    <input class="btn btn-default btn-sm" type=submit name="add_sound" value="{$lang.Upload}" onclick="return check_sound_files();">
                                </span>
                            </td>
                        </tr>
                        </tbody>
                        <tr>
                            <td nowrap>
                                <span class='help_bt' h_id='Send_to_email'></span>
                                <input type=checkbox name="email_on" {if $email_on}checked{/if}
                                    onclick="document.getElementById('email_set').style.display = this.checked?'':'none';{if !$smtp_ready || $tariff_limits.mailing_off} if (this.checked) jalert('{$lang.tip_alert_no_smtp_servers}');{/if}">
                            </td>
                            <td colspan=2>{$lang.Send_to_email}</td>
                        </tr>
                        <tbody id="email_set" {if !$email_on}style="display:none"{/if}>
                        <tr>
                            <td align=right><span class='help_bt' h_id='mail_template'></span></td>
                            <td align=right>{$lang.mail_template}:</td>
                            <td><select class="form-control form-control-250" name="email_template">{$sel_template}</select></td>
                        </tr>
                        <tr>
                            <td><span class='help_bt' h_id='mail_subject'></span></td>
                            <td align=right>{$lang.mail_subject}:</td>
                            <td><input class="form-control form-control-250" type=text name="email_subject" value="{htmlentities($email_subject|unescape:'html')}" size=120></td>
                        </tr>
                        <tr>
                            <td><span class='help_bt' h_id='mail_note'></span></td>
                            <td></td>
                            <td><i>{$lang.mail_note}</i></td>
                        </tr>
                        </tbody>
                        <tr>
                            <td>
                                <span class='help_bt' h_id='Send_to_SMS'></span>
                                <input type=checkbox name="sms_on" {if $sms_on}checked{/if}
                                    onclick="document.getElementById('sms_set').style.display = this.checked?'':'none';{if !$smsc_ready} if (this.checked) jalert('{$lang.tip_alert_no_smsc_servers}');{/if}">
                            </td>
                            <td colspan=2>{$lang.Send_to_SMS}</td>
                        </tr>
                        <tbody id="sms_set" {if !$sms_on}style="display:none"{/if}>
                        <tr>
                            <td><span class='help_bt' h_id='SMS_sender'></span></td>
                            <td align=right>{$lang.SMS_sender}:</td>
                            <td>
                                {if $sel_signature}
                                    <select class="form-control form-control-250" name="sms_sender">{$sel_signature}</select>
                                {else}
                                    <input class="form-control form-control-250" type=text name="sms_sender" value="{$sms_sender}" size=30>
                                {/if}
                            </td>
                        </tr>
                        </tbody>

                        <tr>
                            <td>
                                <span class='help_bt' h_id='Send_to_PUSH'></span>
                                <input type=checkbox name="push_on" id="push_on" {if $push_on}checked{/if}
                                    onclick="document.getElementById('push_set').style.display = this.checked?'':'none';">
                            </td>
                            <td colspan=2>{$lang.send_push_notification}</td>
                        </tr>
                        <tbody id="push_set" {if !$push_on}style="display:none"{/if}>
                        <tr>
                            <td><span class='help_bt' h_id='PUSH_sender'></span></td>
                            <td align=right>{$lang.Title}:</td>
                            <td>
                                <input class="form-control form-control-250" type=text name="push_title" id="push_title" {if $push_title}value="{$push_title}"{/if} size=30>
                            </td>
                        </tr>
                        </tbody>

                        <tr>
                            <td>
                                <span class='help_bt' h_id='send_to_wazzup'></span>
                                <input
                                  type=checkbox
                                  id="wazzup_extension"
                                  {if $wazzup_extension}checked{/if}
                                  onclick="wazzup_extension_checked()"
                                >
                                <input
                                  type="hidden"
                                  name="wazzup_extension"
                                  id="wazzup_extension_hidden"
                                  value='{if $wazzup_extension}on{else}off{/if}'
                                >
                                <script>
                                  function wazzup_extension_checked() {
                                    if ($('#wazzup_extension').is(':checked')) {
                                      $('#wazzup_extension_hidden').val('on');
                                    } else {
                                      $('#wazzup_extension_hidden').val('off')
                                    }
                                  }
                                </script>
                            </td>
                            <td colspan=2>{$lang.send_from_wazzup}</td>
                        </tr>

                        {if $all_modules.telegram_notify}
                        <tr>
                            <td>
                                <span class='help_bt' h_id='send_to_telegram'></span>
                                <input type=checkbox name="telegram_on" id="telegram_on" {if $telegram_on}checked{/if}>
                            </td>
                            <td colspan=2>{$lang.send_to_telegram}</td>
                        <tr>
                            <td>
                                <span class='help_bt' h_id='send_to_max'></span>
                                <input type=checkbox name="max_on" id="max_on" {if $max_on}checked{/if}>
                            </td>
                            <td colspan=2>{$lang.send_to_max}</td>
                        </tr>
                        {/if}
                    </table>
                </td>
            </tr>
            <tr>
                <td align=right>{$lang.Auto_clean_tip}<span class='help_bt' h_id='Auto_clean_tip'></span>:</td>
                <td><input type=checkbox name="auto_clean" {if $auto_clean}checked{/if}></td>
            </tr>
            <tr>
                <td align=right>{$lang.req_for_execution}<span class='help_bt' h_id='Main_tip'></span>:</td>
                <td><input type=checkbox name="main_tip" {if $main_tip}checked{/if}
                        onclick="if (this.checked) { document.getElementById('main_set').style.display=''; } else { document.getElementById('main_set').style.display='none'; }">
                </td>
            </tr>
            <tr>
            <td align=right>{$lang.Repeat_tip_minutes}<span class='help_bt' h_id='notify_repeat'></span>:</td>
                <td>
                    <input class="form-control" type=text name="notify_repeat"
                        value='{if $notify_repeat}{$notify_repeat}{/if}' style="width:50px;">
                    {$lang.Repeat_tip_minutes2}
                </td>
            </tr>
            <tr>
                <td align=right>{$lang.Use_records}<span class='help_bt' h_id='Use_records'></span>:</td>
                <td>
                    <input type=checkbox name="use_records[]" value=0 {if 0|in_array:$use_records}checked{/if}> {$lang.active}<br>
                    <input type=checkbox name="use_records[]" value=1 {if 1|in_array:$use_records}checked{/if}> {$lang.archive}<br>
                    <input type=checkbox name="use_records[]" value=2 {if 2|in_array:$use_records}checked{/if}> {$lang.deleted}
                </td>
            </tr>
            <tr>
                <td align=right>
                    {$lang.Last_run_time}<span class='help_bt' h_id='tip_last_runtime'></span>:
                </td>
                <td>
                    {$last_runtime} {$lang.seconds}
                </td>
            </tr>
            <tr>
                <td align=right>
                    {$lang.Day_run_time}<span class='help_bt' h_id='tip_day_runtime'></span>:
                </td>
                <td>
                    {$day_runtime} {$lang.seconds}
                </td>
            </tr>
            <tr>
                <td align="right">{$lang.Help}<span class="help_bt" h_id="cond_help"></span>:</td>
                <td><textarea class="form-control" name="help" rows="5" cols="38">{$help}</textarea></td>
            </tr>
        </tbody>
        <tbody 
          id='additional' 
          class='additional'
        >
        </tbody>
        <tr class="config_access_rules_window access_window_header">
            <td align=right></td>
            <td>
                {$lang.Display_in}
            </td>
        </tr>
        <tr class="config_access_rules_window access_window_header">
            <td align="left" valign="top" width="227px"></td>
            <td>
                <div style="float: left;margin:0 0 0 17px;width: 31px; padding-top: 8px; padding-bottom: 6px; text-align: center;">
                    <img style="margin-top:4px;{if $acc_blocked}cursor:not-allowed;{/if}" id="all_read" src="images/check_off_m.png" 
                        {if !$acc_blocked}onclick="check_all('read', this)"{/if} o_value="{if $parent}2{else}0{/if}">
                </div>
            </td>
        </tr>
        {foreach from=$access_data key=gid item=acc}
            <tr class="config_access_rules_window access_window_eyes {if !$acc_blocked}access_checkbox_wrapper{/if}">
                <td style="padding: 0" align=right>{$acc.name}:</td>
                <td style="padding: 0">
                    <div style="float: left;margin:0 50px 0 32px;width: 31px; padding-top: 8px; padding-bottom: 6px; text-align: center;">
                        <input id="read_" name="ob_access[{$gid}]" value="{$acc.access}" data-o_value="{if $acc.access}1{else}0{/if}"
                               data-type="access" data-gid="{$gid}" {if $acc.pid}data-parent="{$acc.parent}"
                               data-pid='{$acc.pid.access}'{/if} type="hidden">
                        <img id="par_read_" {if $acc_blocked}style="cursor:not-allowed"{/if}
                             src="images/check_{if $acc.access==2}dis_on{elseif $acc.access==3}dis_off{elseif $acc.access}on{else}off{/if}_m.png">
                    </div>
                </td>
            </tr>
        {/foreach}
        {if $config.protect_of_elements && $user.id == 1}
        <tbody id="protect_block" style="display:none">
            <tr>
                <td align="right">{$lang.Protected}<span class='help_bt' h_id='Protect_of_element'></span>:</td>
                <td>
                    <input type="checkbox" name="protected" {if $protected}checked{/if} onclick="$('[id^=pr_]').prop('disabled', !this.checked)">
                    <span class="access_param_wrapper">{$lang.View2}<span class='help_bt' h_id='protect_of_view'></span></span>
                    <span class="access_param_wrapper">{$lang.Edit3}<span class='help_bt' h_id='protect_of_edit'></span></span>
                    {if $config.access_protect_mode == 2}
                    <span class="access_param_wrapper">{$lang.Access}<span class='help_bt' h_id='protect_of_access'></span></span>
                    {/if}
                </td>
            </tr>
            <tr>
                <td align="right"></td>
                <td>
                    <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 15px; text-align: center;">
                        <input type="checkbox" id="pr_view_all" {if !$protected}disabled{/if}
                               onclick="$('[id^=pr_view]').prop('checked', this.checked); if (!this.checked) $('[id^=pr_edit]').prop('checked', 0);">
                    </div>
                    <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 0; text-align: center;">
                        <input type="checkbox" id="pr_edit_all" {if !$protected}disabled{/if}
                               onclick="$('[id^=pr_edit]').prop('checked', this.checked); if ( this.checked) $('[id^=pr_view]').prop('checked', 1);">
                    </div>
                    {if $config.access_protect_mode == 2}
                    <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 0; text-align: center;">
                        <input type="checkbox" id="pr_acc_all" {if !$protected}disabled{/if}
                               onclick="$('[id^=pr_acc]').prop('checked', this.checked);">
                    </div>
                    {/if}
                </td>
            </tr>
            {foreach from=$protect key=gid item=acc}
                <tr>
                    <td align="right" style="padding-top: 11px;">{$acc.name}:</td>
                    <td style="display: flex; flex-wrap: nowrap;">
                        <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 15px; text-align: center;">
                            <input type="checkbox" name="protect_rights[{$gid}][view]" id="pr_view{$gid}" value="1"
                                   {if $acc.view}checked{/if} {if !$protected}disabled{/if}
                                   onclick="if (!this.checked) $('#pr_edit{$gid}').prop('checked', 0)">
                        </div>
                        <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 0; text-align: center;">
                            <input type="checkbox" name="protect_rights[{$gid}][edit]" id="pr_edit{$gid}" value="1"
                                   {if $acc.edit}checked{/if} {if !$protected}disabled{/if}
                                   onclick="if ( this.checked) $('#pr_view{$gid}').prop('checked', 1)">
                        </div>
                        {if $config.access_protect_mode == 2}
                        <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 0; text-align: center;">
                            <input type="checkbox" name="protect_rights[{$gid}][acc]" id="pr_acc{$gid}" value="1"
                                   {if $acc.acc}checked{/if} {if !$protected}disabled{/if}>
                        </div>
                        <div style="float: left; margin:0 34px; width: 60px; padding: 8px 0 6px 0; text-align: center;">
                            <a href="edit_protect.php?group={$gid}&cat={$cat_id}&table={$table_id}&menu=tips" target="_blanc">{$lang.Go}</a>
                        </div>
                        {/if}
                    </td>
                </tr>
            {/foreach}
            <tr><td></td></tr>
            <tr>
                <td align=right>{$lang.Comment}<span class='help_bt' h_id='protect_comment'></span>:</td>
                <td><textarea class="form-control form-control-250" name="protect_comment" rows=5>{$protect_comment}</textarea></td>
            </tr>
        </tbody>
        {/if}

        <tr>
          <td colspan="4" align="center">
            <br>
            <input
              class="btn btn-default btn-sm"
              type="submit"
              name="save"
              value="{$lang.Save}"
              onClick="
                link_fields_in_condition();
                if (!onAlertFieldsTip()) {
                  return false;
                }

                if (
                  !document.getElementById('name').value.replace(/ /g,'') ||
                  !document.getElementById('condition').value.replace(/ /g,'') ||
                  !document.getElementById('message').value.replace(/ /g,'') ||
                  !check_brackets() ||
                  !document.getElementById('push_title').value.replace(/ /g,'') && push_on.checked
                ) {
                  return false
                }
              "
              {if $no_save_mode == 2}disabled title="{$lang.Element_no_edit_msg}"{/if}
            />
            <br/><br/>
            <a href="edit_tip.php?table={$table_id}{$back_url_prm}">{$lang.Return}</a>
          </td>
        </tr>
    </table>
</form>
{/if}
<script src="include/js/configuration.js?{$revision}"></script>