$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function (name) {
        return $.getUrlVars()[name];
    }
});

function getUrlVars2(location2) {
    var vars = [], hash;
    var hashes = location2.slice(location2.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');

        if ($.inArray(hash[0], vars) > -1) {
            vars[hash[0]] += "," + hash[1];
        }
        else {
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
    }

    return vars;
}

function delfile(field_id, file_name) {
    myApp.confirm('Удалить файл ' + file_name + '?',
        function () {
            $$('#del_file' + field_id).val(file_name);
            $$('#edit_mode').val(0);
            $$('.m-cb-toolbar-view-line-edit-mode-on button').click();
        },
        function () {
        }
    );
}

var myMessages;

function type_4_mult_val_check_all(el) {
  if (el.checked == true) {
    for (let i = 0; i < $(el).parent().parent().find('.type_4_mult_val').length; i++) {
      $(el).parent().parent().find('.type_4_mult_val')[i].firstElementChild.checked = true;
    }
  } else {
    for (let i = 0; i < $(el).parent().parent().find('.type_4_mult_val').length; i++) {
      $(el).parent().parent().find('.type_4_mult_val')[i].firstElementChild.checked = false;
    }
  }
}

// Initialize your app
var myApp = new Framework7({
    pushState: true,

    cache: false,

    modalTitle: 'Клиентская база',
    modalButtonOk: 'ОК',
    modalButtonCancel: 'Отмена',
    modalPreloaderTitle: 'Загрузка...',

    onAjaxStart: function (xhr) {
        myApp.showIndicator();
    },
    onAjaxComplete: function (xhr) {
        myApp.hideIndicator();
        hideEmptyGroups();
    },

    swipeBackPageBoxShadow: false,
    swipeoutNoFollow: true,
    swipeBackPage: false
});

// Export selectors engine
var $$ = Framework7.$;

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we use fixed-through navbar we can enable dynamic navbar
    dynamicNavbar: true
});

$$(document).on('pageBeforeAnimation', function (e) {
    mainView.hideToolbar();
});
$$(document).on('pageAfterAnimation', function (e) {
    mainView.showToolbar();
    myMessages = myApp.messages('.messages', {
        autoLayout: true,
        scrollMessages: true,
    });
});

$$(document).on("click", ".m-cb-control-multi-link", function () {
    create_multi_link(this);
});

// Event listener to run specific code for specific pages
$$(document).on('pageInit', function (e) {
    var page = e.detail.page;

    // If it is Message page
    if (page.name === 'messages') {
        var $dd = $(e.detail.page.container).find('.toolbar');
        refresh_idx();
    }
    // If it is View-line page
    if (page.name === 'view-line') {
        initColors();
        // run createContentPage func after link was clicked
        //$$(e.detail.page.container).find('.m-cb-control-multi-link').on('click', function () {
        //create_multi_link(this);
        //});
        /*$$('.m-cb-control-multi-link').on('click', function () {
         create_multi_link(this);
         });*/
    }
    // If it is Calendar page
    if (page.name === 'calendars') {
        // run createContentPage func after link was clicked
        $(e.detail.page.container).find(".calendar_div").swipe({
            swipeLeft: function (event, direction, distance, duration, fingerCount) {
                mainView.loadPage($(e.detail.page.container).find(".m-cb-cal-next").attr("href"));
            },
            swipeRight: function (event, direction, distance, duration, fingerCount) {
                mainView.loadPage($(e.detail.page.container).find(".m-cb-cal-prev").attr("href"));
            },
            //Default is 75px, set to 0 for demo so any distance triggers swipe
            threshold: 75
        });
        $(e.detail.page.container).find(".day_view").swipe({
            swipeLeft: function (event, direction, distance, duration, fingerCount) {
                mainView.loadPage($(e.detail.page.container).find(".m-cb-cal-next-day").attr("href"));
            },
            swipeRight: function (event, direction, distance, duration, fingerCount) {
                mainView.loadPage($(e.detail.page.container).find(".m-cb-cal-prev-day").attr("href"));
            },
            //Default is 75px, set to 0 for demo so any distance triggers swipe
            threshold: 75
        });
    }
    hideEmptyGroups();
    onchange_3711();
    onchangeView_3711();
});

$$(document).on('pageAfterAnimation', function (e) {
    var page = e.detail.page;

    var loc_hash = window.location.hash;
    loc_hash = loc_hash.replace('#!/', '');
    if (loc_hash.indexOf('?mess_user=') != -1) {
        $$('.page-content').scrollTop(10000); //скроллим вниз на сообщениях
    }
    if (loc_hash.indexOf('&main_table=') != -1) {
        $$('.back_custom').removeClass('back');
        $$('.back_custom').attr('href', 'view_line2.php?table=' + getUrlVars2(loc_hash)["main_table"] + '&line=' + getUrlVars2(loc_hash)["main_line"]);
    }
    else if (loc_hash.indexOf('report.php') != -1) {
        $$('.back_custom').removeClass('back');
        $$('.back_custom').attr('href', 'm_menu.php?cat=' + $(e.detail.page.container).find(".page_to_back").val());
    }
    else if (loc_hash.indexOf('view_line2.php') != -1) {
        $$('.back_custom').removeClass('back');
        $$('.back_custom').attr('href', 'fields.php?table=' + $(e.detail.page.container).find(".page_to_back").val() + '&page=' + $(e.detail.page.container).find(".page_to_real_page").val() + '&filter=' + $(e.detail.page.container).find(".page_to_real_filter").val() + $(e.detail.page.container).find(".page_to_real_status").val());
    }
    else if (loc_hash.indexOf('fields.php') != -1) {
        $$('.back_custom').removeClass('back');
        if ($(e.detail.page.container).find(".page_to_back_line").val()) var rel_line = '&line=' + $(e.detail.page.container).find(".page_to_back_line").val();
        else var rel_line = '';

        if ($(e.detail.page.container).find(".page_to_back_table").val() && rel_line) $$('.back_custom').attr('href', 'view_line2.php?table=' + $(e.detail.page.container).find(".page_to_back_table").val() + rel_line);
        else if ($(e.detail.page.container).find(".page_to_back_table").val()) $$('.back_custom').attr('href', 'fields.php?table=' + $(e.detail.page.container).find(".page_to_back_table").val());
        else $$('.back_custom').attr('href', 'm_menu.php?cat=' + $(e.detail.page.container).find(".page_to_back").val());
    }


    // View line
    if (loc_hash.indexOf('view_line2.php') != -1) {
        var loc_hash = window.location.hash;
        loc_hash = loc_hash.replace('#!/', '');
        var rel_table = getUrlVars2(loc_hash)["rel_table"];
        var m_table = getUrlVars2(loc_hash)["table"];

        if (getUrlVars2(loc_hash)["edit_mode"] == 1) {
            $$('.back_custom').removeClass('back');
            $$('.back_custom').attr('href', 'fields.php?table=' + $(e.detail.page.container).find(".page_to_back_tr").val());
        }

    }


    // Messages
    var loc_hash = window.location.hash;
    loc_hash = loc_hash.replace('#!/', '');

    if (loc_hash.indexOf('m_messages.php?list=2') != -1) {
        $.ajax({
            type: "GET",
            url: loc_hash
        })
            .then(function (response) {
                re = /<div class="page-content pull-to-refresh-content messages-content">([\s\S]*?)<\/div> <!-- Page Content -->/im;
                found = response.match(re);
                if (found == null) {
                    re = /<div class="page-content pull-to-refresh-content ">([\s\S]*?)<\/div> <!-- Page Content -->/im;
                    found = response.match(re);
                }
                if (found == null) {
                    re = /<div class="page-content pull-to-refresh-content">([\s\S]*?)<\/div> <!-- Page Content -->/im;
                    found = response.match(re);
                }
                if (found != null) {
                    msg = found[1];
                    $$('.pull-to-refresh-content').html(msg);
                }

                // When loading done, we need to reset it
                myApp.pullToRefreshDone();
            });
    }

    if (loc_hash.indexOf('m_messages.php?list=2') != -1) {
        var c_month = getUrlVars2(loc_hash)["month"];
        var c_day = getUrlVars2(loc_hash)["day"];
        var c_calendar_id = getUrlVars2(loc_hash)["calendar_id"];
        var back_url = getUrlVars2(loc_hash)["back_url"];
        if (!c_month && !c_day && !back_url) {
            $$('.back_custom').removeClass('back');
            $$('.back_custom').attr('href', 'm_menu.php');
        }
    }


    // Calendars
    if (loc_hash.indexOf('m_calendars.php?back_url') != -1) {
        $$('.back_custom').removeClass('back');
        $$('.back_custom').attr('href', 'm_menu.php');
    }


    // Scroll
    if (last_sub_table) {
        $('body').scrollTop($(last_sub_table.attr("data-target")).prev());
    }

    $.ajax({
        type: "GET",
        url: `m_calendars.php?calendar_id=${getUrlVars2(loc_hash)["calendar_id"]}&get_calendar_config=1`
      }).then(function(response) {
          let hour;
        for(let i=0;i<document.querySelectorAll('.day_view .no-gutter').length;i++){
            hour= +document.querySelectorAll('.day_view .no-gutter')[i].firstElementChild.textContent.split(':')[0];
            if(hour < (+JSON.parse(response).first_hour) || hour > (+JSON.parse(response).last_hour)){
                document.querySelectorAll('.day_view .no-gutter')[i].style.display = 'none';
            }
        }
      });

    // Первая загрузка страницы
    defaultPlaceholderForNumbers();
    $('.item-content .item-inner .item-input[field-type=3] a').each(function (i,el) {
        el.classList.add("external");
    });
    return false;

    var loc_hash = window.location.hash;
    loc_hash = loc_hash.replace('#!/', '');
    var myRe = /cat=([0-9]*)&?/ig;
    var myRe2 = /table=([0-9]*)&?/ig;
    var hash_lost_cat = myRe.exec(loc_hash);
    var hash_lost_table = myRe2.exec(loc_hash);

    var to_sub_tbl = getUrlVars2(loc_hash)["to_sub_tbl"];
    var tos = getUrlVars2(loc_hash)["table"];
    if (to_sub_tbl && $('.page-on-center').find(".id_sub_" + tos).offset()) {
        //$(document).ready(function (){
        //$("#click").click(function (){
        //$(this).animate(function(){
        $('.page-on-center').find('.page-content').animate({
            scrollTop: $('.page-on-center').find(".id_sub_" + tos).offset().top
        }, 200);
        //});
        // });
        //});
    }

    $$('.search-panel-link').attr('href', 'm_search.php');

    $$('.back_custom').addClass('back');

    if (hash_lost_cat)
        if (hash_lost_cat[1]) {
            $$('.search-panel-link').attr('href', 'm_search.php?cat=' + hash_lost_cat[1].toString());

            $$('.back_custom').removeClass('back');
            $$('.back_custom').attr('href', 'm_menu.php');
        }
    if (hash_lost_table)
        if (hash_lost_table[1]) {
            $$('.search-panel-link').attr('href', 'm_search.php?table=' + hash_lost_table[1].toString());
        }


    var back_url = getUrlVars2(loc_hash)["back_url"];//$.getUrlVar('back_url');
    back_url = Base64.decode(back_url);
    var st = back_url.indexOf('|');
    if (st != -1) back_url = back_url.substr(st + 1);
    if (back_url) {
        if (back_url.charAt(0) == '/mobile/') back_url = back_url.substr(8);
        //if (back_url)
        //{
        $$('.back_custom').removeClass('back');
        $$('.back_custom').attr('href', back_url);//return false;

        if (loc_hash.indexOf('view_line2.php') != -1 && back_url.indexOf('m_calendars.php') == -1) {
            var loc_hash = window.location.hash;
            loc_hash = loc_hash.replace('#!/', '');
            var rel_table = getUrlVars2(loc_hash)["rel_table"];
            var m_table = getUrlVars2(loc_hash)["table"];
            if (rel_table == m_table) {
                $$('.back_custom').removeClass('back');
                $$('.back_custom').attr('href', 'fields.php?table=' + $(e.detail.page.container).find(".page_to_back").val());
            }
        }
        //}
    }
    //else
    //{
    /*      var val_back_url = '';
     if ($(e.detail.page.container).find(".page_to_back_line").val()) val_back_url = $(e.detail.page.container).find(".back_url_64").val();
     val_back_url = Base64.decode(val_back_url);
     var st = val_back_url.indexOf('|');
     if (st!=-1) val_back_url = val_back_url.substr(st+1);


     var loc_hash = window.location.hash;
     loc_hash = loc_hash.replace('#!/', '');
     val_back_url = loc_hash;
     */
    if (val_back_url) {
        //$$('.tips-panel-link').attr('href', 'm_tips.php?back_url='+Base64.encode(val_back_url));
        //$$('.messages-panel-link').attr('href', 'm_messages.php?list=2&back_url='+Base64.encode(val_back_url));
        //$$('.calendars-panel-link').attr('href', 'm_calendars.php');//?back_url='+Base64.encode(val_back_url)
    }
    //}
});

