$(document).ready(function() {
    let 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];
    var s,
        handlers = {
            ajax: {
                url: "ajax.php",
                type: "POST",
                data: {
                    module: window.modulename,
                },
            },
            Panel: {
                self: '#HandlersPanel',
                // body: '#HandlersPanel > div.panel-body',
                table: '#HandlersPanel > div.panel-body .bootstrap-table',
                ClicToCallRegister: '#click_call_reg',
                CallbacksRegister: '#click_back_reg'
            },
            settings: {
                buttons: {
                    delete: '[data-bind="iu-event-delete"]',
                },
            },
            Modal:{
                self: '#CallbacksModal',
                dialog: '#CallbacksModal > div.modal-dialog',
                body: '#CallbacksModal div.modal-body',
                callback: '#CallbacksModal #CallbacksTableModal',
                iub24_destdropdown: '#CallbacksModal .iub24_destdropdown',
                iub24_destdropdown2: '#CallbacksModal .iub24_destdropdown2',
                ccModal: '#modal_ONEXTERNALCALLSTART',
                cbModal: '#modal_ONEXTERNALCALLBACKSTART',
            },
            callback: '#CallbacksTable',
            iub24_destdropdown: '#HandlersPanel .iub24_destdropdown',
            iub24_destdropdown2: '#HandlersPanel .iub24_destdropdown2',

            init: function () {
                s = this;
                this.bindUIActions();
            },
            /**
             * обработчики кнопок
             */
            bindUIActions: function () {
                $(document.body).on('click', handlers.Panel.ClicToCallRegister, function(){
                    handlers.ajax.data.command = 'EventBind';
                    handlers.ajax.data.event = 'ONEXTERNALCALLSTART';
                    $.ajax(handlers.ajax).then(function () {
                        $('#event-list-callstart').bootstrapTable('refresh');
                        $(handlers.Modal.ccModal).modal("show");
                    });
                });
                $(document.body).on('click', handlers.Panel.CallbacksRegister, function(){
                    handlers.ajax.data.command = 'EventBind';
                    handlers.ajax.data.event = 'ONEXTERNALCALLBACKSTART';
                    $.ajax(handlers.ajax).then(function () {
                        $('#event-list-callbackstart').bootstrapTable('refresh');
                        $(handlers.Modal.cbModal).modal("show");
                    });
                });
                $(document.body).on('click', s.settings.buttons.delete, function(){
                    var btn = this;
                    var eventCode = $(this).attr('data-code');
                    var hndl = $(this).attr('data-handler');
                    var removeEvent = s.removeEvent(eventCode, hndl);
                    removeEvent.then(function(r){
                        $(btn).closest('tr').remove();
                    });
                });

                $('body').on('change',handlers.iub24_destdropdown,function (event) {
                    handlers.setDropdown(this);
                });

                $('body').on('change',handlers.iub24_destdropdown2,function (event) {
                    handlers.setDropdown2(this);
                    handlers.update($(event.currentTarget),event.currentTarget.dataset.id);
                });

                $('body').on('change',handlers.Modal.iub24_destdropdown,function (event) {
                    handlers.setDropdown(this);
                });

                $('body').on('change',handlers.Modal.iub24_destdropdown2,function (event) {
                    handlers.setDropdown2(this);
                    handlers.update($(event.currentTarget),event.currentTarget.dataset.id);
                });

            },
            setDropdown: function(element){
                let tableID = $(element).parent().parent().parent().parent().attr('id');
                $('[id="' + tableID + '"] [id="' + element.id + '"] option[selected]').attr('selected',false);
                $('[id="' + tableID + '"] [id="' + element.id + '"] option[value="' + $(element).val() + '"]').attr('selected',true);
                let id = $(element).attr('data-id');
                $('[id="' + tableID + '"] .iub24_destdropdown2[data-id="' + id + '"]').addClass('hidden');
                let iub24_destdropdown2 = $('[id="' + tableID + '"] [id="' + $(element).val() + id +'"]');
                iub24_destdropdown2.removeClass('hidden');
                handlers.setDropdown2(iub24_destdropdown2);
                handlers.update(iub24_destdropdown2, id);

            },
            setDropdown2: function(element){

                let tableID = $(element).parent().parent().parent().parent().attr('id');
                let index = $(element).parent().parent().attr('data-index');
                $('[id="' + tableID + '"] [id="' + element.id + '"] option[selected]').attr('selected',false);
                $('[id="' + tableID + '"] [id="' + element.id + '"] option[value="' + $(element).val() + '"]').attr('selected',true);
                IDTable.CallbacksTable[index].destination = $(element).parent().html();
            },
            /**
             * обновление callback
             */
            update: function (elem,id) {
                //todo пофиксить поповер
                let dest = (elem.val()) ? elem.val() : '' ;
                if(dest === 'popover') {
                    var urlStr = elem.data("url") + "&fw_popover=1", id = $(this).data("id");
                    popover_select_id = this.id;
                    popover_box_class = elem.data("class");
                    popover_box_mod = elem.data("mod");
                    popover_box = $("<div id=\"popover-box-id\" data-id=\"" + id + "\"></div>")
                        .html("<iframe data-popover-class=\"" + popover_box_class + "\" id=\"popover-frame\" frameBorder=\"0\" src=\"" + urlStr + "\" width=\"100%\" height=\"95%\"></iframe>")
                        .dialog({
                            title: "Add",
                            resizable: false,
                            modal: true,
                            width: window.innerWidth - (window.innerWidth * '.10'),
                            height: window.innerHeight - (window.innerHeight * '.10'),
                            create: function() {
                                $("body").scrollTop(0).css({ overflow: "hidden" });
                            },
                            close: function(e) {
                                if(!runningPopOverActions) {
                                    //cheating by puttin a data-id on the modal box
                                    var id = $(this).data("id");
                                    //dropdown 1
                                    var par = $('[id="goto' + id + '"]').data("last");
                                    //reset the original option to the first in the list *if* it wasn't
                                    //previously selected. This is so we dont get random 'white' (empty)
                                    //options selected when coming back from a canceled popover
                                    var name = $('[id="goto' + id + '"]').val();
                                    if(par !== name) {
                                        $('[id="' + name + id + '"]')[0].selectedIndex = 0;
                                    }
                                    $('[id="goto' + id + '"]').val(par).change();
                                    if (par !== "") { //Get dropdown2
                                        //todo concat undefined
                                        var par_id = par.concat(id);
                                        $('[id="' + par_id + '"]').val($('[id="' + par_id + '"]').data("last")).change();
                                    }
                                    $("#popover-frame").contents().find("body").remove();
                                    $("#popover-box-id").html("");
                                    $("body").css({ overflow: "inherit" });
                                }
                                $(e.target).dialog("destroy").remove();
                            },
                            buttons: [
                                {
                                    text: fpbx.msg.framework.save,
                                    click: function() {
                                        pform = $("#popover-frame").contents().find(".popover-form").first();
                                        if (pform.length === 0) {
                                            pform = $("#popover-frame").contents().find("form").first();
                                        }
                                        pform.submit();
                                    }
                                }, {
                                    text: fpbx.msg.framework.cancel,
                                    click: function() {
                                        $(this).dialog("close");
                                    }
                                }
                            ]
                        });
                }else{
                    handlers.ajax.data.command = 'updateCallbacks';
                    handlers.ajax.data.line = id;
                    handlers.ajax.data.destination = dest;
                    $.ajax(handlers.ajax);
                }
            },
            removeEvent: function(event, handler) {
            var removed = $.ajax({
                url: "ajax.php",
                type: "POST",
                data: {
                    command: 'Event',
                    module: window.modulename,
                    event: event,
                    handler: handler,
                    method: 'event.unbind'
                }
            });
            return removed;
            },
            /**
             * Получаем destination route из селектов
             * в настройках
             * @returns {*}
             */
        };
            handlers.init();

});