(function () {

    /**
     * Конструктор условий
     * @author Marsel Gaifiev <marsel@clientbase.ru>
     * @constructor
     */

    function ConditionsConstruct(table, params) {
        this.table = table;
        if (params) {
            this.params = params;
        } else {
            this.params = {};
        }
        this.field = {};
        this.fields_types = {};
        this.fields_multy = {};
        this.start = false;
        this.count = 0;
        this.debug = function (param) {
            console.log(param);
        };
        /** Словарь типов */
        this.types = {
            TEXT: 3,
            FILE: 6,
            IMAGE: 9,
            NUMBER: 1,
            DATE: 2,
            DATETIME: 12,
            LINK: 5
        };
        this.get_type = function (container) {
            var result = null;
            var $container = $(container);
            if ($container.length > 0) {
                var cons_field = $container.find($('.cons_field'));
                if (cons_field.length > 0) {
                    var val = cons_field.val();
                    var option = cons_field.find($('option[value=' + val + ']'));
                    result = parseInt(option.data('type'));
                }
            }

            return result;
        };

        this.get_cond = function (select) {
            var val;
            if (select !== undefined) {
                val = select.val();
            } else {
                val = 0;
            }
            if (val !== 0) {
                var field_type = this.fields_types[val];
                var mult_value = this.fields_multy[val];
                var conds_opts = {};
                if (field_type === 10 || field_type === 1) {
                    conds_opts = {
                        '=': lang['='],
                        '!=': lang['!='],
                        '>': lang['>'],
                        '<': lang['<'],
                        '>=': lang['>='],
                        '<=': lang['<='],
                    };
                } else if (field_type === 3 || field_type === 6 || field_type === 9 || mult_value === 1) {
                    conds_opts = {
                        '=': lang['='],
                        '!=': lang['!='],
                        'LIKE': lang['LIKE'],
                        'NOT LIKE': lang['NOT LIKE'],
                    };
                } else if (field_type === 12 || field_type === 2) {
                    conds_opts = {
                        '=': lang['='],
                        '!=': lang['!='],
                        'period': lang['period'],
                        'current': lang['current_date'],
                        'current_time': lang['current_time'],
                    };
                } else {
                    conds_opts = {
                        '=': lang['='],
                        '!=': lang['!='],
                    };
                }
            }

            return conds_opts;
        };

        this.build_cond_construct = function (container_wrap, num) {
            var $container_wrap = $(container_wrap);
            if ($container_wrap.length > 0) {
                if (this.params['cond_params'] && this.start === false) {
                    this.start = true;
                    $.each(this.params['cond_params'], function (num, cond_param) {
                        this.build_cond_construct($container_wrap, num);
                        this.count++;
                    }.bind(this));
                    return;
                }
                var remove_cond_btn = $('<button type="button" class="cond-remove-btn btn-drop">')
                    .attr('data-num', this.count)
                    .click(function () {
                        var data_num = remove_cond_btn.attr('data-num');
                        var cond_container = $('.cond-container[data-num="' + data_num + '"]');
                        _deinit_events_after_changes(cond_container);
                        if ($container_wrap.find($('.cond-container')).length === 1) {
                            var cons_field = cond_container.find($('.cons_field'));
                            var cons_cond = cond_container.find($('.cons_cond'));
                            var cons_union = cond_container.find($('.cons_union'));
                            var cons_params = cond_container.find($('.cons_params'));

                            if (cons_field.length > 0 && cons_union.length > 0 && cons_cond.length > 0
                                && cons_params.length > 0) {
                                cons_field.val('0');
                                this.set_events_to_union(cons_union, $container_wrap);
                                cons_cond.html('');

                                /** Формируем дефолтный инпут и вставляем его */
                                var element = $('<input>')
                                    .attr('class', 'form-control form-control-100')
                                    .attr('data-num', this.count)
                                    .attr('name', 'cond[' + this.count + '][params]');
                                cons_params.html('');
                                cons_params.append(element);
                            }
                        } else {
                            /** Проверяем, последний ли элемент мы удаляем */
                            if (cond_container[0] === $container_wrap.find($('.cond-container')).eq($container_wrap.find($('.cond-container')).length - 1)[0]) {
                                this.set_events_to_union(cond_container.prev().find($('.cons_union')), $container_wrap);
                            }
                            cond_container.remove();
                        }
                        if ($('#calc_form').length > 0) set_tpl_events();
                    }.bind(this));
                /** Формируем открытую скобку */
                var open_brackets = $('<span></span>')
                    .attr('id', 'span_ob_' + this.count)
                    .attr('class', 'brackets')
                    .attr('data-type', 'ob_' + this.count)
                    .css({
                        'cursor': 'pointer',
                        'color': '#ddd'
                    });
                open_brackets.append('<b>(</b>');
                open_brackets.click( (event) => { set_bracket(event) });
                var open_bracket_input = $('<input/>')
                    .attr('type', 'hidden')
                    .attr('name', 'cond[' + this.count + '][open_bracket]')
                    .attr('id', 'cond_ob_' + this.count)
                    .attr('value', '0');

                /** Формируем список полей */
                var fields_select = $('<select></select>')
                    .attr('class', 'form-control form-control-160 cons_field')
                    .attr('data-num', this.count)
                    .attr('name', 'cond[' + this.count + '][field]');
                var fields = this.getFieldsInfo();
                fields_select
                    .append($('<option></option>')
                        .attr('value', 0)
                        .text(''));
                fields_select
                    .append($('<option></option>')
                        .attr('value', -1)
                        .text('{' + lang.New_record + '}'));
                $.each(fields, function (field_id, field_info) {
                    this.fields_types[field_id] = Number(field_info.type_field);
                    this.fields_multy[field_id] = Number(field_info.mult_value);
                    fields_select
                        .append($('<option></option>')
                            .attr('value', field_id)
                            .attr('data-type', field_info.type_field)
                            .text(field_info.name_field));
                }.bind(this));
                fields_select.change(function () {
                    let data_num = fields_select.data('num');
                    let cond_container = $('.cond-container[data-num="' + data_num + '"]');
                    let fieldMultVal = 0;
                    const fieldId = parseInt(fields_select.val());
                    const allFields = this.getFieldsInfo();

                    if (fieldId !== -1) {
                        fieldMultVal = parseInt(allFields[fieldId]['mult_value']);
                    }
                    if (cond_container.length > 0) {
                        _deinit_events_after_changes(cond_container);
                        conds.html('');
                        $.each(this.get_cond(fields_select), function (cond_val, cond) {
                            const condOption = $('<option></option>')
                                                .attr('value', cond_val)
                                                .text(cond);
                            if (fieldMultVal === 1 && cond_val === 'LIKE') condOption.attr('selected', true);
                            conds.append(condOption);
                            
                        });
                        container_input.html('');
                        var opt = fields_select.find($('option[value=' + fields_select.val() + ']'));
                        container_input.html(this.get_cond_input(fields_select.val(), opt.data('type'), data_num));
                        _init_fields_after_change(cond_container, this.table, this.count);
                    }
                    if ($('#calc_form').length > 0) set_tpl_events();
                }.bind(this));
                /** Формируем список условий */
                var conds = $('<select></select>')
                    .attr('class', 'form-control form-control-100 cons_cond')
                    .attr('data-num', this.count)
                    .attr('name', 'cond[' + this.count + '][cond]');
                $.each(this.get_cond(), function (cond_val, cond) {
                    conds
                        .append($('<option></option>')
                            .attr('value', cond_val)
                            .text(cond))
                });

                conds.change(function () {
                    var cond_container = conds.parent();
                    if (cond_container.length > 0) {
                        var type = this.get_type(cond_container);
                        var data_num = cond_container.data('num');
                        var cons_params = cond_container.find($('.cons_params'));
                        const fieldId = parseInt(fields_select.val());
                        const allFields = this.getFieldsInfo();
                        const condTermVal = conds.val();
                        const isTermFocused = conds.is(':focus');
    
                        if (fieldId !== -1) {
                            const fieldType = parseInt(allFields[fieldId]['type_field']);
                            const fieldMultVal = parseInt(allFields[fieldId]['mult_value']);
                            
                            if (condTermVal === '=' && isTermFocused) checkFieldForMultiValAndShowTooltip(fieldType, fieldMultVal, 1);
                            if (condTermVal === '!=' && isTermFocused) checkFieldForMultiValAndShowTooltip(fieldType, fieldMultVal, 2);
                        }

                        if (type === this.types.DATE || type === this.types.DATETIME) {
                            if (condTermVal === 'current') {
                                cons_params.html('');
                            } else if (condTermVal === 'current_time') {
                                cons_params.html('');
                                var text1 = $('<span>').html(' + допуск ');
                                var interval = $('<input>')
                                    .attr('class', 'form-control form-control-20')
                                    .attr('name', 'cond[' + data_num + '][params]')
                                    .val('0');
                                var text2 = $('<span>').html(' ' + lang.minutes + ' ');
                                cons_params.append(text1).append(interval).append(text2);
                            } else if (condTermVal === 'period') {
                                cons_params.html('');
                                var date_from = $('<input>')
                                    .attr('class', 'datepicker form-control form-control-75')
                                    .attr('name', 'cond[' + data_num + '][params][date_1]');
                                var date_to = $('<input>')
                                    .attr('class', 'datepicker form-control form-control-75')
                                    .attr('name', 'cond[' + data_num + '][params][date_2]');
                                var dash = $('<span>')
                                    .text('-')
                                    .css('margin-right', '5px');
                                cons_params.append(date_from).append(dash).append(date_to);
                                _init_fields_after_change(cond_container, this.table, this.count);
                            } else if (cons_params.find($('.datepicker')).length != 1) {
                                cons_params.html('');
                                var date = $('<input>')
                                    .attr('class', 'datepicker form-control form-control-75')
                                    .attr('name', 'cond[' + data_num + '][params]');
                                cons_params.append(date);
                                _init_fields_after_change(cond_container, this.table, this.count);
                            }
                        }
                    }
                }.bind(this));
                /** Формируем поле для ввода данных */
                var container_input = $('<span class="cons_params"></span>')
                    .attr('data-num', this.count);
                var input = this.get_cond_input();
                container_input.append(input);

                /** Формируем закрытую скобку */
                var close_brackets = $('<span></span>')
                    .attr('id', 'span_cb_' + this.count)
                    .attr('class', 'brackets')
                    .attr('data-type', 'cb_' + this.count)
                    .css({
                        'cursor': 'pointer',
                        'color': '#ddd'
                    });
                close_brackets.append('<b>)</b>');
                close_brackets.click( (event) => { set_bracket(event) });
                var close_bracket_input = $('<input/>')
                    .attr('type', 'hidden')
                    .attr('name', 'cond[' + this.count + '][close_bracket]')
                    .attr('id', 'cond_cb_' + this.count)
                    .attr('value', '0');

                /** Формируем список объединений */
                var union_terms = {
                    '': '',
                    'and': lang['and'],
                    'or': lang['or'],
                };
                var union = $('<select></select>')
                    .attr('class', 'form-control form-control-75 cons_union')
                    .attr('data-num', this.count)
                    .attr('name', 'cond[' + this.count + '][union]')
                    .change(function () {
                        if (union.val() !== '') {
                            this.count++;
                            this.params = {};
                            this.build_cond_construct($container_wrap);
                            union.find($('option[value=""]')).remove();
                            union.off();
                        }
                        init_chosen();
                    }.bind(this));
                $.each(union_terms, function (union_id, union_name) {
                    union
                        .append($('<option></option>')
                            .attr('value', union_id)
                            .text(union_name));
                });

                /** Формируем контейнер для всего конструктора */
                var container = $('<div class="cond-container"></div>')
                    .attr('data-num', this.count);
                container.append(open_brackets).append(open_bracket_input).append(fields_select).append(conds).append(container_input).append(close_brackets).append(close_bracket_input).append(union).append(remove_cond_btn);
                $container_wrap.append(container);

                /** Загружаем конструктор параметрами */
                var data_num = fields_select.data('num');
                if (this.params['cond_params'] && this.params['cond_params'][num]['field']) {
                    fields_select.val(this.params['cond_params'][num]['field']);
                    var opt = fields_select.find($('option[value=' + fields_select.val() + ']'));
                    if (this.params['cond_params'][num]['params']['text']
                        && this.params['cond_params'][num]['params']['val']) {
                        container_input.html(this.get_cond_input(fields_select.val(),
                            opt.data('type'),
                            data_num,
                            this.params['cond_params'][num]['params']['val'],
                            this.params['cond_params'][num]['params']['text']));
                    } else {
                        container_input.html(this.get_cond_input(fields_select.val(), opt.data('type'), data_num, this.params['cond_params'][num]['params']));
                    }
                }
                if (this.params['cond_params'] && this.params['cond_params'][num]['cond']) {
                    conds.html('');
                    $.each(this.get_cond(fields_select), function (cond_val, cond) {
                        conds
                            .append($('<option></option>')
                                .attr('value', cond_val)
                                .text(cond))
                    }.bind(this));
                    conds.val(this.params['cond_params'][num]['cond']);
                    if (this.params['cond_params'][num]['cond'] === 'current') {
                        var cond_container = conds.parent();
                        var cons_params = cond_container.find($('.cons_params'));
                        cons_params.html('');
                    } else if (this.params['cond_params'][num]['cond'] === 'current_time') {
                        var cond_container = conds.parent();
                        var cons_params = cond_container.find($('.cons_params'));
                        cons_params.html('');
                        var text1 = $('<span>').html(' + допуск ');
                        var interval = $('<input>')
                            .attr('class', 'form-control form-control-20')
                            .attr('name', 'cond[' + data_num + '][params]')
                            .val(this.params['cond_params'][num]['params']);
                        var text2 = $('<span>').html(' ' + lang.minutes + ' ');
                        cons_params.append(text1).append(interval).append(text2);
                    } else if (this.params['cond_params'][num]['cond'] === 'period') {
                        var cond_container = conds.parent();
                        var cons_params = cond_container.find($('.cons_params'));
                        cons_params.html('');
                        var date_from = $('<input>')
                            .attr('class', 'datepicker form-control form-control-75')
                            .attr('name', 'cond[' + data_num + '][params][date_1]')
                            .val(this.params['cond_params'][num]['params']['date_1']);
                        var date_to = $('<input>')
                            .attr('class', 'datepicker form-control form-control-75')
                            .attr('name', 'cond[' + data_num + '][params][date_2]')
                            .val(this.params['cond_params'][num]['params']['date_2']);
                        var dash = $('<span>')
                            .text('-')
                            .css('margin-right', '5px');
                        cons_params.append(date_from).append(dash).append(date_to);
                    }
                }
                if (this.params['cond_params'] && this.params['cond_params'][num]['union']) {
                    union.val(this.params['cond_params'][num]['union']);
                    if (union.val() !== '') {
                        union.find($('option[value=""]')).remove();
                        union.off();
                    }
                }
                
                // Данные для открывающих скобок
                if (this.params['cond_params'] && this.params['cond_params'][num]['open_bracket']) {
                    open_bracket_input.val(this.params['cond_params'][num]['open_bracket']);
                    init_bracket('ob_' + num);
                }
                // Данные для закрывающих скобок
                if (this.params['cond_params'] && this.params['cond_params'][num]['close_bracket']) {
                    close_bracket_input.val(this.params['cond_params'][num]['close_bracket']);
                    init_bracket('cb_' + num);
                }
                _init_fields_after_change($('.cond-container[data-num="' + this.count + '"]'), this.table, this.count);
            }
        };

        this.set_events_to_union = function (elem, container_wrap) {
            var $elem = $(elem);
            var $container_wrap = $(container_wrap);
            if ($elem.length > 0 && $container_wrap.length > 0 && $elem.find($('option[value=""]')).length === 0) {
                $elem
                    .prepend($('<option value="" selected>'))
                    .change(function (e) {
                        var union = $(e.target);
                        if (union.val() !== '') {
                            this.count++;
                            this.build_cond_construct($container_wrap);
                            union.find($('option[value=""]')).remove();
                            union.off();
                        }
                    }.bind(this));
            }
        };

        this.get_users_list = function () {
            var users_list;
            if (window.users_list === undefined) {
                var url = 'calc_construct.php';
                var params = {
                    'getUsersCons': 1,
                    'csrf': csrf
                };
                users_list = this.ajax_sender(url, params);
                window.users_list = users_list;
            } else {
                users_list = window.users_list;
            }
            return users_list;
        };
        this.get_group_list = function () {
            var group_list;
            if (window.group_list === undefined) {
                var url = 'calc_construct.php';
                var params = {
                    'getGroupCons': 1,
                    'csrf': csrf
                };
                group_list = this.ajax_sender(url, params);
                window.group_list = group_list;
            } else {
                group_list = window.group_list;
            }
            return group_list;
        };
        this.get_select_list = function (field_id, type) {
            var url = 'calc_construct.php';
            var params = {
                'getSelectCons': field_id,
                'type': type,
                'csrf': csrf
            };
            return this.ajax_sender(url, params);
        };
        this.get_cond_input = function (field_id, type, num, val, text) {
            var type_field;
            if (type !== undefined && type !== 0) {
                type_field = type;
            } else {
                type_field = 0;
            }
            if (field_id === undefined) {
                field_id = 0;
            } else {
                field_id = Number(field_id);
            }
            if (num === undefined) {
                num = this.count;
            }
            if (!text) {
                text = '';
            }
            var element;
            if (type_field !== 0) {
                if (type_field === 11 || type_field === 7 || type_field === 4 || type_field === 5 || type_field === 13 || type_field === 14) {
                    if (type_field === 11 || type_field === 7) {
                        var users_list = this.get_users_list();

                        element = $('<select></select>')
                            .attr('class', 'form-control form-control-75')
                            .attr('data-num', num)
                            .attr('name', 'cond[' + num + '][params]')
                            .attr('id', 'cond_value_' + num);
                        element
                            .append($('<option></option>')
                                .attr('value', 0));
                        $.each(users_list, function (user_id, user_name) {
                            element
                                .append($('<option></option>')
                                    .attr('value', user_id)
                                    .text(user_name));
                        });
                    } else if (type_field === 14) {
                        var group_list = this.get_group_list();
                        element = $('<select></select>')
                            .attr('class', 'form-control form-control-75')
                            .attr('data-num', num)
                            .attr('name', 'cond[' + num + '][params]')
                            .attr('id', 'cond_value_' + num);
                        element
                            .append($('<option></option>')
                                .attr('value', 0));
                        $.each(group_list, function (group_id, group_name) {
                            element
                                .append($('<option></option>')
                                    .attr('value', group_id)
                                    .text(group_name));
                        });
                    } else if (type_field === 13 || type_field === 4) {
                        var select_list = this.get_select_list(field_id, type_field);
                        element = $('<select></select>')
                            .attr('class', 'form-control form-control-75')
                            .attr('data-num', num)
                            .attr('name', 'cond[' + num + '][params]')
                            .attr('id', 'cond_value_' + num);
                        if (type_field === 4) {
                            element
                                .append($('<option></option>')
                                    .attr('value', ''));
                        }
                        $.each(select_list, function (select_val, select_text) {
                            element
                                .append($('<option></option>')
                                    .attr('value', select_val)
                                    .text(select_text));
                        });
                    } else if (type_field === 5) {
                        element = $('<select class="combobox">')
                            .attr({
                                'data-num': num,
                                'name': 'cond[' + num + '][params][val]',
                                'field_id': field_id,
                                'id': 'cond_value_' + num
                            });
                    }
                } else if (type_field === 12 || type_field === 2) {
                    element = $('<input>')
                        .attr('class', 'datepicker form-control form-control-75')
                        .attr('data-num', num)
                        .attr('name', 'cond[' + num + '][params]')
                        .attr('id', 'cond_value_' + num);
                } else {
                    element = $('<input>')
                        .attr('class', 'form-control form-control-100')
                        .attr('data-num', num)
                        .attr('name', 'cond[' + num + '][params]')
                        .attr('id', 'cond_value_' + num);
                }
            } else {
                if (field_id === -1) {
                    const yeapOpt = $('<option></option>').attr('value', 1).text(lang.Yes);
                    const noOpt = $('<option></option>').attr('value', 0).text(lang.No);

                    element = $('<select></select>')
                            .attr('class', 'form-control form-control-75')
                            .attr('data-num', num)
                            .attr('name', 'cond[' + num + '][params]')
                            .attr('id', 'cond_value_' + num);
                    element.append(yeapOpt).append(noOpt);
                } else {
                    element = $('<input>')
                        .attr('class', 'form-control form-control-100')
                        .attr('data-num', num)
                        .attr('name', 'cond[' + num + '][params]')
                        .attr('id', 'cond_value_' + num);
                }
            }
            if (val) {
                if (type_field !== 5) {
                    element.val(val);
                } else {
                    element.attr({
                        'ac_val': val.text || val,
                        'ac_text': text || val.text
                    });
                }
            }
            return element;
        };

        this.get_fields = function () {
            if ($.isEmptyObject(this.field)) {
                const url = 'calc_construct.php';
                const params = {
                    'getFieldCons': this.table,
                    'csrf': csrf
                };
                this.field = this.ajax_sender(url, params);
            }
            return this.field;
        };

        this.getFieldsInfo = function () {
            const url = 'calc_construct.php';
            const params = {
                'getFieldsInfo': this.table,
                'csrf': csrf
            };
            return this.ajax_sender(url, params);as
        };

        this.ajax_sender = function (url, params) {
            return JSON.parse($.ajax({
                type: 'POST',
                url: url,
                async: false,
                data: params,
            }).responseText);
        };

    }

    /**
     * Инициализация полей выборки после изменения состояния
     * @param container {Element}
     * @param table_id {Number}
     * @private
     */
    function _init_fields_after_change(container, table_id, count) {
        var $container = $(container);

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

            /** Инициализация полей типа связь */
            var combobox = $container.find($('.combobox'));
            if (combobox.length > 0) {
                var field_id = combobox.attr('field_id');
                var url = 'select_value.php?table=' + table_id + '&csrf=' + csrf + '&field=' + field_id;
                autocomplete_ajax_request(combobox, url, false, false, 0, '', {}, false);
                create_combobox(combobox);
                var data_num = combobox.data('num');
                var autocomplete = combobox.next().find('.autocomplete__input');
                autocomplete.attr('name', 'cond[' + data_num + '][params][text]');
                var ac_text = combobox.attr('ac_text');
                var ac_val = combobox.attr('ac_val');
                if (ac_text) {
                    autocomplete.val(ac_text);
                }
                if (ac_val) {
                    combobox.val(ac_val);
                }
                var timeout = 0;
                if (autocomplete.length > 0) {
                    autocomplete.on('keyup', function (e) { // Навешиваем keyup на автокомплит, чтобы формировалась ссылка на данные с введенными символами
                        var word = '&q=';
                        if (autocomplete.val() !== '') {
                            word += encodeURIComponent(autocomplete.val());
                        }
                        url = 'select_value.php?table=' + table_id + '&csrf=' + csrf + '&field=' + field_id + word;
                        if (e.keyCode === 17 || e.keyCode === 18 || e.keyCode === 16 || e.keyCode === 27 || e.keyCode === 40 || e.keyCode === 37 ||
                            e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 9 || e.keyCode === 20 || e.keyCode === 13) {
                            return;
                        }
                        clearTimeout(timeout);
                        timeout = setTimeout(function () {
                            autocomplete_ajax_request(combobox, url, false, true);
                        }, 100);
                    });
                }
            }

        }
        set_expert(count);
    }

    /**
     * Метод, удаляющий обработчики с поля типа связь
     * @param container {Element}
     * @private
     */
    function _deinit_events_after_changes(container) {
        var $container = $(container);

        if ($container.length > 0) {
            /** Удаление обработчиков с поля типа связи */
            var autocompletes = $container.find($('autocomplete__input'));
            if (autocompletes.length > 0) {
                autocompletes.each(function (i, autocomplete) {
                    $(autocomplete).off();
                });
            }
        }
    }

    function set_bracket(event) {
        let id = $(event.target).parent().attr('data-type');
        let 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 init_bracket(id) {
        let bracket = $('#cond_' + id).val() == '1';
        $('#span_' + id).css('color', bracket ? 'black' : '#ddd');
        $('#span_' + id).prop('title', bracket ? lang.Disable_bracket: lang.Enable_bracket);
    }

    function set_expert(count) {
        var condition = "";
        var and_count = 0;
        var or_count = 0;
        for (var num = 0; num <= count; num++) {
            if ($(`.cond-container[data-num=${num}]`) && $(`.cons_field[data-num=${num}]`).val() == '-1') {
                condition += "new_record" + $(`.cons_union[data-num=${num}]`).val();
            }
            if ( $(`.cond-container[data-num=${num}]`) && ( $(`.cons_field[data-num=${num}]`).val() > '0' || $(`.cons_field[data-num=${num}]`).val() == '-2' ) ) {
                var cond_union = $(`.cons_union[data-num=${num}]`).val();

                and_count += (cond_union == 'and') ? 1 : 0;
                or_count  += (cond_union == 'or' ) ? 1 : 0;
            }
        }

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

    window.ConditionsConstruct = ConditionsConstruct;

})();