// Pull to refresh content
// Add 'refresh' listener on it
$$(document).on('refresh', '.pull-to-refresh-content', function (e) {
    e.preventDefault();
    // Emulate 2s loading
    setTimeout(function () {
        var loc_hash = window.location.hash;
        loc_hash = loc_hash.replace('#!/', '');

        $.ajax({
            type: "GET",
            url: loc_hash
        })
            .then(function (response) {
                re = /<div class="page-content pull-to-refresh-content messages-content">([\s\S]*?)<\/div> <!-- Page Content -->/im;
                found = response.match(re);
                if (found == null) {
                    re = /<div class="page-content pull-to-refresh-content ">([\s\S]*?)<\/div> <!-- Page Content -->/im;
                    found = response.match(re);
                }
                if (found == null) {
                    re = /<div class="page-content pull-to-refresh-content">([\s\S]*?)<\/div> <!-- Page Content -->/im;
                    found = response.match(re);
                }
                if (found != null) {
                    msg = found[1];
                    $$('.pull-to-refresh-content').html(msg);
                }

                // When loading done, we need to reset it
                myApp.pullToRefreshDone();
            });
    }, 2000);
});

$$(document).on('click', '.m-cb-popup-filters', function (e) {
    e.preventDefault();
    var clickedLink = this;
    var remoteUrl = $(this).attr("data-url");
    $.ajax({
        type: "GET",
        url: remoteUrl
    })
        .then(function (response) {
            myApp.popup(response);
        });
});

$$(document).on('change', '#filter-value', function (e) {
    const tableId = $(e.target).attr('table_id');
    const filterVal = $(e.target).val();

    mainView.loadPage('fields.php?table=' + tableId + '&filter=' + filterVal);
});

$$(document).on('click', '.add-button-href', function (e) {
    e.preventDefault();
    e.stopPropagation();
    var _url = $(this).attr("href");

    $.ajax({
        type: "GET",
        url: $(this).attr("href")
    })
        .then(function (response) {
            var temp_res = trim(response);
            if (temp_res.substr(0, 8) == '<script>') {
                var new_href = trim(str_replace("<script>location.href='", '', temp_res));
                new_href = trim(str_replace("'</script>", '', new_href));
                mainView.loadPage(new_href);
            }
            else {
                mainView.loadPage(_url);
            }
        });
});

$$(document).on('click', '.m-cb-popup-filters-modal a', function () {
    myApp.closeModal('.m-cb-popup-filters-modal');
});

$$(document).on('click', '.m-cb-toolbar-edit-mode-on', function () {
    var $self = $(this);
    $('.item-link').toggle();
    $('.close-panel').toggle();
    $('.label-checkbox').toggle();
    if ($self.attr("data-active-mode") == "0") {
        $self.attr("data-active-mode", "1");
        $self.text("Готово");
    } else {
        $self.attr("data-active-mode", "0");
        $self.text("Выбрать");

    }
});

var $current_page;

$$(document).on('click', '.open-additional-tab', function (e) {
    e.preventDefault();
    $current_page = $(this).parents(".page");
    var _action_list = $current_page.find('.m-cb-action-dummy i');
    var _main_buttons = [];
    $.each(_action_list, function (i, action) {
        var _data = $(action).data();
        if (_data["isCustom"] == "0") {
            _main_buttons.push({
                text: _data["title"],
                onClick: function () {
                    $current_page.find(".m-cb-dyn-script").empty();
                    var script = document.createElement("script");
                    script.type = "text/javascript";
                    script.innerHTML = $current_page.find(".m-cb-fields-validation").html();
                    document.getElementsByClassName('m-cb-dyn-script')[0].appendChild(script);
                    if (_data["method"] == 'script') {
                        $.ajax({
                            type: "GET",
                            url: _data["url"]
                        })
                            .then(function (response) {
                                var temp_res = trim(response);
                                if (temp_res.substr(0, 8) == '<script>') {
                                    var new_href = trim(str_replace("<script>location.href='", '', temp_res));
                                    new_href = trim(str_replace("'</script>", '', new_href));
                                    mainView.loadPage(new_href);
                                }
                                else {
                                    mainView.loadPage(_data["url"]);
                                }
                            });
                    }
                    else if (_data["url"]) {
                        mainView.loadPage(_data["url"]);
                    } else {
                        eval(_data["onclick"]);
                    }
                }
            });
        }
    });
    var buttons4 = [
        {
            text: 'Отмена',
            red: true
        }
    ];

    var buttons2 = [];
    var buttons5 = [];
    //показываем только при редактировании записей в таблице
    if (window.location.href.includes('fields.php')) {
        // рисуем две кнопки на разные случаи
        var $self = $('.m-cb-toolbar-edit-mode-on');
        if ($self.attr("data-active-mode") == "0") {
            buttons2 = [
                {
                    text: 'Выбрать',
                    onClick: function () {
                        var $self = $('.m-cb-toolbar-edit-mode-on');
                        $('.item-link').toggle();
                        $('.close-panel').toggle();
                        $('.label-checkbox').toggle();
                        $self.attr("data-active-mode", "1");
                        $self.text("Готово");
                    }
                }
            ];
        } else {
            buttons2 = [
                {
                    text: 'Готово',
                    onClick: function () {
                        var $self = $('.m-cb-toolbar-edit-mode-on');
                        $('.item-link').toggle();
                        $('.close-panel').toggle();
                        $('.label-checkbox').toggle();
                        $self.attr("data-active-mode", "0");
                        $self.text("Выбрать");
                    }
                }
            ];
        }


    }
    if (window.location.href.includes('view_line2.php')) {
        var path = document.querySelector('#table_return_link a').href
        path = path.substr(path.indexOf('fields.php'));
        buttons5 = [
            {
                text: 'Вернуться в таблицу',
                onClick: function () {
                    mainView.loadPage(path);
                }
            }
        ];
    }

    var groups = [];
    if (_main_buttons && buttons2.length > 0) {
        groups.push(_main_buttons, buttons2, buttons4);
        myApp.actions(groups);
    } else {
        groups.push(_main_buttons, buttons4, buttons5);
        myApp.actions(groups);
    }
});

//желтый плюсик на странице с категориями
$$(document).on('click', '#circle', function (e) {
    var buttons1 = [];
    for (var i = 0; i < Object.keys(dataTitles).length; i++) {
        buttons1.push({
            text: Object.keys(dataTitles)[i],
            href: dataTitles[Object.keys(dataTitles)[i]],
            onClick: function () {
                $.ajax({
                    type: "GET",
                    url: this.href,
                    statusCode: {
                        200: function (response) {
                            var temp_res = trim(response);
                            if (temp_res.substr(0, 8) == '<script>') {
                                var new_href = trim(str_replace("<script>location.href='", '', temp_res));
                                new_href = trim(str_replace("'</script>", '', new_href));
                                mainView.loadPage(new_href);
                            }
                            else {
                                mainView.loadPage(this.url);
                            }
                        }
                    }
                })
            }
        });
    };
    var buttons2 = [
        {
            text: lang.Cancel,
            color: 'red'
        }
    ];
    var groups = [buttons1, buttons2];
    myApp.actions(groups);
});

$$(document).on('delete', '.swipeout', function (e) {
    e.preventDefault();
    closeTip($$(this).attr('user_id'), $$(this).attr('tip_id'), $$(this).attr('line_id'));
});

function closeTip(user_id, tip_id, line_id) {
    $.ajax({ // Формируем запрос
        type: "POST",
        url: "events.php",
        data: { sel: 'put', type: 'tips', key: 'close', value: tip_id, csrf: csrf }
    });
}

function open_add_actions($page) {
    $current_page = $page;
    var _action_list = $page.find('.m-cb-action-dummy i');
    var _add_buttons = [];
    var popupHTML = '<div class="popup">' +
        '<div class="list-block">' +
        '<ul>'
    $.each(_action_list, function (i, action) {
        var _data = $(action).data();
        if (_data["isCustom"] == "1") {
            popupHTML += '<li>' +
                '<a href="#" onClick="' + _data["onclick"] + ' return false;" title="' + _data["title"] + '" class="list-button item-link tets3">' + _data["name"] + '</a>' +
                '</li>'
        }
    });
    popupHTML += '<li><a href="#" class="close-popup list-button item-link">Назад</a></li>';
    popupHTML += '</ul></div></div>';

    myApp.popup(popupHTML);
}

