$(document).ready(function() {
    var outbound,
        OutboundRoutesTab = {
            ajax: {
                url: "ajax.php",
                type: "POST",
                data: {
                    command: 'updateOutboundRoute',
                    module: window.modulename,
                },
            },
            OutboundRoutesPanel: {
                self:'#OutboundRoutesPanel',
                body: '#OutboundRoutesPanel > div.panel-body',
                table: '#outbound_routes_table',
                fields:{
                    statusEnable: '#edit_outbound_modal #record_enabled_update',
                    statusAssessment: '#edit_outbound_modal #record_assessment_update',
                }},
            OutboundRoutesModal: {
                self: '#OutboundRoutes',
                table: '#outbound_table_modal',
                dialog: '#OutboundRoutes > div.modal-dialog',
            },
            fields: {
                outboundID: '#outboundID',
                description: '#edit_outbound_modal #description',
                status: '#edit_outbound_modal input[name="status_mode"]',
                greatings: '#edit_outbound_modal #greatings',
                bye: '#edit_outbound_modal #bye',
                exceptions: '#edit_outbound_modal #exceptions',
                source: '#edit_outbound_modal div[data-placement="source-options"]',
                create_lead: '#edit_outbound_modal input[name="create_lead"]',
                show_card: '#edit_outbound_modal input[name="show_card_route"]',
                modify_number: '#edit_outbound_modal #modify_number_first',
                regPriority: '#edit_outbound_modal select[name="regPriority"]',


            },
            help: {
                regPriorityHelp: '#edit_outbound_modal span[id="OutboundregPriority-help"]',
                statusModehelp: '#edit_outbound_modal span[id="status_mode-help"]',
                greatingsHelp: '#edit_outbound_modal span[id="out_greatings-help"]',
                byeHelp: '#edit_outbound_modal span[id="out_bye-help"]',
                exceptionsHelp: '#edit_outbound_modal span[id="out_exceptions-help"]',
                sourceHelp: '#edit_outbound_modal span[id="out_source_route-help"]',
                showCardHelp: '#edit_outbound_modal span[id="out_show_card-help"]',
                createLeadHelp: '#edit_outbound_modal span[id="out_create_lead-help"]',
                OutboundModifyHelp: '#edit_outbound_modal span[id="out_number_modify-help"]',
            },
            buttons: {
                modal_outbound_ok: '#modal_outbound_ok',
                showAdvancedSettings: '.showNumberModify'
            },
            modal: '#edit_outbound_modal',
            showNumberModifyInput: '#edit_outbound_modal .showNumberModifyInput',
            showAssessment: '#edit_outbound_modal .show_div',
            title: $('#edit_outbound_modal .modal-title'),

            init: function() {
                outbound = this;
                translate(this.help);
                this.bindUIActions();
            },
            bindUIActions: function() {
                $(outbound.buttons.showAdvancedSettings).on('click', function() {
                    $(outbound.showNumberModifyInput).toggle();
                });
                $(outbound.buttons.modal_outbound_ok).on('click', function () {
                    if (outbound.__checkInvalid()) {
                        outbound.update();
                        $(event.currentTarget).parent().parent().parent().parent().parent().parent().modal('hide');
                        toggle_reload_button("show");
                    }
                });
                $(outbound.modal).on('show.bs.modal', function(event) {
                    // console.log(event.relatedTarget.dataset.id);
                    var promise = outbound.detail(event.relatedTarget.dataset.id);
                    outbound.title.html($('#modal_action_route').attr('value') + ' ' + $('#modal_action_edit').attr('value'));
//todo Дописывать заголовок Outbound Route Edit
                    promise.done(function(res) {
                        (res.route_id)?$(outbound.fields.outboundID).attr('data-id', res.route_id):'';
                        (res.name)?$(outbound.fields.description).val(res.name):'';
                        (res.regPriority) ? $(outbound.fields.regPriority)[0].selectize.setValue(JSON.parse(res.regPriority),true) : '';
                        (res.create_lead)?$(outbound.fields.create_lead + '[value=' + res.create_lead + ']').prop('checked', true):'';
                        (res.show_card)?$(outbound.fields.show_card +'[value=' + res.show_card + ']').prop('checked', true):'';
                        if (res.source && $(outbound.fields.source + ' select').length > 0){
                            $(outbound.fields.source + ' select')[0].selectize.setValue(res.source);
                        } else {
                            $(outbound.fields.source).attr('data-value', res.source);
                        }
                        (res.exceptions)?$(outbound.fields.exceptions).val(res.exceptions):'';
                        (res.modify_number)? $(outbound.fields.modify_number).val(res.modify_number): $(outbound.fields.modify_number).val('${EXTEN}');
                        if (res.intracompany_route == 'YES') {
                            $(outbound.fields.status +'[value=intracompany]').prop('checked', true);
                        } else {
                            switch (res.status) {
                                case 'no':
                                    $(outbound.fields.status +'[value=no]').prop('checked', true);
                                    break;
                                case 'yes':
                                    $(outbound.fields.status +'[value=yes]').prop('checked', true);
                                    break;
                                case 'voting':
                                    $(outbound.showAssessment).trigger('change');
                                    (res.greatings) ? $(outbound.fields.greatings).val(res.greatings) : '';
                                    (res.bye) ? $(outbound.fields.bye).val(res.bye) : '';
                                    $(outbound.fields.status +'[value=voting]').prop('checked', true);
                                    break;
                                default:
                                    $(outbound.fields.status +'[value=no]').prop('checked', true);
                            }
                        }
                    });

                });


                $(outbound.fields.status).on('change',function() {
                    switch ($(this).val()) {
                        case 'voting':
                            $(outbound.showAssessment).show();
                            break;
                        default:
                            $(outbound.showAssessment).hide();
                            break;
                    }
                });

            },

            update: function() {
                outbound.ajax.data['id'] = $(outbound.fields.outboundID).attr('data-id');
                outbound.ajax.data['description'] = ($(outbound.fields.description).val()) ? $(outbound.fields.description).val(): '';
                outbound.ajax.data['status'] = ($(outbound.fields.status + ':checked').val()) ? $(outbound.fields.status + ':checked').val() : '';
                outbound.ajax.data['greatings'] = ($(outbound.fields.greatings).val()) ? $(outbound.fields.greatings).val() : '';
                outbound.ajax.data['bye'] = ($(outbound.fields.bye).val()) ? $(outbound.fields.bye).val() : '';
                outbound.ajax.data['regPriority'] = $(outbound.fields.regPriority).val().length ? JSON.stringify($(outbound.fields.regPriority).val()) : '["DEFAULT"]';
                outbound.ajax.data['create_lead'] = ($(outbound.fields.create_lead + ':checked').val()) ? $(outbound.fields.create_lead + ':checked').val() : '';
                outbound.ajax.data['show_card'] = ($(outbound.fields.show_card + ':checked').val()) ? $(outbound.fields.show_card + ':checked').val() : '';
                outbound.ajax.data['source'] = ($(outbound.fields.source +' select').val()) ? $(outbound.fields.source + ' select').val() : '';
                outbound.ajax.data['exceptions'] = ($(outbound.fields.exceptions).val()) ? $(outbound.fields.exceptions).val() : '';
                outbound.ajax.data['modify_number'] = ($(outbound.fields.modify_number).val()) ? $(outbound.fields.modify_number).val() : '';

                $.ajax({
                    url: outbound.ajax.url,
                    type: outbound.ajax.type,
                    data: outbound.ajax.data,
                    success: function (data) {
                        fpbxToast('Complete', 'Update Outbound Route', 'success');
                        IDTable.outbound_routes_table = data;
                    }}).then(function () {
                    if ($(outbound.OutboundRoutesModal.self).css('display') === 'block') {
                        $(outbound.OutboundRoutesModal.table).bootstrapTable('refresh');
                    }
                    $(outbound.OutboundRoutesPanel.table).bootstrapTable('refresh');
                });
            },

            detail: function(id) {
                var deferred = $.Deferred();
                var route = null;

                $.ajax({
                    url: "ajax.php",
                    type: "POST",
                    data: {
                        command: 'getRouteOutboundByID',
                        module: window.modulename,
                        id: id
                    },
                    success: function(data) {
                        route = data;
                    },
                    complete: function() {
                        deferred.resolve(route);
                    }
                });

                return deferred.promise();
            },
            __checkInvalid: function() {
                if (!$(outbound.fields.regPriority).val().length || ($(outbound.fields.regPriority).val().length < 3  && !$(outbound.fields.regPriority).val().includes("DEFAULT")) ){
                    warnInvalid($(outbound.fields.regPriority));
                    return false;
                }

                if (!$(outbound.fields.show_card).is(':checked')){
                    warnInvalid($(outbound.fields.show_card ));
                    return false;
                }
                if (!$(outbound.fields.create_lead).is(':checked')){
                    warnInvalid($(outbound.fields.create_lead));
                    return false;
                }

                return true;
            },
        };

    OutboundRoutesTab.init();

});