var IDTable = {};
var BSTables = new Map();

function getIDtable(params) {
    if (!IDTable[params[0]]) {
        IDTable[params[0]] = {};
        $.ajax({
            url: "ajax.php",
            type: "POST",
            data: {
                command: params[1],
                module: 'iub24',
            },
            success: function (result) {
                IDTable[params[0]] = result;
            }
        }).then(function () {
            params.success(IDTable[params[0]]);
        });
    } else {
        return params.success(IDTable[params[0]]);
    }
}

function LinesrowStyle(row, index) {
    let css = "";
    let classes = "";
    if (row.prefix.length && !row.used)
            css = {"background-color": "#faf2cc"};
        return {
            classes: classes,
            css: css,
        };
}

function UsedCell(value) {
    return (value) ? value.split('<br>').filter(a => a.length)[0] : '';
}

function LinescellStyle(value, row, index, field) {
    let css = "";
    let classes = "";
    if (value.length && !row.used)
        css = {"background-color": "#faf2cc", "color" : "#8A6D39", "font-weight": "bold"};
    return {
        classes: classes,
        css: css,
    };
}
function updateSelects(element){
    let def = new Option('== choose one ==', '');
    $(element).html(def);
    $.each(IDTable.exceptions_grid, function (i, item){
        let o = new Option(item.description, item.id);
        $(element).append(o);
    });
}
function updateTaskSelects(element){
    let def = new Option('== choose one ==', '');
    $(element).html(def);
    $.each(IDTable.tasks_table, function (i, item){
        let o = new Option(item.task_name, item.id);
        $(element).append(o);
    });
}

function translate(help){
    $.each(help,(function (src,dest) {
        $(dest).html($('div[id="'+ src + '"]').attr('value'));
    }));
}