function open_standart_actions($page) {
    $current_page = $page;
    var _action_list = $page.find('.m-cb-action-dummy i[data-type="standart"]');
    var popupHTML = '<div class="popup">' +
        '<div class="list-block">' +
        '<ul>'
    $.each(_action_list, function (i, action) {
        var _data = $(action).data();

        if (_data["isCustom"] == "1") {

          if (_data["method"] = 'script' && _data["url"]) {
            popupHTML += '<li>' +
                '<a href="#" onClick="action_method_script(' + _data["url"] + '); return false;" title="' + _data["title"] + '" class="list-button item-link">' + _data["title"] + '</a>' +
                '</li>'
          } else if (_data["url"]) {
            popupHTML += '<li>' +
                '<a href="#" onClick="mainView.loadPage(' + _data["url"] + '); return false;" title="' + _data["title"] + '" class="list-button item-link">' + _data["title"] + '</a>' +
                '</li>'
          } else if (_data["onclick"]) {
            popupHTML += '<li>' +
                '<a href="#" onClick="' + _data["onclick"] + ' return false;" title="' + _data["title"] + '" class="list-button item-link">' + _data["title"] + '</a>' +
                '</li>'
          }

        };
    });
    popupHTML += '<li><a href="#" class="close-popup list-button item-link">Назад</a></li>';
    popupHTML += '</ul></div></div>';

    myApp.popup(popupHTML);
}

function action_method_script(dataUrl) {
  $.ajax({
      type: "GET",
      url: dataUrl
  })
  .then(function (response) {
      var temp_res = trim(response);
      if (temp_res.substr(0, 8) == '<script>') {
          var new_href = trim(str_replace("<script>location.href='", '', temp_res));
          new_href = trim(str_replace("'</script>", '', new_href));
          mainView.loadPage(new_href);
      }
      else {
          mainView.loadPage(dataUrl);
      }
  });
}

function user_button(id, $page, buttonType, lineId) {
    if (buttonType == 1) {
        $page.find("#button_pressed").val(id);
        $page.find("form").submit();
    } else {
        window.open(`user_button.php?id=${id}&line_id=${lineId}`);
    }
}

$$(document).on('click', '.m-cb-toolbar-view-line-edit-mode-on', function (e) {
    e.preventDefault();

    var $self = $(this);
    var $current_page = $(this).parents(".page");
    checkDataOnChangingMode();
    if ($self.attr("data-active-mode") == "0") {
        $current_page.find('.edit_block_class').toggle();
        $current_page.find('.view_block_class').toggle();
        $current_page.find('#m__circle-dots').toggle();
        $current_page.find('#m__circle-edit').addClass('m__circle-green');
        $current_page.find('#m__circle-edit').removeClass('m__circle-yellow');
        $current_page.find('#m__circle-edit').addClass('m__circle-save');
        $current_page.find('#m__circle-edit').removeClass('m__circle-pencil');
        $self.attr("data-active-mode", "1");
    } else {

        if (valid_form($current_page) && checkRequiredFields()) {
            if(checkTextOnEditMode()){
                return false;
            };
            checkFormValuesOnEditMode();
            $current_page.find(".edit_mode_save").val('false');
            var loc_hash = window.location.hash;
            loc_hash = loc_hash.replace('#!/', '');
            var rel_table = getUrlVars2(loc_hash)["rel_table"];
            var rel_field = getUrlVars2(loc_hash)["rel_field"];
            var rel_line = getUrlVars2(loc_hash)["rel_line"];
            $current_page.find(".main_table").val(rel_table);
            $current_page.find(".main_line").val(rel_line);
            $current_page.find(".main_field").val(rel_field);
            $self.parents(".toolbar").prev().find('.ajax-submit-button').click();
            myApp.showIndicator();
            $current_page.find('#m__circle-dots').toggle();
            $current_page.find('#m__circle-edit').addClass('m__circle-yellow');
            $current_page.find('#m__circle-edit').removeClass('m__circle-green');
            $current_page.find('#m__circle-edit').addClass('m__circle-pencil');
            $current_page.find('#m__circle-edit').removeClass('m__circle-save');

            displayAdditionalSettingsBtn();
            $self.attr("data-active-mode", "0");
        } else {
            myApp.alert(lang['not_all_fields_or_number_characters_not_match']);
        }
    }
});


/**
 * Проверяет, заполнены ли все обязательные поля.
 * @returns {boolean} Возвращает true, если все обязательные поля заполнены, иначе false.
 */
function checkRequiredFields() {
  var itemInners = document.querySelectorAll('.item-inner');

  // Перебираем все элементы 'item-inner'
  for (var i = 0; i < itemInners.length; i++) {
      var itemInner = itemInners[i];
      // Проверяем, есть ли внутри элемента 'item-inner' элемент 'span' с текстом '*'
      var requiredSpan = itemInner.querySelector('.item-title.label span');
      if (requiredSpan && requiredSpan.textContent.includes('*')) {
          // Находим текстовое поле внутри элемента 'item-input'
          var textField = itemInner.querySelector('.item-input input[type="text"]');
          // Проверяем, пустое ли значение текстового поля
          if (textField && textField.value.trim() === '') {
              return false; // Значение поля пустое, возвращаем false
          }
      }
  }
  return true; // Все обязательные поля заполнены, возвращаем true
}

// Добавляем желтый кружочек "•••", если его нет
function displayAdditionalSettingsBtn() {
  const dotsBtn = $('#circle-dots-btn');

  if (dotsBtn.find('#m__circle-dots').length < 1) {
      const link = $('<a href="#" style="float:left;" class="link open-additional-tab"></a>');
      const addBtn = $('<button id="m__circle-dots" class="m__circle-yellow  m__circle-dots"><div><span>•••</span></div></button>');

      link.append(addBtn);
      dotsBtn.append(link);
  }
}

/**
 * Проверка заполнены ли все необходимые поля и соответствует ли количество символов в инпутах необходимым
 * @param {jQuery} $current_page Объект jQuery, представляющий текущую страницу, на которой выполняется валидация.
 * @returns {boolean}
 */
function valid_form($current_page) {
    let isValid = true;

    $current_page.find(".supamida").each(function (index, element) {
        var $this = $(this);
        $this.removeClass('incorrect-title');
        var idAttr = $this.attr('id');
        var supamidaElementsVal = $(this).next().find(".valval").val();

        if (typeof idAttr !== 'undefined' && idAttr.startsWith('value')) {
            var id = idAttr.replace('value', '');
            let templWord = this.parentElement.querySelector('#templ_word' + id);

            // Соответствует ли количество символов в инпутах необходимым
            if (templWord) {
              var text = templWord.textContent;
              var match = text.match(/\((\d+)\)/);
              if (match && match[1]) {
                  var numberInBrackets = parseInt(match[1], 10);
                  var inputValue = $this.val();
                  if (inputValue.length !== numberInBrackets) {
                      $this.addClass('incorrect-title');
                      isValid = false;
                      return false
                  }
              }
            }
            // Заполнены ли все необходимые поля
            if (check_click(id)) {
                $this.addClass('incorrect-title');
                isValid = false;
                return false
            }
        }
        if (!supamidaElementsVal) {
          $this.addClass('incorrect-title');
          isValid = false;
          return false
        }

        var $checkboxes = $(this).next().find(".valval[type='checkbox']");
        if ($checkboxes.length > 0 && !$checkboxes.is(':checked')) {
            $this.addClass('incorrect-title');
            isValid = false;
            return false;
        }

    });
    return isValid;
}

var d = $.Deferred();

function ajaxOnSubmitAction(response, new_href) {
    re = /<div class="page-content pull-to-refresh-content messages-content">([\s\S]*?)<\/div> <!-- Page Content -->/im;
    found = response.match(re);
    if (found == null) {
        re = /<div class="page-content pull-to-refresh-content ">([\s\S]*?)<\/div> <!-- Page Content -->/im;
        found = response.match(re);
    }
    if (found == null) {
        re = /<div class="page-content pull-to-refresh-content">([\s\S]*?)<\/div> <!-- Page Content -->/im;
        found = response.match(re);
    }
    if (found == null) {
        re = /<div class="page-content" style="background: #fff;">([\s\S]*?)<\/div> <!-- Page Content -->/im;
        found = response.match(re);
    }
    if (found != null) {
        myApp.closeModal();
        msg = found[1];

        var loc_hash = window.location.hash;
        loc_hash = loc_hash.replace('#!/', '');

        if (loc_hash.indexOf('=new&') != -1 || loc_hash.indexOf('&edit_mode=1&') != -1 || window.location.href.indexOf('&line=array') != -1) {
            mainView.loadPage(new_href);

        }
        else {
            $$('.pull-to-refresh-content').html(msg);
        }
    }
    else {
        myApp.closeModal();
        var popupHTML = '<div class="popup">' +
            '<div class="content-block no_print">' +
            '<p><a href="#" class="close-popup">Закрыть</a> | <a href="#" onclick="window.print()">Печать</a></p>' +
            '</div>' +
            '<div class="content-block">' +
            response +
            '</div>' +
            '</div>';
        myApp.popup(popupHTML);
    }
    // When loading done, we need to reset it
    myApp.pullToRefreshDone();
    myApp.hideIndicator();
    hideEmptyGroups();

    d.resolve();

    // После сохранения и выхода из редактирования
    defaultPlaceholderForNumbers();
    checkFormValuesOnEditMode();
    setTextColorForEditFields('black');
    $('.item-content .item-inner .item-input[field-type=3] a').each(function (i,el) {
        el.classList.add("external");
    });
}

