var faxingOption = {
    settings: {
        ajaxUrl: '',
        faxingOptionFormUrl: '',
        faxingOptionFormActionUrl: '',
        patient_autocomplete_url: '',
        company_autocomplete_url: '',
        referring_health_facility_autocomplete_url: '',
    },
    dataList: null,
    init: function() {
        faxingOption.initDataTable();
    },
    initDataTable: function() {

        var callBack = function() {
            faxingOption.bindFaxingOptionForm();
            global.askContinue();
        }, actionCol = jQ('#faxingOption-datalist th').length - 1;;

        faxingOption.dataList = jQ('#faxingOption-datalist').DataTable({
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': faxingOption.settings.ajaxUrl,
                'data': function(d) {
                    d.url = global.settings.url;
                    d.status = jQ('#status-filter').val();
                }
            },
            'deferRender': true,
            'columnDefs': [
                { 'orderable': false, 'targets': actionCol },
                { 'searchable': false, 'targets': actionCol }
            ],
            "order": [[ 0, "desc" ]],
            drawCallback: function() {
                callBack();
            },
            responsive: {
                details: {
                    renderer: function( api,rowIdx ) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBack);
                    }
                }
            }
        });

        jQ('#status-filter').on('change', function(){
            faxingOption.dataList.draw();
        });

        jQ('.content-container').removeClass('has-loading');
        jQ('.content-container-content').removeClass('hide');
    },
    bindFaxingOptionForm: function() {
        if(jQ('.href-faxingOption-form').length > 0) {

            jQ('.href-faxingOption-form').unbind('click').bind('click', function(){

                var requestName = 'faxingOptionForm',
                    modal = jQ('#modal-small'),
                    modalContent = jQ('#modal-content-small');

                global.ajaxCancel(requestName);

                var settings = {
                    url: faxingOption.settings.faxingOptionFormUrl + '/' + jQ(this).data('action') + '/' + jQ(this).data('id'),
                    type: 'GET',
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open');
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        modal.foundation('open');
                        global.bindFormSubmitted();
                        faxingOption.bindFaxingOptionFormAction();
                        global.autocomplete.bind(faxingOption.settings.patient_autocomplete_url, '#faxingOptions_patientName', '#faxingOptions_patient');
                        global.autocomplete.bind(faxingOption.settings.company_autocomplete_url, '#faxingOptions_company_desc', '#faxingOptions_company');
                        global.autocomplete.bind(faxingOption.settings.referring_health_facility_autocomplete_url,
                            '#faxingOptions_referringHealthFacility_desc',
                            '#faxingOptions_referringHealthFacility',
                            {
                                onSelect: function (d) {
                                    jQ('#faxingOptions_faxNo').val(d.fax_no)
                                }
                            });

                        const editor = CKEDITOR.replace('faxingOptions_customBody');
                        editor.on('change', function () {
                            editor.updateElement();
                        });
                    }
                };
                global.ajax(settings, requestName);
            });
        }
    },
    bindFaxingOptionFormAction: function() {

        jQ('.href-faxingOption-action').unbind('click.faxingOptionFormAction').bind('click.faxingOptionFormAction', function(){

            var requestName = 'faxingOptionFormAction',
                modal = jQ('#modal-small'),
                modalContent = jQ('#modal-content-small'),
                _form = jQ('#form-faxingOption'),
                axn = jQ(this).data('axn');

            _form.find('.form-action').val(axn);

            var formData = new FormData(jQ('#form-faxingOption')[0]);
            jQ.ajax({
                url: faxingOption.settings.faxingOptionFormActionUrl,  //Server script to process data
                type: 'POST',
                xhr: function() {  // Custom XMLHttpRequest
                    var myXhr = jQ.ajaxSettings.xhr();
                    if(myXhr.upload){ // Check if upload property exists
                        myXhr.upload.addEventListener('progress', function(e) {
                            if(e.lengthComputable){
                                var percentComplete = (e.loaded / e.total) * 100;
                                _form.find(".progress-meter").width(percentComplete+'%');
                            }
                        }, false); // For handling the progress of the upload
                    }
                    return myXhr;
                },
                //Ajax events
                beforeSend: function() {
                    global.formSubmitted();
                    if(axn !== 'd') {
                        _form.find(".progress-meter").width('0');
                        _form.find('.progress').show();
                    }
                },
                success: function(json) {
                    global.formSubmittedReverse();
                    if(json.success) {
                        faxingOption.dataList.draw();
                        global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'success', json.successMessages);
                        modal.foundation('close');
                    } else {
                        _form.find('.progress').hide();
                        // alert(json.errorMessages);
                        global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                    }
                },
                error: function(xhr, response_text) {
                    global.formSubmittedReverse();
                    if(response_text !== 'abort' && response_text !== 'error') {
                        alert('Error. Please try again.');
                    }
                },
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        });
    },
};