$(document).ready(function() {
    var path = window.location.pathname.toString().split('/');
    path[path.length - 1] = 'ajax.php';
    if (typeof(window.location.origin) == 'undefined') {
        window.location.origin = window.location.protocol + '//' + window.location.host;
    }
    window.ajaxurl = window.location.origin + path.join('/');
    window.modulename = window.location.search.split(/\?|&/)[1].split('=')[1];
    window.wcode = null;
    var DashBoard ={
      panels: {
          RegistrationDataPanel:{
              self : '#RegistrationDataPanel',
              footer : '#RegistrationDataPanel .panel-footer',
              licenseGroup : '#license_group',
              floatBarsG : '#license_group #floatBarsG',
              err404:'#error_license_404',
              client_server: '#client_server_panel',
              ext_address: '#ext_address_panel',
          } ,
          HandlersPanel: {
              self: '#HandlersPanel',
              body: '#HandlersPanel > div.panel-body',
              table: '#HandlersPanel > div.panel-body .bootstrap-table'
          },
          AdvancedPanel: '#AdvancedPanel',
          TasksPanel: '#TasksPanel',
          ExceptionsPanel: 'ExceptionsPanel',
          OutboundRoutesPanel: {
              fields:{
                  statusEnable: '#edit_outbound_modal #record_enabled_update',
                  statusAssessment: '#edit_outbound_modal #record_assessment_update',
              }},
      },
    };
    var s,
        ModuleIUB24 = {
            ajax: {
                url: "ajax.php",
                type: "POST",
                data: {
                    module: window.modulename,
                }
            },
            settings: {
                protocol: '.protocol',
                registerWindow: '#registrationData',
                accessCode: '#modal_access_code',
                buttons: {
                    submit: '#regDataSubmit',
                    register: '#registerModule',
                }
            },
            fields:{
                client_server: '#client_server',
                ext_address: '#ext_address',
                ext_address_port: '#ext_address_port'
            },
            helpPopover: 'a[target="_blank"]',
            modals: {
                inbound: {
                    title: '#InboundDestinations .panel-title',
                    notInRoute: '.notInRoute',
                },
                outbound: {
                    title: '#edit_outbound_modal .panel-title',
                },
                customContexts : {
                    self : '#modal_custom_contexts',
                    table : '#modal_custom_contexts #custom_context_table',
                    tableEmpty : '#modal_custom_contexts tr.no-records-found',
                    checkbox : '#modal_custom_contexts #check_cc'
                },
                RegistrationData:{
                    help:{
                        clientServerHelp: '#registrationData span[id="client_server-help"]',
                        extAddressHelp: '#registrationData span[id="ext_address-help"]',
                        statusPayModalHelp: '#registrationData span[id="status_pay_b24_modal-help"]',
                        activeBeforeModalHelp: '#registrationData span[id="active_before_modal-help"]',
                        extensionsCountModalHelp: '#registrationData span[id="extensions_count_modal-help"]'
                    }
                }
            },
            /**
             * Инициализация модуля
             */
            init: function() {
                s = this;

                this.__checkActives();
//JS_1
                this.checkAviablesSites([
                    'oauth.bitrix1.info',
                    'license.informunity.ru'
                ]);
//END_JS_1
                translate(this.modals.RegistrationData.help);
                this.bindUIActions();

            },

            /**
             * События работы модуля
             */
            bindUIActions: function() {
                $(document).on('change', '.iub24_destdropdown' ,function () {
                        let tableID = $(this).parent().attr('class');
                        if ($('[class="' + tableID + '"] option[selected]').val() == "Error") {
                            $(this).css("background-color", "red");
                        } else {
                            $(this).css("background-color", "");
                        }
                });
                $(document).on( "fpbx_reload",function(event,data){
                    if(data.complete) {
                        document.location.reload();
                    }
                });

                $('body').on('show.bs.modal', '.modal_table',function (){
                    let table = $('[id="' + this.id + '"] table.table');
                    table.bootstrapTable('refresh');
                    let name = eval(table.attr('data-ajax-options'));
                    if(!BSTables.has(name[0])) {
                        BSTables.set(name[0],true);
                        $('[id="' + this.id + '"] .modal-dialog').addClass('width-92');
                    }
                });
                $('body').on('hide.bs.modal', '.modal_table',function (){
                    let table = $('[id="' + this.id + '"] table.table');
                    let name = eval(table.attr('data-ajax-options'));
                    $('#' + name[0]).bootstrapTable('refresh');
                    if(NeedReload){
                        toggle_reload_button("show");
                    }
                });


                $('body').on('click', '.panel',function (event) {
                    if(!s.showModal(event.target.tagName)) {
                        $($('[id="' + this.id + '"] .panel-heading').attr('data-target')).modal('show');
                    }
                });

                $('#HandlersPanel .bootstrap-table').on('click', function (event) {
                    if(!s.showModal(event.target.tagName)) {
                        $('#CallbacksModal').modal('show');
                    }
                });

                $('select[name="regPriority"]').each(function (index,element) {
                    $(element).selectize({
                        onItemAdd: function (event) {
                            let selectize = this;
                            let items = this.items.slice();
                            items.forEach(function (item) {
                                if((event==='DEFAULT' && item !== 'DEFAULT') || (event !== 'DEFAULT' && item === 'DEFAULT')){
                                    selectize.removeItem(item,true);
                                }
                            });
                            this.refreshOptions(false);
                        }
                    });
                    $(element)[0].selectize.setValue('DEFAULT',true);
                });

                var self = this;
                var delTarget;
                var delFromModal = false;
                var delRow = [];
                var NeedReload = false;
                var timeout = 0;
                var hovered = '';
                var unhover = {};
                var ajax = {url: "ajax.php",
                    type: "POST",
                    data: {
                        command: 'submit',
                        module: 'iub24',
                    }};
                $('.iub24_panel').on('mouseover',function () {
                    let parent = this;
                    if(hovered === parent.id) {
                        clearTimeout(unhover);
                        timeout = 0;
                    }
                    $('.hovered select').on('change', function () {
                        timeout = 800;
                    });
                    if(hovered.length === 0) {
                        let width = $(this).css('width');
                        $(parent).css('width', width);
                        $(parent).addClass('hovered');
                        hovered = parent.id;
                    }
                });
                $('.iub24_panel').on('mouseleave',function () {
                    var obj = this;
                    if(hovered === this.id) {
                        unhover = setTimeout(function () {
                            $(obj).removeClass('hovered');
                            hovered = '';
                            timeout = 0;
                        },timeout);
                    }
                });

                $(s.helpPopover).popover({
                    trigger: 'hover',
                    delay: {show: 0, hide: 500}
                });

                $('#client_server_401 > div >label a').popover({
                    trigger: 'hover',
                    content: $('#popper_client_server_401').attr('value'),
                    delay: {show: 0, hide: 500}
                });

                $('#client_server_405 > div >label a').popover({
                    trigger: 'hover',
                    content: $('#popper_client_server_405').attr('value'),
                    delay: {show: 0, hide: 500}
                });

                $('#ext_address_403 > div >label a').popover({
                    trigger: 'hover',
                    content: $('#popper_ext_address_403').attr('value'),
                    delay: {show: 0, hide: 500}
                });
                $('#error_license_404 > div >label a').popover({
                    trigger: 'hover',
                    content: $('#popper_ext_address_403').attr('value'),
                    delay: {show: 0, hide: 500}
                });

                $(ModuleIUB24.modals.customContexts.table).on("load-success.bs.table", function (event) {
                    if($(ModuleIUB24.modals.customContexts.table + ' tr.no-records-found').length == 0) {
                        $(ModuleIUB24.modals.customContexts.self).on('show.bs.modal', function(){
                            let myModal = $(this);
                            clearTimeout(myModal.data('hideInterval'));
                            myModal.data('hideInterval', setTimeout(function(){
                                myModal.modal('hide');
                            }, 5000));
                        });
                        $(ModuleIUB24.modals.customContexts.self).modal("show");
                        $(ModuleIUB24.modals.customContexts.checkbox).on('change',function (event) {
                            ajax.data[this.name] = (event.currentTarget.checked) ? 1 : 0;
                            $.ajax(ajax);
                            $(ModuleIUB24.modals.customContexts.self).modal("hide");
                        });
                    }

                });

                $('table[data-toggle="table"]').on("load-success.bs.table", function (event, data) {
                    s.checkPanelStatus($(event.target),data);
                });
                $('.saveOnLeave input').on('change',function () {
                    ajax.data[this.name] = this.value;
                });
                $('.saveOnLeave select').on('change',function (event) {
                    var name = this.name;
                    var val = this.value;
                    if(name === 'log-files'){
                    }else {
                        ajax.data[name] = val;
                    }
                        name = '';
                        val = '';
                });
                $('.saveOnLeave').on('mouseleave',function () {
                    if(Object.keys(ajax.data).length > 2) {
                        $.ajax(ajax).then(function () {
                            ajax.data = {command: 'submit', module: 'iub24'};
                            toggle_reload_button("show");
                        })
                    };
                });

                $(document).on('click', 'div.selectize-input div.item', function(e) {
                    var select = $(this).parent().parent().parent().find('select').selectize();
                    var selectedValue = event.target.dataset.value;
                    select[0].selectize.removeItem(selectedValue);
                    select[0].selectize.refreshItems();
                    select[0].selectize.refreshOptions();
                });

                $('#modal_delete').on('show.bs.modal', function(event) {
                    delTarget = undefined;
                    delFromModal = false;
                    delTarget = event.relatedTarget.dataset;
                    delFromModal = $(event.relatedTarget).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().hasClass('modal');
                    delRow = [$(event.relatedTarget).parent().parent().parent().parent().attr('id') , $(event.relatedTarget).parent().parent().attr('data-index')];
                    $('[id="' + this.id + '"] .panel-title').html($('#modal_action_delete').attr('value') + ' ' + $('#modal_action_'+ event.relatedTarget.dataset.name).attr('value'));
                });
                $('#modal_delete_button_ok').on('click',function () {

                    if(delTarget && delTarget.id) {
                        s.ajax.data.id = delTarget.id;
                         switch (delTarget.name) {
                             case 'did':
                                 s.ajax.data.command = 'removeDid';
                                 break;
                             case 'route':
                                 s.ajax.data.command = 'removeOutboundRoute';
                                 break;
                             case 'line':
                                 s.ajax.data.command = 'removeLine';
                                 s.ajax.data.number = delTarget.lineNumber;
                                 break;
                             case 'task':
                                 s.ajax.data.command = 'removeTask';
                                 break;
                             case 'exception':
                                 s.ajax.data.command = 'removeException';
                                 break;
                         }
                        $.ajax({
                            url: s.ajax.url,
                            type: s.ajax.type,
                            data: s.ajax.data,
                            success: function () {
                                fpbxToast('Complete', 'Removing', 'success');
                                if(delRow) {
                                    s.deleteTableRow(delRow,delFromModal);
                                    delRow=[];
                                    updateSelects('#add_inbound_modal  select#exceptions');
                                    updateSelects('#edit_outbound_modal  select#exceptions');
                                }
                            }
                        });
                    }
                });
//JS_2
                $(s.settings.buttons.register).on('click',function () {
                    if(s.__checkInvalid()){
                            s.setCridentials()
                                .then(function (data) {
                            $('#modal_register_ok').attr('data-appID', data['app']);
                            s.__submitData();
                        }).then(function () {
                            $(s.settings.accessCode).modal('show');
                        }).then(function () {
                            s.openRegisterWindow();
                        })
                    }
                });

                $('#modal_register_ok').on('click',function () {
                    s.register();
                });
//END_JS_2
                $(s.settings.buttons.submit).on('click',function () {
                    s.submitUpdate();
                });
            },
            deleteTableRow: function(delRow,delFromModal){
                let panelTable = eval($('[id="' + delRow[0] + '"][data-ajax="getIDtable"]').attr('data-ajax-options'));
                if (panelTable[0] === "outbound_routes_table"){
                    s.cleanOutboundTableRow(delRow,delFromModal);
                    return;
                }
                IDTable[panelTable[0]].splice(delRow[1], 1);
                if (panelTable[0] === "Lines_panel_table"){
                    let index = $('#CallbacksTable tr[data-uniqueid="'+ $('[id="' + delRow[0] +'"] tr[data-index="' + delRow[1] + '"] .iu_lines_delete').attr('data-line-number')  +'"]').attr('data-index');
                    IDTable.CallbacksTable.splice(index, 1);
                    $('#CallbacksTable').bootstrapTable('refresh');
                }
                $('[id="' + delRow[0] +'"]').bootstrapTable('refresh');
                if(delFromModal) {
                    $('[id="' + panelTable[0] + '"]').bootstrapTable('refresh');
                    NeedReload = true;
                }else{
                    toggle_reload_button("show");
                }
            },
            cleanOutboundTableRow: function(cleanRow,delFromModal){
                let panelTable = eval($('[id="' + cleanRow[0] + '"][data-ajax="getIDtable"]').attr('data-ajax-options'));
                IDTable[panelTable[0]][cleanRow[1]].status = null;
                $('[id="outbound_table"]').bootstrapTable('refresh');
                if(delFromModal) {
                    $('[id="' + cleanRow[0] + '"]').bootstrapTable('refresh');
                    NeedReload = true;
                }else{
                    toggle_reload_button("show");
                }
            },
            myTimeout: function(){
                // console.log(timeout);
                while(timeout >= 0){
                    console.log(timeout);
                    if(timeout < 0 ){
                        timeout = 0;
                        return false;
                    }
                    if(timeout === 0){
                        return true;
                    }
                    setTimeout(timeout--, 1);
                }
                return true;
            },
            showModal: function(name){
              return  (name === 'INPUT' || name === 'I' || name === 'A' || name === 'SELECT' || name === 'BUTTON' || name === 'SPAN')
            },
            checkPanelStatus: function(table,data){
                let tableID = table.attr('id');
                let panel = table.parent().parent().parent().parent().parent();
                let panelId = $(panel).attr('id');
                let panelColorClass = 'panel-info';
                if(data.message || data.length === 0){
                    panelColorClass = 'panel-default';
                }else {
                    switch (tableID) {
                        case 'inbound_destinations_table':
                            if(data.length) {
                                $(s.modals.inbound.notInRoute).parent('a').popover({
                                    trigger: 'hover',
                                    delay: {show: 0, hide: 100},
                                    placement: 'right',
                                    html: 'true',
                                    content: $('#not_used_destination').html()
                                });
                                let n = 0;
                                data.forEach(function (element) {
                                    if (element.notinroute) {
                                        n++;
                                    }
                                });
                                if (n == data.length) {
                                    panel.removeClass('panel-info');
                                    panel.addClass('panel-warning');
                                    if(!$( '[id="'+panelId+'"]'+ ' .panel-title .fa-info').length) {
                                        $('[id="' + panelId + '"]' + ' .panel-title').append($('#not_used').html());
                                    }
                                }
                                if(didID !== undefined){
                                    $('.iu_edit[data-id="'+ didID +'"]').trigger('click');
                                }
                            }
                            break;
                        case 'outbound_routes_table':
                            let empty = true;
                            data.forEach(function (element) {
                                if(element.status && element.status !== 'Intracompany') {
                                    empty = false;
                                }
                            });
                            if(empty) {
                                panel.removeClass('panel-info');
                                panel.addClass('panel-warning');
                                if(!$( '[id="'+panelId+'"]'+ ' .panel-title .fa-info').length) {
                                    $('[id="' + panelId + '"]' + ' .panel-title').append($('#not_configured').html());
                                }
                            }
                            break;
                        case 'Lines_panel_table':
                            $.each(data,(function(key,element) {
                                if(element.prefix.length && !element.used.length) {
                                    used = $('#Lines_panel_table tr[data-index="' + key + '"] td:nth-child(4)');
                                    used.append($('#not_used_Line').attr('value'));
                                }
                            }));
                            break;
                    }

                }
                switch (panelColorClass) {
                    case 'panel-info':
                        panel.removeClass('panel-info');
                        panel.addClass(panelColorClass);
                        panel.removeClass('iub24_panel-disabled');
                        panel.find('input[placeholder="Search"]').prop('disabled',false);
                        break;
                    case 'panel-default':
                    case 'panel-danger':
                        panel.removeClass('panel-info');
                        panel.addClass(panelColorClass);
                        panel.addClass('iub24_panel-disabled');
                        panel.find('input[placeholder="Search"]').prop('disabled',true);
                        break;
                }
            },
//JS_3
            setCridentials: function(){
               return $.ajax({
                    url: "ajax.php",
                    type: "POST",
                    data: {
                        command: 'setCredentials',
                        module: window.modulename,
                        client_server: $('select[name="portal_protocol"]').val().trim() + "://" + $('input[name="client_server"]').val().trim() + ':' + $('input[name="client_server_port"]').val().trim(),
                        ext_address: $('select[name="fpbx_protocol"]').val().trim() + "://" + $('input[name="ext_address"]').val().trim() + ':' + $('input[name="ext_address_port"]').val().trim(),
                    },
                }
            )},
            /**
             * Получаем заполненный урл портала b24
             */
            getClientServerWhenRegister: function(){
                return $('select[name="portal_protocol"]').val().trim() + "://" + $('input[name="client_server"]').val().trim() + ':' + $('input[name="client_server_port"]').val().trim();
            },
            /**
             * проверяем на доступность сайты
             * для дальнейшей работы
             * @param {*} urls
             */
            checkAviablesSites: function(urls) {
                var promise = $.ajax({
                    url: "ajax.php",
                    type: "POST",
                    data: {
                        command: 'checkAviableSite',
                        module: window.modulename,
                        url: urls[0]
                    }
                });
                promise.then(function(data) {

                    if(data.message != 'unknown') {
                        $('#page_body .container-fluid').before(data.message);
                    }
                    return $.ajax({
                        url: "ajax.php",
                        type: "POST",
                        data: {
                            command: 'checkAviableSite',
                            module: window.modulename,
                            url: urls[1]
                        }
                    });
                }).then(function(data){
                    if(data.message != 'unknown') {
                        $('#page_body .container-fluid').before(data.message);
                    }
                },function(err){
                    console.error(err);
                });

            },
//END_JS_3
            __checkActives: function() {
                var se = this;
//JS_4
                    //проверим доступность портала b24
                    let checkAviableSite = $.ajax({
                        url: "ajax.php",
                        type: "POST",
                        data: {
                            command: 'checkAviableSite',
                            module: window.modulename,
                            url: this.getClientServerWhenRegister()
                        }
                    });

                    checkAviableSite.then(function(data) {
                        if(data.error) {
                            data.error.forEach(function (element) {
                                BitrixAddressWarn($('#div_client_server'));
                            });
                            if (data.message != 'unknown') {
                                $('#page_body .container-fluid').before(data.message);
                            }
                        }else{
                            if(!$('#client_server_401').hasClass('hidden')) {
                                BitrixAddressWarn($('#div_client_server'), true);
                            }
                        }
                        let isEventRegister = $.ajax({
                            url: "ajax.php",
                            type: "POST",
                            data: {
                                command: 'isEventRegister',
                                module: window.modulename,
                            }});

                        let getModuleInfo = $.ajax({
                            url: "ajax.php",
                            type: "POST",
                            data: {
                                command: 'getModuleInfo',
                                module: window.modulename,
                                client_server: $('select[name="portal_protocol"]').val().trim() + "://" + $('input[name="client_server"]').val().trim() + ':' + $('input[name="client_server_port"]').val().trim(),
                                ext_address: $('select[name="fpbx_protocol"]').val().trim() + "://" + $('input[name="ext_address"]').val().trim() + ':' + $('input[name="ext_address_port"]').val().trim(),

                            }
                        });

                        isEventRegister.then(function(data){
                            var events = JSON.parse(data.message);
                            $('[data-placement="isRegisterCall"]').html(events['isRegisterCall']);
                            $('[data-placement="isRegisterCallback"]').html(events['isRegisterCallback']);
                        }, function(err){
                            console.error(err);
                        });

                        getModuleInfo.then(function(data){
                            if(data.error) {
                                // console.log(data);
                                Object.keys(data.error).forEach(function (element) {
                                    switch (element) {
                                        case '403':
                                            FreePBXAddressInvalid($('#div_ext_address'));
                                            break;
                                        case '404':
                                            errorLicense();
                                            break;
                                        case '405':
                                            BitrixAddressInvalid();
                                            break;
                                        default:
                                            break;
                                    }

                                });
                            }else{
                                if(!$('#ext_address_403').hasClass('hidden')) {
                                    FreePBXAddressInvalid($('#div_ext_address'), true);
                                }
                                if(!$('#client_server_405').hasClass('hidden')){
                                    BitrixAddressInvalid(true);
                                }
                            }
                            $('#extensions_count').text(data['users']);
                            $('#extensions_count_modal').text(data['users']);
                            $('#status_pay_b24').text(data['description']);
                            $('#status_pay_b24_modal').text(data['description']);
                            $('#active_before').text(data['workdate']);
                            $('#active_before_modal').text(data['workdate']);

                        }, function(err){
                            console.error(err);
                        });

//END_JS_4
                        let getUserOnPortal = $.ajax({
                            url: "ajax.php",
                            type: "POST",
                            data: {
                                command: 'getUserOnPortal',
                                module: window.modulename,
                            }
                        });

                        let getSourcesList =  $.ajax({
                            url: "ajax.php",
                            type: "POST",
                            data: {
                                command: 'getSourcesList',
                                module: window.modulename,
                            }
                        });

                        getUserOnPortal.then(function(data){
                            var responce = JSON.parse(data.message);
                            se.__renderPortalUsers(responce,'selectSingle');
                            se.__renderPortalUsers(responce,'selectMulti','multiple');
                        }, function(err){
                            console.error(err);
                        });

                        getSourcesList.then(function(data) {
                            var sources = data.message;
                            $('[data-placement="source-options"] #floatBarsG').remove();
                            $('[data-placement="source-options"]').html(sources).show();
                            $('[data-placement="source-options"]').each(function () {
                                $select = $(this).children().selectize();
                                if($(this).attr('data-value') !== undefined){
                                    $select[0].selectize.setValue($(this).attr('data-value'));
                                }
                            });
                        }, function(err){
                            console.error(err);
                        });

                    },
//JS_5
                        function(err){
                        console.error(err);
                    });

                // }
            },

            /**
             * Регистрация
             */
            register: function() {
                var self = this;

                if ($('#access_code').val()) {
                    fpbxToast($('#processing').attr('value'), '', 'info');
                    s.__newRegister();
                    window.wcode.close();
                }
            },

            openRegisterWindow: function() {
                var url = $('#registrationData select[name="portal_protocol"]').val().trim() + '://' + $('#registrationData input[name="client_server"]').val().trim() + ':' + $('#registrationData input[name="client_server_port"]').val().trim() + '/oauth/authorize/?client_id=' + $('#modal_register_ok').attr('data-appid').trim();
                let top = screen.height - 700;
                window.wcode = window.open(url, 'Auth in Bitrix', "menubar=no, top=" + top + ", toolbar=no ,width=600, height=700");
                if (window.wcode) {
                    //Browser has allowed it to be opened
                } else {
                    //Browser has blocked it
                    alert('Please allow pop-up windows for this web-site');
                }
            },

            submitUpdate: function() {
                if (s.__checkInvalid()) {
                    fpbxToast($('#processing').attr('value'), '', 'info');
                    s.__submitData();
                }
            },

            __submitData: function() {

                $.ajax({
                    url: "ajax.php",
                    type: "POST",
                    data: {
                        command: 'submit',
                        module: window.modulename,
                        access_code: $('#access_code').val(),
                        client_server: $('select[name="portal_protocol"]').val().trim() + "://" + $('input[name="client_server"]').val().trim() + ':' + $('input[name="client_server_port"]').val().trim(),
                        ext_address: $('select[name="fpbx_protocol"]').val().trim() + "://" + $('input[name="ext_address"]').val().trim() + ':' + $('input[name="ext_address_port"]').val().trim(),
                    },
                    success: function (data) {

                        $(DashBoard.panels.RegistrationDataPanel.client_server).val($('select[name="portal_protocol"]').val().trim() + "://" + $('input[name="client_server"]').val().trim() + ':' + $('input[name="client_server_port"]').val().trim());
                        $(DashBoard.panels.RegistrationDataPanel.ext_address).val($('select[name="fpbx_protocol"]').val().trim() + "://" + $('input[name="ext_address"]').val().trim() + ':' + $('input[name="ext_address_port"]').val().trim());
                        $(s.settings.registerWindow).modal('hide');
                        s.__checkActives();

                        // document.location.reload();
                    }
                });
            },

            __newRegister: function() {
                $.ajax({
                    url: "ajax.php",
                    type: "POST",
                    data: {
                        command: 'register',
                        module: window.modulename,
                        access_code: $("#access_code").val()
                    },
                    success: function(data) {
                        // console.log(data);
                        if (data['message'].length && data['message'] != 'unknown' && data['message'] != 'n') {
                            $('#registerError label').html($('#' + data['message']).attr('value'));
                            $('#registerError').removeClass('hidden');
                            warnInvalid($(ModuleIUB24.fields.client_server));
                        } else {
                            document.location.reload();
                        }
                    },
                });

            },
//END_JS_5
            /**
             * Сопоставление протокола - порту
             * @param select указатель на текущий select, обьект dom html
             * @private
             */
            __setPort: function(select) {
                //todo прикрутить
                // console.log('setPort', $(select).val());
                var port_no = '';
                switch (($(select).val())) {
                    case 'http':
                        port_no = '80';
                        break;
                    case 'https':
                        port_no = '443';
                        break;
                    default:
                        port_no = '443';
                }
                $(select).closest('.row').find('.port').attr('value', port_no);
            },
            /**
             * Получаем destination route из селектов
             * в настройках
             * @returns {*}
             */
            getDestination: function() {
                var destination = $('select[name=dest_inbound_b24]').val();

                return destination;
            },
            /**
             * Получаем destination route из селектов
             * в настройках
             * @returns {*}
             */
            getDestinationForm: function($form) {
                var firstSelect = $form.find('select.iub24_destdropdown').val();
                var destination = $form.find('select[name="'+firstSelect+'0"]').val();
                return destination;
            },
            /**
             * Проверка на обязательные поля формы
             * @returns {boolean}
             * @private
             */
            __checkInvalid: function() {
                if(isPrivateIP($(ModuleIUB24.fields.client_server).val())){
                    warnInvalid($(ModuleIUB24.fields.client_server));
                    return false
                }
                if(domainAdressValid($(ModuleIUB24.fields.client_server).val())) {
                    if(ipAdressValid($(ModuleIUB24.fields.client_server).val())){
                        warnInvalid($(ModuleIUB24.fields.client_server));
                        return false
                    }
                }

                if(isPrivateIP($(ModuleIUB24.fields.ext_address).val())){
                    warnInvalid($(ModuleIUB24.fields.ext_address));
                    return false
                }
                if(domainAdressValid($(ModuleIUB24.fields.ext_address).val())) {
                    if(ipAdressValid($(ModuleIUB24.fields.ext_address).val())){
                        warnInvalid($(ModuleIUB24.fields.ext_address));
                        return false
                    }
                }

                if($(ModuleIUB24.fields.ext_address_port).val() < 0 || $(ModuleIUB24.fields.ext_address_port).val() > 65535){
                    warnInvalid($(ModuleIUB24.fields.ext_address_port));
                    return false
                }
                return true;
            },
            /**
             * Рисуем список пользователей полученных из портала б24
             * @param { } responce
             */
            __renderPortalUsers: function(responce,selectClass,type = '') {
                let $selcectClass = '.' +selectClass;
                if(typeof responce.users != "undefined" && responce.users.length > 0) {
                    // let $template='<p class"control">';
                    let $template='<select '+ type +'>';
                    for (let i in responce.users) {
                        if(responce.users[i]['LAST_NAME'] != "" || responce.users[i]['NAME'] != "") {
                            $template += '<option value='+responce.users[i]['ID']+'>'+responce.users[i]['LAST_NAME']+' '+responce.users[i]['NAME']+'</option>';
                        }
                    };
                    $template += '</select>';
                    // $template += '</p>';
                    $($selcectClass).each(function () {
                        $(this).html($template);
                        $select = $(this).children('select').selectize();
                        if($(this).attr('data-value') != undefined && $(this).attr('data-value').length > 0){
                            $select[0].selectize.setValue($(this).attr('data-value').split(','));
                        }
                    });
                } else {
                    // $('#' + divToPut).html(responce.error);
                }
            },

        };

    ModuleIUB24.init();
//JS_6
    function BitrixAddressWarn(theField,type = false) {
        if (theField) {
            let field = (theField instanceof jQuery) ? theField : $(theField);
            let fieldID = field.attr('id');
            if(type){
                field.focus();
                field.removeClass("has-error");
                $('[id="' + fieldID + '"] .fa-exclamation-triangle').addClass('hidden');
                $('[id="' + fieldID + '"] [id="client_server_401"]').addClass('hidden');

                $(DashBoard.panels.RegistrationDataPanel.self).removeClass('panel-danger');
                $(DashBoard.panels.RegistrationDataPanel.self).addClass('panel-success');
                $(DashBoard.panels.OutboundRoutesPanel.fields.statusEnable).prop('disabled', false);
                $(DashBoard.panels.OutboundRoutesPanel.fields.statusAssessment).prop('disabled', false);
            }else {
                field.focus();
                field.addClass("has-error");
                $('[id="' + fieldID + '"] .fa-exclamation-triangle').removeClass('hidden');
                $('[id="' + fieldID + '"] [id="client_server_401"]').removeClass('hidden');

                $(DashBoard.panels.RegistrationDataPanel.self).removeClass('panel-success');
                $(DashBoard.panels.RegistrationDataPanel.self).addClass('panel-danger');
                $(DashBoard.panels.OutboundRoutesPanel.fields.statusEnable).prop('disabled', true);
                $(DashBoard.panels.OutboundRoutesPanel.fields.statusAssessment).prop('disabled', true);
            }
        }
    }
    function BitrixAddressInvalid(type = false) {
        if(type){
            $('#div_client_server').removeClass("has-error");
            $('#client_server_405').addClass('hidden');
            $(DashBoard.panels.RegistrationDataPanel.self).addClass('panel-success');
            $(DashBoard.panels.RegistrationDataPanel.self).removeClass('panel-warning');
        }else {
            $('#div_client_server').addClass("has-error");
            $('#client_server_405.hidden').removeClass('hidden');
            $(DashBoard.panels.RegistrationDataPanel.self).removeClass('panel-success');
            $(DashBoard.panels.RegistrationDataPanel.self).addClass('panel-warning');
        }
    }
    function FreePBXAddressInvalid(theField,type = false) {
        if (theField) {
            let field = (theField instanceof jQuery) ? theField : $(theField);
            let fieldID = field.attr('id');
            if(type){
                field.removeClass("has-error");
                $('#ext_address_403').addClass('hidden');

                $(DashBoard.panels.HandlersPanel.self + ' .panel-footer').addClass('hidden');
                $('[id="' +fieldID+ '"] .fa-exclamation-triangle').addClass('hidden');

                $(DashBoard.panels.RegistrationDataPanel.self).addClass('panel-success');
                $(DashBoard.panels.RegistrationDataPanel.self).removeClass('panel-warning');

                $(DashBoard.panels.HandlersPanel.self).addClass('panel-success');
                $(DashBoard.panels.HandlersPanel.self).removeClass('panel-warning');

                $(DashBoard.panels.HandlersPanel.self + ' .panel-body').removeClass('disabledPanel');
                $(DashBoard.panels.HandlersPanel.table).removeClass('hidden');
            }else {
                field.focus();
                field.addClass("has-error");
                $('#ext_address_403.hidden').removeClass('hidden');

                $(DashBoard.panels.HandlersPanel.self + ' .panel-footer').removeClass('hidden');
                $('[id="' +fieldID+ '"] .fa-exclamation-triangle').removeClass('hidden');

                $(DashBoard.panels.RegistrationDataPanel.self).removeClass('panel-success');
                $(DashBoard.panels.RegistrationDataPanel.self).addClass('panel-warning');

                $(DashBoard.panels.HandlersPanel.self).removeClass('panel-success');
                $(DashBoard.panels.HandlersPanel.self).addClass('panel-warning');

                $(DashBoard.panels.HandlersPanel.self + ' .panel-body').addClass('disabledPanel');
                $(DashBoard.panels.HandlersPanel.table).addClass('hidden');
            }

        }
        return false;
    }
    function errorLicense() {
       let theField = $('#license_group');
        var field = (theField instanceof jQuery) ? theField : $(theField);

        field.focus();
        field.addClass("has-error");
        $(DashBoard.panels.RegistrationDataPanel.floatBarsG).addClass('hidden');
        // $(DashBoard.panels.RegistrationDataPanel.err404 + '.hidden').removeClass('hidden');
        $(DashBoard.panels.RegistrationDataPanel.footer + '.hidden').removeClass('hidden');
        // field.children().children().children().children().children().children('.hidden').removeClass('hidden');
        // field.children('#error_license_404.hidden').removeClass('hidden');
        $(DashBoard.panels.RegistrationDataPanel.self).removeClass('panel-success');
        $(DashBoard.panels.RegistrationDataPanel.self).addClass('panel-danger');

    }

    function ipAdressValid(ipaddress) {
        if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) {
            return (false);
        }
        return (true);
    }

    function domainAdressValid(domain) {
        if (/^(www\.)?[a-z0-9\-\.]{3,}\.[a-z]{2,}$/.test(domain)   ){
            return (false);
        }
        return (true);
    }
    
    function isPrivateIP(ip) {
       var parts = ip.split('.');
       return parts[0] === '10' || 
          (parts[0] === '172' && (parseInt(parts[1], 10) >= 16 && parseInt(parts[1], 10) <= 31)) || 
          (parts[0] === '192' && parts[1] === '168');
    }
//END_JS_6
});