$$(document).on('submitted', '.ajax-submit', function (e) {
    var xhr = e.detail.xhr; // actual XHR object

    var data = e.detail.data; // Ajax repsonse from action file
    // do something with response data

    var new_data = trim(data);

    var sp = new_data.substr(0, 9);
    var new_href = '';

    if (sp == '<!DOCTYPE') { //значит нам сразу пришел ответ с хтмл кодом
        new_href = xhr.responseURL.replace(/http:\/\/.+\//, '');
        ajaxOnSubmitAction(new_data, new_href);

        if (new_href.includes('line=new')) {
        // Регулярное выражение для поиска всех URL с параметром line
            const urlRegex = /\/view_line2\.php\?[^"]*line=\d+[^"]*/g;
            const urls = xhr.response.match(urlRegex);

            let maxLine = -1;

            // Перебор всех найденных URL
            urls && urls.forEach(url => {
                // Извлечение значения параметра line
                const lineMatch = url.match(/line=(\d+)/);
                if (lineMatch) {
                    const lineValue = parseInt(lineMatch[1], 10);

                    // Обновление максимального значения и сохранение URL, если найдено большее значение line
                    if (lineValue > maxLine) {
                        maxLine = lineValue;
                        new_href = url;
                    }
                }
            });
        }
    } else if (sp == '<script>alert(' || sp == "<script data='") {
        if (new_data.indexOf(" data='file'") != -1) {
            var new_data_alert = trim(str_replace("<script data='file'>alert('", '', new_data));
            sp = new_data_alert.indexOf("')</script>");
            new_data_alert = new_data_alert.substr(0, sp);
        }
        else {
            var new_data_alert = trim(str_replace("<script>alert('", '', new_data));
            sp = new_data_alert.indexOf("')</script>");
            new_data_alert = new_data_alert.substr(0, sp);
        }

        myApp.alert(new_data_alert, function () {

            if (new_data.indexOf(" data='file'") != -1) {
                $('.edit_block_class').toggle();
                $('.view_block_class').toggle();
                $$('.m-cb-toolbar-view-line-edit-mode-on').click();
                myApp.hideIndicator();
                return false;
            }

            var new_data_href = str_replace("<script>alert('" + new_data_alert + "')</script>", '', new_data);
            new_href = str_replace("<script>location.href='", '', trim(new_data_href));
            new_href = trim(str_replace("'</script>", '', new_href));

            if (new_href.indexOf('&uniq_line=') != -1) {
                var loc_hash = window.location.hash;
                loc_hash = loc_hash.replace('#!/', '');
                new_href += '&back_url=' + Base64.encode(loc_hash);
            }

            if (new_href.indexOf('m_calendars.php') != -1) {
                if (new_href.indexOf('?calendar_id=') != -1) {
                    var cal_id = new_href.substring(28, new_href.indexOf('&'));
                    new_href += '&back_url=' + Base64.encode('m_calendars.php?calendar_id=' + cal_id);
                }
                mainView.loadPage(new_href);
            }

            $.ajax({
                type: "GET",
                url: new_href
            })
                .then(function (response) {
                    ajaxOnSubmitAction(response, new_href);
                });
        });
    }
    else {
        new_href = trim(str_replace("<script>location.href='", '', new_data));
        new_href = trim(str_replace("'</script>", '', new_href));


        if (new_href.indexOf('m_calendars.php') != -1) {
            if (new_href.indexOf('?calendar_id=') != -1) {
                var cal_id = new_href.substring(28, new_href.indexOf('&'));
                new_href += '&back_url=' + Base64.encode('m_calendars.php?calendar_id=' + cal_id);
            }
            mainView.loadPage(new_href);
        };

        $.ajax({
            type: "GET",
            url: new_href
        })
            .then(function (response) {
                ajaxOnSubmitAction(response, new_href);
            });
    }
    // Перед сохранением в режиме редактирования
    checkFormValuesOnEditMode();
    if (new_href) {
      localStorage.setItem('redirectAfterReload', new_href);
  }
  location.reload();
});

$(document).ready(function() {
  if(window.location.hash.includes('new') || window.location.hash.includes('edit_mode=1')){

    var redirectAfterReload = localStorage.getItem('redirectAfterReload');
    if (redirectAfterReload) {
        localStorage.removeItem('redirectAfterReload'); // Удаляем использованный URL
        window.location.href = redirectAfterReload; // Перенаправляем пользователя
    }
  }
});

$$(document).on('click', 'a.sent-message', function () {
    $$('.toolbar form').trigger('submit');
});

// Conversation flag
var conversationStarted = false;
$$(document).on('submit', '.toolbar form', function (e) {
    e.preventDefault();

    // Message text
    var messageText = $$('.toolbar .message-text').val().trim();
    // Exit if empy message
    if (messageText.length === 0) return;

    // Add message
    myMessages.addMessage({
        // Message text
        text: messageText,
        // Random message type
        type: (['sent', 'sent'])[Math.round(Math.random())],
        // Day
        day: !conversationStarted ? 'Сегодня' : false,
        time: !conversationStarted ? (new Date()).getHours() + ':' + (new Date()).getMinutes() : false
    });
    // Update conversation flag
    conversationStarted = true;
    // Empty input
    $$('.toolbar .message-text').val('');
    $$('.toolbar .message-text').blur();

    // AJAX send message
    var to_user = $$('.messages').attr('to_user');

    msgQueue = {};
    msgQueue[to_user] = {};
    msgQueue[to_user]['length'] = 0;    // Счётчик сообщений на отправку в данной вкладке
    msgQueue[to_user]['messages'] = {}; // Объект сообщений на отправку

    msgQueue[to_user]['length'] += 1; // Увеличиваем счётчик

    var m_sec = 0 + new Date().getTime();
    var msg_id = 'd' + m_sec;

    // Добавляем сообщение в объект
    msgQueue[to_user]['messages'][msg_id] = messageText;

    $.ajax({ // Формируем запрос
        type: "POST",
        url: "events.php",
        data: { sel: 'put', type: 'messages', key: 'sent', value: msgQueue, csrf: csrf }
    });

    // Очищаем очередь сообщений
    msgQueue = {};
});


$$(document).on('click', '.setup_type_m2', function () {
    $$('.select-cats-manual').show();
});
$$(document).on('click', '.setup_type_f2', function () {
    $$('.select-cats-manual').hide();
});

function select_count() {
    manual = document.getElementById('setup_type_f');
    if (manual.checked) return true;

    el = document.getElementById('manual_cats');
    els = el.getElementsByTagName('INPUT');

    for (var i = 0; i < els.length; i++) {
        if (els[i].checked) return true;
    }

    myApp.alert(lang['setup_manual_count']);
    return false;
}

function create_multi_link(link) {
    let _html = '';
    let _add_html = '';
    let searchAttr = '';
    let parentFieldId = $(link).attr("fixed-search-parent-field");
    let childFieldId = $(link).attr("fixed-search-child-field");
    let parentFilter = childFilter = filter = '';
    let textValue = $(link).find("span.link_field_pretend_to_be_input .link-field__main-value").text().trim();
    const isSearchField = $(link).attr("fix_search") === '1';

    if (isSearchField) {
        searchAttr = "fix_search='1' ";
        parentFilter = $('#fix_search_value' + parentFieldId) ? ($('#fix_search_value' + parentFieldId).attr('ac_value') ? $('#fix_search_value' + parentFieldId).attr('ac_value') : $(`[data-field-id=${parentFieldId}]`).attr('ac_value')) : '';
        childFilter = $('#fix_search_value' + childFieldId) ? ($('#fix_search_value' + childFieldId).attr('ac_value') ? $('#fix_search_value' + childFieldId).attr('ac_value') : $(`[data-field-id=${childFieldId}]`).attr('ac_value')) : '';
        filter = parentFilter && parentFilter.length > 0 ? parentFilter : (childFilter && childFilter.length > 0 ? childFilter : '');
    } else {
        parentFilter = $('#value' + parentFieldId) ? $('#value' + parentFieldId).val() : '';
        childFilter = $('#value' + childFieldId) ? $('#value' + childFieldId).val() : '';
        filter = parentFilter && parentFilter.length > 0 ? parentFilter : (childFilter && childFilter.length > 0 ? childFilter : '');
    }

    $.ajax({
        type: "GET",
        url: "select_value.php",
        data: "field=" + $(link).attr("data-field-id") + "&line=" + $(link).attr("data-line-id") + "&filter_value=" + filter + "&mobile=1",
        dataType: "json",
        success: function (data) {
            $.each(data, function (k, v) {
                // Если это сообщение о том, что значений не найдено, выводим его как обычный блок
                if (v == lang['not_found_value']) {
                    _html += '<li>' +
                        '<label class="item-content" data-field-id="empty">' +
                        '<div class="item-inner m__empty-searchbar">' +
                        '<div class="item-title">' + v + '</div>' +
                        '</div>' +
                        '</label>' +
                        '</li>';
                } else {
                    _html += '<li>' +
                        '<label class="label-radio item-content m-cb-add-link-select" ' + searchAttr + 'data-field-id="' + $(link).attr("data-field-id") + '">' +
                        '<input type="radio" name="my-radio" value="' + k.replace('+','') + '">' +
                        '<div class="item-inner">' +
                        '<div class="item-title">' + v + '</div>' +
                        '</div>' +
                        '</label>' +
                        '</li>';
                }
            });
            $.ajax({
                type: "GET",
                url: "select_value.php",
                data: "field=" + $(link).attr("data-field-id") + "&filter_value=" + filter + "&option=get&mobile=1",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (i, el) {
                        _add_html += '<li ' + el["hidden_filter"] + '>' +
                            '<div class="item-content">' +
                            '    <div class="item-inner">' +
                            '       <div class="item-title label">' + el["label"] + '</div>' +
                            '       <div class="item-input">' +
                            el["input"] +
                            '       </div>' +
                            '    </div>' +
                            '</div>' +
                            '</li>'
                    });

                    let importFieldRights = true;
                    if (typeof $(link).attr('import') != 'undefined') {
                        importFieldRights = $(link).attr('import') === 'true';
                    } else {
                        importFieldRights = checkFieldImportRights($(link).attr("data-s-table-id"), 'any', $(link).attr("data-s-field-id"), $(link));
                    }

                    // Добавляем кнопку "Добавить новую запись", если есть права на импорт у связанного поля и есть права для добавления новых полей (есть код в _add_html)
                    if (importFieldRights && _add_html && _add_html.replace(/\s/g, '').length > 0) {
                        _html = '<li id="new-record">' +
                            '<label class="item-content m__new-record-row" data-field-id="new">' +
                            '<div class="item-inner">' +
                            '<div class="item-title">Добавить новую запись</div></div>' +
                            '</label>' +
                            '</li>' +
                            _html;
                    }

                    myApp.popup('<div class="popup m-cb-link-popup">' +
                        '     <div class="list-block">' +
                        '     <ul>' +
                        '<li>' +
                        '<div class="item-content">' +
                        '<div class="item-inner">' +
                        '<div class="item-input search-link-input">' +
                        '<input data-table-id="' + $(link).attr("data-table-id") + '" data-filter-id="' + $(link).attr("data-filter-id") + '" data-field-id="' + $(link).attr("data-field-id") + '" data-line-id="' + $(link).attr("data-line-id") + '" type="text" name="link_search" class="link_search" value="" placeholder="Поиск...">' +
                        '</div>' +
                        '<div class="item-text clear-btn"><div id="clear-searchbar" class="close-popup"><img src="images/cancel_b.gif"></div></div>' +
                        '</div>' +
                        '</div>' +
                        '</li>' +
                        _html +
                        '           </ul>' +
                        '       </div>' +
                        '</div>', true
                    );

                    $('#new-record').on('click', function () {
                        myApp.popup('<div class="popup m-cb-link-popup" id="new-rec-popup">' +
                            '     <div class="content-block">' +
                            '         <div class="content-block__page-title">' +
                            '           <div><span class="m__add-new-rec--title">Добавить новую запись</span></div>' +
                            '           <div class="m__close-popup-btn" data-id="new-rec" onclick="closeCurrentPopup(this);"><img src="images/cancel_b.gif"></div>' +
                            '         </div>' +
                            '       </div>' +
                            '     <div class="list-block">' +
                            '          <ul>' +
                            _add_html +
                            '          </ul>' +
                            '     </div>' +
                            '    <div class="content-block m__new-record--save-btn">' +
                            '       <a href="#" data-main-link="' + $(link).attr("data-field-id") + '" data-base-url="mfield=' + $(link).attr("data-field-id") + '&sel=save&table=' + $(link).attr("data-s-table-id") + '&line=new&csrf=' + csrf + '&" class="button button-big button-submit m-cb-add-link-btn">Сохранить</a>' +
                            '    </div>' +
                            '</div>', true
                        );
                    });

                    $("label.m-cb-add-link-select").off("click");
                    $("label.m-cb-add-link-select").on("click", function (e) {
                        e.stopPropagation();

                        const fieldId = $(this).attr('data-field-id');
                        const isFastSearch = $(this).attr('fix_search') === '1';
                        const inputValue = $('.value' + fieldId).last();
                        const itemTitle = $(this).find('.item-title');
                        const itemInput = $(this).find("input");

                        $(".value" + fieldId).val($(this).find(".item-title").text());
                        if ($(this).find(".item-title").text().trim() === textValue) {
                            myApp.closeModal('.m-cb-link-popup');
                            return false;
                        }

                        if (childFieldId && childFieldId.length > 0) {
                            $('#value' + childFieldId).val('');
                            $('#value' + childFieldId).attr('ac_value', '');
                            $(link).find("span.link_field_pretend_to_be_input").text('');
                            $(link).attr('ac_value', '');
                        }
                        inputValue.val(itemInput.val());

                        if (isFastSearch) {
                            $("#fix_search_value" + fieldId).trigger('change');
                            $("#fix_search_value" + fieldId).prev().html(itemTitle.html());
                            $("#fix_search_value" + fieldId).prev().attr('field_val', $(this).find("input[type='radio']").val());
                            inputValue.prev().html(itemTitle.html());
                            $("#fix_search_value" + fieldId).attr('ac_value', itemInput.val())
                        } else {
                            inputValue.prev().html(itemTitle.html());
                            inputValue.prev().attr('field_val', $(this).find("input[type='radio']").val());
                        }
                        $(this).off("click");
                        myApp.closeModal('.m-cb-link-popup');
                    });

                    //Добавление кнопки сброса поля
                    var fieldId = link.getAttribute('data-field-id');
                    var lineId = link.getAttribute('data-line-id');
                    createResetButton(fieldId);
                    attachResetHandler(lineId, fieldId);
                }
            });
        }
    });
    return;
}

function closeCurrentPopup(pop){
    const id = '#' + $(pop).attr('data-id') + '-popup';
    myApp.closeModal(id);
}

// Проверка поля "Связь" на наличие прав на импорт в связанном поле
// line_id - необязательный параметр, в запросе можно прописать line=any
function checkFieldImportRights(table_id, line_id, field_id, obj) {
    let import_right = true;
    $.ajax({
        url: "get_value.php?show_fields&table=" + table_id + "&line=" + line_id,
        type: "GET",
        async: false,
        success: function (response) {
            var all_fields = JSON.parse(response);
            var field_write_acc = all_fields['fields'][field_id]['write'];

            if (field_write_acc == false || field_write_acc < 1) { import_right = false; }
            obj.attr('import', import_right);
        },
        error: function () {
            console.log('Поле не найдено');
            return true;
        }
    });
    return import_right;
}

function get_childos_filter(f_id, m_id) {
    $('[data-field-id = ' + f_id + ' ]').attr('data-filter-value', $('#value' + m_id).val());
}

var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();

$(document).on('click', '#clear-searchbar', function () {
    $('.link_search').val('').trigger('input');
});

$(document).on("input", ".link_search", function () {
    let $list = $(this).parents(".list-block");
    let _value = $(this).val();
    let self = this;
    let _html = _add_html = '';
    const fieldId = $(this).attr('data-field-id');
    const textValue = $("a[data-field-id=' " + fieldId + "'] span.link_field_pretend_to_be_input").text().trim();

    if (_value.length > -1) {
        delay(function () {
            $list.find("li:not(:eq(0)):not('#new-record')").remove(); // Не удаляем строку поиска и строку добавления новой записи
            $.ajax({
                type: "GET",
                url: "select_value.php",
                data: "table=" + $(self).attr("data-table-id") + "&filter=" + $(self).attr("ac_value") + "&field=" + $(self).attr("data-field-id") + "&line=" + $(self).attr("data-line-id") + "&q=" + _value + "&mobile=1",
                dataType: "json",
                success: function (data) {
                    var class_link = "";
                    if (data["error"]) {
                        $.each(data, function (k, v) {
                            _html += '<li>' +
                                '<label class="item-content" data-field-id="' + $(self).attr("data-field-id") + '">' +
                                '<div class="item-inner">' +
                                '<div class="item-title">' + v + '</div>' +
                                '</div>' +
                                '</label>' +
                                '</li>'
                        });
                    } else {
                        $.each(data, function (k, v) {
                            _html += '<li>' +
                                '<label class="label-radio item-content m-cb-add-link-select" fix_search="1" data-field-id="' +
                                        $(self).attr("data-field-id") + '">' +
                                '<input type="radio" name="my-radio" value="' + k + '">' +
                                '<div class="item-inner">' +
                                '<div class="item-title">' + v + '</div>' +
                                '</div>' +
                                '</label>' +
                                '</li>'
                        });
                    }

                    $list.find("ul").append(_html);
                    $("label.m-cb-add-link-select").off("click");
                    $("label.m-cb-add-link-select").on("click", function (e) {
                        e.stopPropagation();
                        const isFastSearch = $(this).attr('fix_search') === '1';

                        $(".value" + $(this).attr("data-field-id")).val($(this).find(".item-title").text());
                        if ($(this).find(".item-title").text() === textValue) {
                            myApp.closeModal('.m-cb-link-popup');
                            return false;
                        }

                        $("#value" + fieldId).val($(this).find("input").val());

                        if (isFastSearch) {
                            $("#fix_search_value" + fieldId).trigger('change');
                            $("#fix_search_value" + fieldId).prev().text($(this).find(".item-title").text());
                            $("#fix_search_value" + fieldId).prev().attr('field_val', $(this).find("input[type='radio']").val());
                            $("#value" + fieldId).prev().text($(this).find(".item-title").text());
                            $("#fix_search_value" + fieldId).attr('ac_value', $(this).find("input").val())
                        } else {
                            $("#value" + fieldId).prev().text($(this).find(".item-title").text());
                            $("#value" + fieldId).prev().attr('field_val', $(this).find("input[type='radio']").val());
                        }
                        $(this).off("click");
                        myApp.closeModal('.m-cb-link-popup');
                    });
                }
            });

        }, 150);
    }
    ;
    return;
});

$$(document).on("click", ".m-cb-add-link-btn", function () {
    let base_url = $(this).attr("data-base-url");
    let main_field = $(this).attr("data-main-link");
    let list_params = $(this).parent().prev().find("ul li");
    let temp = $('[data-field-id = ' + main_field + ']');
    let line_id = 0;
    let newValue = '';

    $.each(list_params, function (i, el) {
        if ($(el).find("select").val()) {
            base_url += "value[new][" + $(el).find("select").attr("field_id") + "]=" + $(el).find("select").val() +
                "&edit[new][" + $(el).find("select").attr("field_id") + "]=1&";
            newValue = $(el).find("select").val();
        }
        else if ($(el).find("textarea").val()) {
            base_url += "value[new][" + $(el).find("textarea").attr("field_id") + "]=" + $(el).find("textarea").val() +
                "&edit[new][" + $(el).find("textarea").attr("field_id") + "]=1&";
            newValue = $(el).find("textarea").val();
        }
        else {
            base_url += "value[new][" + $(el).find("input").attr("field_id") + "]=" + $(el).find("input").val() +
                "&edit[new][" + $(el).find("input").attr("field_id") + "]=1&";
            newValue = $(el).find("input").val();
        }

        if (!line_id) line_id = $(el).find("input").attr("line_id");
    });

    $.ajax({
        type: "POST",
        url: "view_line2.php",
        data: base_url,
        success: function (data) {
            if (data.includes('<!DOCTYPE html>')) {
                myApp.closeModal('.m-cb-link-popup');
                myApp.alert(lang['Error']);
            } else {
                data = data.split("|");
                if (data[0] == 'dupl') {
                    myApp.alert(lang['fast_field_already_exists_p1'] + ' ' + lang['fast_field_already_exists_p2']);
                } else {
                    $(".value" + line_id).val(data[2]);
                    $(".value" + line_id).prev().text(Base64.decode(data[3]));
                    myApp.closeModal('.m-cb-link-popup');
                }
            }
        }
    });
});

$$(document).on("click", ".open-calendar-tab", function () {
    let popup = '';

    popup = '<div class="popup popup-cal-type">' +
        $(this).parents('.toolbar').prev().find('.add_calendar_event').html() +
        '</div>';

    myApp.popup(popup);

});

$$(document).on('opened', '.popup-cal-type', function () {
    $("label.type_event_radio").unbind("click");
    $("label.type_event_radio").one("click", function () {
        var $selfy = $$('.page-on-center');
        var n_popup = $$('.add_calendar_event').html();
        var type = $$(this).children('.type_event_radio_value').val();
        var cal_id = $selfy.find('.get_calendar_id').val();
        var year_id = $selfy.find('.get_year_id').val();
        var month_id = $selfy.find('.get_month_id').val();
        var day_id = $selfy.find('.get_day_id').val();
        var _add_html = '';
        var _add_html_mass_field = '';
        var _html = '';

        $.ajax({
            type: "POST",
            url: "m_calendars.php",
            data: 'get_add_field=1&event_type=' + type + '&calendar_id=' + cal_id + '&year=' + year_id + '&month=' + month_id + '&day=' + day_id + '&csrf=' + csrf,
            dataType: "json",
            success: function (data) {
                $.each(data, function (i, el) {
                    //_add_html += '<input type="hidden" name="month_id" value="{$calendar_id}" class="get_month_id">';
                    //_add_html += '<input type="hidden" name="day_id" value="{$calendar_id}" class="get_month_id">';
                    if (el['mass_field']) {
                        _add_html_mass_field += '<li>' +
                            '<div class="item-content">' +
                            '    <div class="item-inner">' +
                            '       <div class="item-title label">' + el["label"] + '</div>' +
                            '       <div class="item-input">' +
                            el["input"] +
                            '       </div>' +
                            '    </div>' +
                            '</div>' +
                            '</li>';
                    }
                    else if (el['type_field'] != 5) {
                        _add_html += '<li>' +
                            '<div class="item-content">' +
                            '    <div class="item-inner">' +
                            '       <div class="item-title label">' + el["label"] + '</div>' +
                            '       <div class="item-input">' +
                            el["input"] +
                            '       </div>' +
                            '    </div>' +
                            '</div>' +
                            '</li>';
                    }
                    else {
                        _add_html += '<li>' +
                            '<a href="#" class="item-link m-cb-control-multi-link" data-table-id="' + el["table_id"] + '" data-filter-id="" data-line-id="" data-field-id="' + el["field_id"] + '" data-s-table-id="' + el["s_table_id"] + '" data-s-field-id="' + el["s_field_id"] + '" data-csrf="IUegLzSqkLaQz173wzt5Bg==">' +
                            '<div class="item-content">' +
                            '    <div class="item-inner ie_component_fuck">' +
                            '       <div class="item-title label">' + el["label"] + '</div>' +
                            '       <div class="item-input" style="margin-left: 14px;">' +
                            el["input"] +
                            '       </div>' +
                            '    </div>' +
                            '</div>' +
                            '</a>' +
                            '</li>';
                    }
                });

                mainView.loadContent(
                    '<div class="pages">' +
                    '  <!-- Page, data-page contains page name-->' +
                    '  <div data-page="dynamic-pages" class="page">' +
                    '    <!-- Scrollable page content-->' +
                    '    <div class="page-content">' +
                    //'       <div class="list-block">'+
                    // '           <ul>'+
                    // _html +
                    //'               <li>'+
                    //'                   <span href="#" class="item-link list-button">lang.Add</span>'+
                    //'               </li>'+
                    // '           </ul>'+
                    //  '       </div>'+
                    '    <div class="content-block-title" style="margin:69px 0px 0px 0px;">' + lang.Add + '</div>' +
                    '    <form action="m_calendars.php?calendar_id=' + cal_id + '&month=' + month_id + '&day=' + day_id + '&event_type=' + type + '&add_event=1&csrf=' + csrf + '" method="POST" class="ajax-submit">' +
                    '      <div class="list-block inset">' +
                    '        <ul>' +
                    _add_html_mass_field +
                    '        </ul>' +
                    '      </div>' +

                    '      <div class="list-block inset">' +
                    '        <ul>' +
                    _add_html +
                    '        </ul>' +
                    '      </div>' +
                    '      <div class="content-block">' +
                    '        <input type="submit" class="ajax-submit-button" style="display: none;"/>' +
                    '        <a href="#" data-base-url="" class="button button-big  button-submit m-cb-add-link-btn-calendar">Сохранить</a>' +
                    '      </div>' +
                    '    </form>' +
                    '  </div>' +
                    '</div>'
                );

                myApp.closeModal();
            }
        });
    });
});

$$(document).on("click", ".close-calendar-tab", function () {
    myApp.showIndicator();
    $.ajax({ // Формируем запрос
        type: "POST",
        url: "events.php",
        data: { sel: 'put', type: 'tips', key: 'close', value: 'all', csrf: csrf },
        success: function (msg) { // Сообщение с сервера
            $.ajax({
                type: "GET",
                url: 'm_tips.php'
            })
                .then(function (response) {
                    re = /<div class="page-content pull-to-refresh-content messages-content">([\s\S]*?)<\/div> <!-- Page Content -->/im;
                    found = response.match(re);
                    if (found == null) {
                        re = /<div class="page-content pull-to-refresh-content ">([\s\S]*?)<\/div> <!-- Page Content -->/im;
                        found = response.match(re);
                    }
                    if (found == null) {
                        re = /<div class="page-content pull-to-refresh-content">([\s\S]*?)<\/div> <!-- Page Content -->/im;
                        found = response.match(re);
                    }
                    if (found != null) {
                        msg = found[1];
                        $$('.pull-to-refresh-content').html(msg);
                    }

                    // When loading done, we need to reset it
                    myApp.pullToRefreshDone();
                    myApp.hideIndicator();
                });
        }
    });
});

//$( document ).on("click", "label.type_event_radio", function () {
//  var n_popup = $$('.add_calendar_event').html();
//  var type = $$(this).children('.type_event_radio_value').val();
//  var cal_id = $$('.get_calendar_id').val();
//  var month_id = $$('.get_month_id').val();
//  var day_id = $$('.get_day_id').val();
//  var _add_html = '';
//  var _html = '';
//
//  $.ajax({
//           type: "POST",
//           url: "m_calendars.php",
//           data: 'get_add_field=1&event_type='+type+'&calendar_id='+cal_id+'&month='+month_id+'&day='+day_id+'&csrf='+csrf,
//           dataType: "json",
//           success: function(data){
//             $.each(data, function(i, el){
//               //_add_html += '<input type="hidden" name="month_id" value="{$calendar_id}" class="get_month_id">';
//               //_add_html += '<input type="hidden" name="day_id" value="{$calendar_id}" class="get_month_id">';
//               _add_html += '<li>'+
//                            '<div class="item-content">'+
//                            '    <div class="item-inner">'+
//                            '       <div class="item-title label">'+el["label"]+'</div>'+
//                            '       <div class="item-input">'+
//                                      el["input"]+
//                            '       </div>'+
//                            '    </div>'+
//                            '</div>'+
//                            '</li>'
//             });
//
//             mainView.loadContent(
//               '<div class="pages">' +
//               '  <!-- Page, data-page contains page name-->' +
//               '  <div data-page="dynamic-pages" class="page">' +
//               '    <!-- Scrollable page content-->' +
//               '    <div class="page-content">' +
//               //'       <div class="list-block">'+
//              // '           <ul>'+
//              // _html +
//                 //'               <li>'+
//                 //'                   <span href="#" class="item-link list-button">lang.Add</span>'+
//                 //'               </li>'+
//              // '           </ul>'+
//             //  '       </div>'+
//               '    <div class="content-block-title">lang.Add</div>'+
//               '    <form action="m_calendars.php?calendar_id='+cal_id+'&month='+month_id+'&day='+day_id+'&event_type='+type+'&add_event=1&csrf='+csrf+'" method="POST" class="ajax-submit">'+
//               '      <div class="list-block inset">'+
//               '        <ul>'+
//               _add_html +
//               '        </ul>'+
//               '      </div>'+
//               '      <div class="content-block">'+
//               '        <input type="submit" class="ajax-submit-button" style="display: none;"/>'+
//               '        <a href="#" data-base-url="" class="button button-submit m-cb-add-link-btn-calendar">Сохранить</a>'+
//               '      </div>'+
//               '    </form>'+
//               '  </div>' +
//               '</div>'
//             );
//
//             myApp.closeModal();
//           }
//         });
//});

$$(document).on("click", ".m-cb-add-link-btn-calendar", function (e) {
    e.preventDefault();
    $$('.ajax-submit-button').click();
});

$$(document).on("click", ".list-group .item-title", function () {
    if ($(this).hasClass("active")) {
        $(this).removeClass("active");
    } else {
        $(this).addClass("active");
    }
});

function popup_for_img(e,el){
    if ($(el).has("img").length > 0) {
        e.stopPropagation();

        var url = $(el).attr('href');
        var popupHTML = '<div class="popup">' +
            '<div class="content-block">' +
            '<p><a href="#" class="close-popup">Закрыть</a></p>' +
            '<img src="' + url + '" style="width: 100%;height: 100%;" onload="myApp.hideIndicator();">' +
            '</div>' +
            '</div>';
        myApp.popup(popupHTML);
        myApp.showIndicator();
    }
}

$$(document).on("click", "#view_block .item-input a", function (e) {
    popup_for_img(e,this);
});

$$(document).on("click", "#edit_block .item-input a", function (e) {
    popup_for_img(e,this);
});

function open_dialog(mode, $page) {
    $$('.m-cb-toolbar-edit-mode-on').click();

    var $self = $('.m-cb-toolbar-edit-mode-on');
    if ($self.attr("data-active-mode") == "1") {
        $('.item-link').toggle();
        $('.label-checkbox').toggle();
        if ($self.attr("data-active-mode") == "0") {
            $self.attr("data-active-mode", "1");
            $self.text("Готово");
        } else {
            $self.attr("data-active-mode", "0");
            $self.text("Выбрать");

        }
    }

    var popupHTML = '<div class="popup">' +
        $page.find('.dialog_' + mode).html() +
        '</div>';
    myApp.popup(popupHTML);
    return false;
}

function dial_form(op, id, type, warning, from) {
    if (!from) {
        var $form_sel = $(".page-on-center #form_sel"),
            $form_type = $(".page-on-center #form_type"),
            $sel_records = $(".page-on-center #sel_records");

        $form_sel.val(id);
        $form_type.val(type);
    }
    else {
        var $form_sel = $(".page-on-center #form"),
            $form_type = $(".page-on-center #form_type"),
            $form_op = $(".page-on-center #op"),
            $sel_records = $(".page-on-center #sel_records");

        $form_sel.val(id);
        $form_type.val(type);
        $form_op.val(op);
    }

    $('.page-on-center .ajax-submit-button').click();
}

function downloadMobilePdf(tableId, formId, mobLineId) {
    location.href = typeof mobLineId != 'undefined' ? `forms.php?table=${tableId}&form=${formId}&mob_line_id=${mobLineId}` : `forms.php?table=${tableId}&form=${formId}`;
    $('.page-on-center .ajax-submit-button').click();
}

function refresh_idx() {
    $.ajax({ // Формируем запрос
        type: "POST",
        url: "events.php",
        data: { sel: 'get', csrf: csrf },
        dataType: "json",
        success: function (data) {
            $(".m-cb-msg-count").text(data["messages_count"]);
            $(".m-cb-tips-count").text(data["tips_count"]);
            $(".m-cb-calendar-count").text(data["calendars_count"]);
            var a = parseInt(data["messages_count"], 10);
            var b = parseInt(data["tips_count"], 10);
            if (data["calendar_count"]) {
                var z = parseInt(data["calendar_count"], 10);
                var c = a + b + z;
            } else {
                var c = a + b;
            }

            if (c >= 100) {
                $(".m-cb-header-all-count").text(">99");
            } else {
                $(".m-cb-header-all-count").text(c.toString());
            }
            if (data["messages"] != "EMPTY") {
                var from_user = window.location.href
                if (from_user.indexOf("mess_user=") != -1) {
                    from_user = from_user.substr(from_user.indexOf("mess_user=") + 10)
                    $.each(data["messages"], function (i, val) {
                        if (val["from_user"] == from_user) {
                            // Add message
                            var d = val["add_time"];
                            var day = d.split(" ")[0]
                            var time = d.split(" ")[1]
                            myApp.addMessage({
                                // Message text
                                text: val["message"],
                                // Random message type
                                type: (['received', 'received'])[Math.round(Math.random())],
                                // Day
                                time: day.split("-")[2] + '.' + day.split("-")[1] + '.' + day.split("-")[0],
                                day: time.split(":")[0] + ':' + time.split(":")[1]
                            })
                            // Update conversation flag
                            conversationStarted = true;
                            // Empty input
                            $$('.toolbar .message-text').val('');
                            $$('.toolbar .message-text').blur();

                        }
                    });
                }
                if (from_user.indexOf("chat=") != -1) {
                    from_user = from_user.substr(from_user.indexOf("chat=") + 5)
                    $.each(data["messages"], function (i, val) {
                        //if(val["from_user"] == from_user){
                        // Add message
                        var d = val["add_time"];
                        var day = d.split(" ")[0]
                        var time = d.split(" ")[1]
                        var from_user_fio = data["users"][val["from_user"]]["fio"];
                        var msg_text = '<div class="message-name" style="font-size: 12px;font-weight: bold;color: #bf6b6f;">' + from_user_fio + '</div>' +
                            '<div class="message-text">' + val["message"] + '</div>';
                        myApp.addMessage({
                            // Message text
                            text: msg_text,
                            // Random message type
                            type: (['received', 'received'])[Math.round(Math.random())],
                            // Day
                            time: day.split("-")[2] + '.' + day.split("-")[1] + '.' + day.split("-")[0],
                            day: time.split(":")[0] + ':' + time.split(":")[1]
                        })
                        // Update conversation flag
                        conversationStarted = true;
                        // Empty input
                        $$('.toolbar .message-text').val('');
                        $$('.toolbar .message-text').blur();

                    });
                }
            }
            if (typeof data["users"] !== 'string') {
                $.each(data["users"], function (i, val) {
                    if (val["online"] == 0) {
                        $("[data-msg-user-id=" + i + "]").removeClass("user-online");
                        $("[data-msg-user-id=" + i + "]").addClass("user-offline");
                    } else {
                        $("[data-msg-user-id=" + i + "]").removeClass("user-offline");
                        $("[data-msg-user-id=" + i + "]").addClass("user-online");
                    }
                });
            }
        }
    });
}

$(document).on("click", function () {
    refresh_idx();
});

$(window).on('popstate', function () { // скрываем popup при смене истории браузера
    myApp.closeModal('.popup.modal-in');
});

var last_sub_table = undefined;
function addfile() {
    var page = $('.page-on-center');
    var self = $(page).find('.m-cb-toolbar-view-line-edit-mode-on');
    self.parents(".toolbar").prev().find('.ajax-submit-button').click();
    $('#m__circle-edit').parent().attr('data-active-mode', '0');
    self.find('#m__circle-edit').addClass('m__circle-yellow');
    self.find('#m__circle-edit').removeClass('m__circle-green');
    self.find('#m__circle-edit').addClass('m__circle-pencil');
    self.find('#m__circle-edit').removeClass('m__circle-save');
    self.parent().parent().find('#m__circle-dots').toggle()
}

function checkFileValue(val) {
    if (val.value.length !== 0) {
        $(val).next().removeAttr("disabled");
    } else {
        $(val).next().attr('disabled', 'disabled');
    }
};

$(document).on("click", '.get-subline-add', function (e) {
    e.preventDefault();
    last_sub_table = $(this).parents(".collapse").prev();

    var page = $('.page-on-center');
    var self = $(page).find('.m-cb-toolbar-view-line-edit-mode-on');

    if (self.attr("data-active-mode") == "1") {
        self.parents(".toolbar").prev().find('.ajax-submit-button').click();
    }

    var datty = $(this).data();
    $.ajax({ // Формируем запрос
        type: "GET",
        url: "fields.php" + datty['href'],
        success: function (data) {
            //mainView.loadPage('view_line2.php' + datty['href']);
        }
    });
});

$(document).on("change", ".extra-ajax-field", function () {
    /*myApp.showIndicator();
    var $form = $(this).parents("form");
    $form.find(".edit_mode_save").val('1');
    $form.find(".ajax-submit-button").click();
    d.done(function () {
        //$('.edit_block_class').show();
        //$('.view_block_class').hide();
        d = $.Deferred();
    });*/
});

$(function () {
    var loc_hash_temp = window.location.hash;
    if ($$('.back_custom').hasClass('back') && loc_hash_temp == '') {
        var back_url = getUrlVars2(window.location.href)["back_url"];//$.getUrlVar('back_url');
        back_url = Base64.decode(back_url);
        var st = back_url.indexOf('|');
        if (st != -1) back_url = back_url.substr(st + 1);
        if (back_url) {
            if (back_url.charAt(0) == '/mobile/') back_url = back_url.substr(8);
            $$('.back_custom').removeClass('back');
            $$('.back_custom').attr('href', back_url);
        }
    }
});

function hithere(e) {
    if (e) {
        var element_to_hide = e.nextElementSibling;
        if (element_to_hide.hasAttribute('closed')) {
            if (element_to_hide.getAttribute('closed') == 'false') {
                element_to_hide.setAttribute('closed', 'true');
                element_to_hide.style.height = '0';
                element_to_hide.style.opacity = '0';
                element_to_hide.style.position = 'absolute';
                element_to_hide.style.transform = 'translate(0, 4000px)';
                e.children[0].children[1].style.display = 'block';
            } else {
                element_to_hide.setAttribute('closed', 'false');
                element_to_hide.style.height = 'auto';
                element_to_hide.style.opacity = '1';
                element_to_hide.style.position = 'relative';
                element_to_hide.style.transform = 'translate(0, 0)';
                e.children[0].children[1].style.display = 'none';
            }
        }
    }
}

$(document).ready(function () {
    setInterval(function () {
        refresh_idx();
    }, 120000);
});

function checkDateField() {
    $('.list-block .item-input .valval.datepicker[field-type=2]').each(function (i, date) {
        $date = $(date);
        $date.on('change', function () {
        });
    });
}

function defaultPlaceholderForNumbers() {
    $('.item-content .item-inner .item-input[field-type=1]').each(function (i, this_item) {
        this_item = $(this_item);
        const field_text = this_item.text().replace(/\s/g, '');
        const defaut_val = this_item.attr('data-default').replace(/\s/g, '');

        //Если поле не заполнено, выставляем значение по умолчанию
        if (field_text == '') {
            this_item.text(defaut_val).css('color', 'gray');
        }
    });
}

// Проверка значения текстовых полей перед сохранением
function checkTextOnEditMode() {
    let this_error;
    $('.list-block .valval[field-type=3]').each(function (i, item) {
        if(check_click(item.id.substring(5))){
            this_error = true;
        };
    });
    return this_error;
}

// Проверка значения числовых полей в режиме редактирования
function checkFormValuesOnEditMode() {
    $('.list-block .valval[field-type=1]').each(function (i, item) {
        item = $(item);
        const default_value = item.attr('data-default').replace(/\s/g, '');
        const cur_value = item.val().replace(/\s/g, '');

        if ((cur_value == '' || (cur_value == 0 && default_value != 0)) && cur_value !== '0') {
            item.val(default_value).text(default_value).css('color', 'gray');
        }
    });
}

// Проверка значения числовых полей перед началом редактирования
function checkDataOnChangingMode() {
    $('.list-block .valval[field-type=1]').each(function (i, edit_item) {
        edit_item = $(edit_item);
        const default_value = edit_item.attr('data-default').replace(/\s/g, '');

        // if (edit_item.val().replace(/\s/g, '') == default_value) {
        //     edit_item.css('color', 'gray');
        // }
        // Добавляем слушателя при клике на поле
        addClickListenerToNumberField(edit_item, default_value);

        // Если изменили значение поля, изменяем его value
        edit_item.blur(function () {
            edit_item.val($(this).val());
            edit_item.attr('value', edit_item.val().replace(/\s/g, ''));
            addClickListenerToNumberField(edit_item, default_value);
        });
        edit_item.on('keyup', function () {
            if (edit_item.val().replace(/\s/g, '') == '') {
                edit_item.val('');
            }
        });
    });
}

function setTextColorForEditFields(colorr) {
    $('.list-block .valval[field-type=1]').each(function (i, item) {
        $(item).css('color', colorr);
    });
}

// Проверка значения поля и проставление курсора в конец строки
function addClickListenerToNumberField(item_, def_value) {
    item_.click(function () {
        checkClickOnNumberField(item_, def_value);
    });
}

function checkClickOnNumberField(item, defValue) {
    const $item = $(item);
    let curVal = parseFloat($item.val().replace(/\s/g, '').replace(',', '.'));
    let newVal = $item.val();
    defValue = parseFloat(defValue);

    if (curVal.toFixed(10) == defValue.toFixed(10)) {
        $item.val('').focus().css('color', '#000');
    } else {
        $item.val('').focus().val(newVal).css('color', '#000');
    }
}

function checkNewValueOfNumberField(item, defValue) {
    const $item = $(item);
    const curVal = $item.val();
    if (curVal.replace(/\s/g, '') == '' && curVal !== '0') {
        $item.val('').val(defValue).css('color', 'gray');
    }
}

function deleteTrimAndBrackets(el) {
    el = $(el);
    const tableId = el.attr('table_id');
    const fieldId = el.attr('field_id');
    const isMultValue = el.attr('mult_value');
    const table_newdata = init_data(tableId);
    const elVal = el.prev('.link_field_pretend_to_be_input').attr('field_val');
    const elText = el.prev('.link_field_pretend_to_be_input').text();
    // const indexOfBracket = elText.indexOf('(');
    let newVal = elText; //indexOfBracket !== -1 ? elText.slice(0, elText.indexOf('(') - 1) : elText;
    newVal = newVal.trim();

    if (isMultValue) {
        let count = $('#mult_link_count' + fieldId).text().trim().length > 0 ? parseInt($('#mult_link_count' + fieldId).text()) : 0;
        const hiddenVal = $('#fix_search_mult' + fieldId);
        const newCheckBox = $('<input type="checkbox" name="fix_search[' + fieldId + '][value][]" checked value="' + newVal +
                              '" id="fix_search_ch' + fieldId + '_' + elVal +'" onclick="completePseudoSelect(' + fieldId + ', 1, ' + tableId + '); event.cancelBubble=true">');
        const chBoxLabel = $('<label for="fix_search_ch' + fieldId + '_' + elVal + '" onclick="completePseudoSelect(' + fieldId + ', 1, ' + tableId +
                             '); event.cancelBubble=true">' + elText + '<input type="hidden" name="fix_search[' + fieldId + '][value_link][]" value="' + elVal + '"></label>');
        const multValueRow = $('<div class="pseudo_select__wrap pseudo_select__wrap--multi-link"></div>');

        multValueRow.append(newCheckBox).append(chBoxLabel);
        $('#fix_search_mult' + fieldId).val('exist');
        $('#pseudo_select_options' + fieldId).append(multValueRow).show();
        $('#mult_link_count' + fieldId).text('+' + ++count)
        hiddenVal.val(newVal);
    }
    el.val(newVal);
    if (parseInt(table_newdata['fix_search_submit']) === 0) {
        document.getElementById('fix_search_form').submit();
    }
}

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

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

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

    if (isLink == undefined) {
        if (search_text == "")
            search_text = "&nbsp;";
        document.getElementById("pseudo_select_text" + fieldId).innerHTML = search_text;
    }
    else {
        if (search_count == 0) {
            document.getElementById("pseudo_select_options" + fieldId).style.display = "none";
            document.getElementById("mult_link_count" + fieldId).innerHTML = "";
            document.getElementById("fix_search_value" + fieldId).value = "";
            document.getElementById("fix_search_" + fieldId + "_link_value").value = "";

            $("#fix_search_value" + fieldId).prev('span.m__fixed-search--link').text('');

        }
        else
            document.getElementById("mult_link_count" + fieldId).innerHTML = "+" + search_count;
    }
    if (parseInt(table_newdata['fix_search_submit']) === 0) {
        document.getElementById('fix_search_form').submit();
    }
}

function setPlaceholder(field) {
    const phValue = $(field).attr('data-val-type').replace(/\s/g, '').trim();
    const cur_value = $(field).val().replace(/\s/g, '').trim();

    if (cur_value === '' || cur_value.length) {
        $(field).val(phValue);
    }

    $(field).attr('placeholder', phValue);
}

function removePlaceholder(field) {
    const curVal =  $(field).val().replace(/\s/g, '').trim();

    if (curVal === '' || curVal.length < 1) {
        $(field).attr('placeholder', '');
    }
}

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

function init_data(table_id) {
    var result = {};

    $.ajax({
        method: 'GET',
        async: false,
        url: 'get_value.php?&show_lines&table=' + table_id,
        success: function (resp) {
            result = JSON.parse(resp);
            hideEmptyGroups();
            onchange_3711();
            onchangeView_3711();
        },
        error: function () {
            console.log('Ошибка загрузки');
        }
    });

    return result;
}

function fixed_search_chage_period(num, element) {
    if (document.getElementById('fix_search2_' + num).value &&
        ($(element).parent().parent().find('.default-btn.fields__search-btn.fields__template-btn').length === 0)) {
        document.getElementById('fix_search_form').submit();
    }
}

// Функция для проверки одинаковых дат и замена времени на 23:59
let fixed_search_datapicker_values = num => {
    let firstDate = $('#fix_search_' + num)
    let firstDateVal = firstDate.val()
    let secondDate = $('#fix_search2_' + num)
    let secondDateVal = secondDate.val()

    if ( firstDateVal && secondDateVal ) {
        secondDate.val( secondDateVal.replace('00:00','23:59') )
    }
}
/**
 * Метод, скрывающий пустые группы (без полей)
 **/
function hideEmptyGroups() {
    const userDataGroup = $('div.m__f-group-header');
    const editGroupFields = $('div.list-group.main-field');

    if (userDataGroup.length > 0) {
        userDataGroup.each(function (i, item) {
            $item = $(item);

            if (!$item.next().hasClass('m__f-group-list')) $item.hide();
        });
    }

    if (editGroupFields.length > 0) {
        editGroupFields.each(function (idx, row) {
            $row = $(row);

            if ($row.next('div.list-group').length > 0) {
                if ($row.next().hasClass('main-field')) $row.hide();
            } else {
                $row.hide();
            }
        });
    }

    onchangeView_3711();
}

function onchange_3711 () {
  const typeVal = $('#value3711').val();

  if (typeVal == 'Юр.лицо') {
        $('div.list-group.main-field[field_id="140"]').css('display', '');
        $('.list-group[field_id="' + 435 + '"]').css('display', '');
        $('.list-group[field_id="' + 3721 + '"]').hide();
        $('.list-group[field_id="' + 443 + '"]').css('display', '');
        $('.list-group[field_id="' + 439 + '"]').css('display', '');
        $('.list-group[field_id="' + 440 + '"]').css('display', '');
        $('.list-group[field_id="' + 1056 + '"]').css('display', '');
        $('.list-group[field_id="' + 1057 + '"]').css('display', '');
        $('.list-group[field_id="' + 1058 + '"]').css('display', '');
        $('.list-group[field_id="' + 1059 + '"]').css('display', '');
        $('.list-group[field_id="' + 1060 + '"]').css('display', '');
        $('.list-group[field_id="' + 1061 + '"]').css('display', '');
        $('.list-group[field_id="' + 1062 + '"]').css('display', '');
        $('.list-group[field_id="' + 1063 + '"]').css('display', '');
        $('.list-group[field_id="' + 1064 + '"]').css('display', '');
        $('.list-group[field_id="' + 1065 + '"]').css('display', '');
        $('.list-group[field_id="' + 3810 + '"]').css('display', '');
        $('.list-group[field_id="' + 4880 + '"]').css('display', '');
        $('div.list-group.main-field[field_id="11"]').hide();
        $('.list-group[field_id="' + 3741 + '"]').hide();
        $('.list-group[field_id="' + 3751 + '"]').hide();
        $('.list-group[field_id="' + 3761 + '"]').hide();
        $('.list-group[field_id="' + 3771 + '"]').hide();
        $('.list-group[field_id="' + 3781 + '"]').hide();
        $('.list-group[field_id="' + 3791 + '"]').hide();
  } else if (typeVal == 'Физ.лицо') {
        $('div.list-group.main-field[field_id="140"]').hide();
        $('.list-group[field_id="' + 435 + '"]').hide();
        $('.list-group[field_id="' + 3721 + '"]').css('display', '');
        $('.list-group[field_id="' + 443 + '"]').hide();
        $('.list-group[field_id="' + 439 + '"]').hide();
        $('.list-group[field_id="' + 440 + '"]').hide();
        $('.list-group[field_id="' + 1056 + '"]').hide();
        $('.list-group[field_id="' + 1057 + '"]').hide();
        $('.list-group[field_id="' + 1058 + '"]').hide();
        $('.list-group[field_id="' + 1059 + '"]').hide();
        $('.list-group[field_id="' + 1060 + '"]').hide();
        $('.list-group[field_id="' + 1061 + '"]').hide();
        $('.list-group[field_id="' + 1062 + '"]').hide();
        $('.list-group[field_id="' + 1063 + '"]').hide();
        $('.list-group[field_id="' + 1064 + '"]').hide();
        $('.list-group[field_id="' + 1065 + '"]').hide();
        $('.list-group[field_id="' + 3810 + '"]').hide();
        $('.list-group[field_id="' + 4880 + '"]').hide();
        $('div.list-group.main-field[field_id="11"]').css('display', '');
        $('.list-group[field_id="' + 3741 + '"]').css('display', '');
        $('.list-group[field_id="' + 3751 + '"]').css('display', '');
        $('.list-group[field_id="' + 3761 + '"]').css('display', '');
        $('.list-group[field_id="' + 3771 + '"]').css('display', '');
        $('.list-group[field_id="' + 3781 + '"]').css('display', '');
        $('.list-group[field_id="' + 3791 + '"]').css('display', '');
  }
}

function onchangeView_3711() {
    const typeVal = $('#edit_3711').text().trim();

    if (typeVal == 'Юр.лицо') {
        $('#view_block #group-field-140').css('display', '');
        $('#view_block #group-field-140').next().css('display', '');
        $('#view_block #group-field-11').hide();
        $('#view_block #group-field-11').next().hide();
    } else if (typeVal == 'Физ.лицо') {
        $('#view_block #group-field-140').hide();
        $('#view_block #group-field-140').next().hide();
        $('#view_block #group-field-11').css('display', '');
        $('#view_block #group-field-11').next().css('display', '');
    }
}

$$(document).on('change', '#value3711', function (e) {
    onchange_3711();
});


function initInputsRightChange() {
  let inputs = document.querySelectorAll('input:not([type="hidden"])')
  //console.log(inputs)
  inputs.forEach( (input) => {
    input.addEventListener('change', (e) => {
      //console.log(e)
      let value = e.target.value
      let field_id = e.target.id.replace('value', '')

      checkRights(value, field_id)
    })
  })

  let selects = document.querySelectorAll('select:not([type="hidden"])')
  selects.forEach( (select) => {
    select.addEventListener('change', (e) => {
      let value = e.target.value
      let field_id = e.target.id.replace('value', '')

      checkRights(value, field_id)
    })
  })
}
function checkRights(value = false, field_id = false) {
  let value_string
  if (!value || !field_id) {
    let first_finded_input = document.querySelector('[id*="value"]:not([type="hidden"])')
    value = first_finded_input.value
    field_id = first_finded_input.id.replace('value', '')

    value_string = `values[${field_id}]=${value}`
  } else {
    value_string = `values[${field_id}]=${value}`
  }
  let params = window.location.href.split(/[?&]/)
  let table_id = params.find(element => element.includes('table')).split('=').pop()

  $.ajax({
    type: "GET",
    url: `get_rights.php?table_id=${table_id}&line_id=14&${value_string}`,

  }).then(function(response) {
    let update_strings_arr = response.toString().split('\r\n')


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

    if (foundShow) {
        let foundShowArr = foundShow.split('|');
        foundShowArr.shift();
        foundShowArr.forEach( (item) => {
            let show_field_id = item;
            let field = document.querySelector(`[field_id="${show_field_id}"]`);
            field.style.display = 'block'
            field.classList.add('field-show')
            field.classList.remove('field-hidden')
        })

    }
    if (foundNoEdit) {
        let foundNoEditArr = foundNoEdit.split('|');
        foundNoEditArr.shift();
        foundNoEditArr.forEach( (item) => {
            let no_edit_field_id = item;
            let field = document.querySelector(`[field_id="${no_edit_field_id}"]`);
            //console.log(field)
            field.classList.add('field-no-edit')
            field.classList.remove('field-can-edit')
        })

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

            field.classList.add('field-hidden')
            field.classList.remove('field-show')
        })

    }
    if (foundCanEdit) {
        let foundCanEditArr = foundCanEdit.split('|');
        foundCanEditArr.shift();
        foundCanEditArr.forEach( (item) => {
            let edit_field_id = item;
            let field = document.querySelector(`[field_id="${edit_field_id}"]`);
            field.classList.add('field-can-edit')
            field.classList.remove('field-no-edit')
            //console.log(field)
        })

    }
  });
}

/**
 * Создание кнопки сброса значения поля
 * @param {string} fieldId    id сбрасываемого поля
 * @returns {void}
 */
function createResetButton(fieldId) {
  var resetButtonLi = document.createElement('li');
  resetButtonLi.innerHTML = '<a href="#" class="reset-button label-radio item-content" data-field-id="' + fieldId + '"></a>';
  // Вставляем элемент в список после #new-record
  var newRecordLi = document.getElementById('new-record');
  if (newRecordLi) newRecordLi.parentNode.insertBefore(resetButtonLi, newRecordLi.nextSibling);
}

/**
 * Обработчик кнопки сброса значения поля
 * @param {string} lineId     id записи
 * @param {string} fieldId    id сбрасываемого поля
 * @returns {void}
 */
function attachResetHandler(lineId, fieldId) {
  var resetButton = document.querySelector('.reset-button[data-field-id="' + fieldId + '"]');
  if (resetButton) {
    resetButton.addEventListener('click', function(e) {
      e.preventDefault();

      document.querySelectorAll(`[name="value[${lineId}][${fieldId}]"]`).forEach((input) => {
        // Сбрасываем значение input
        input.value = '0';
        let parent = input.parentNode;
        // Внутри родителя находим span и сбрасываем его содержимое
        let span = parent.querySelector('span.link_field_pretend_to_be_input');
        if (span) {
          span.textContent = '';
          span.removeAttribute('field_val');
          myApp.closeModal();
        }
      });
   });
 }
}
