var referringProvider_detail = {
    settings: {
        referringProvider_id: null,

        referringMedicalFacilities_ajaxUrl: '',
        referringProviderChart_ajaxUrl: '',
        file_ajaxUrl: '',
        schedule_ajaxUrl: '',

        note_ajaxUrl: '',
        note_clinical_ajaxUrl: '',
        note_billing_ajaxUrl: '',
        note_appointment_ajaxUrl: '',
        note_specialist_ajaxUrl: '',

        referringMedicalFacilities_formUrl: '',
        referringMedicalFacilities_formActionUrl: '',
        file_formUrl: '',
        file_formActionUrl: '',
        referringProvider_note_formUrl: '',
        referringProvider_note_formActionUrl: '',
    },
    referringMedicalFacilitiesDataList: null,
    referringProviderChartDataList: null,
    fileDataList: null,
    scheduleDataList: null,
    noteDataList: null,
    noteClinicalDataList: null,
    noteBillingDataList: null,
    noteAppointmentDataList: null,
    noteSpecialistDataList: null,
    init: function() {
        // referringProvider_detail.initDataTable();
        referringProvider_detail.bindReferringProviderMedicalFacilityForm();
        referringProvider_detail.bindReferringProviderFileForm();
        referringProvider_detail.bindReferringProviderNoteForm();

        jQ('#referring-provider-tabs').on('change.zf.tabs', function () {
            const id = jQ(this).find('.tabs-title.is-active').data('dt-id');
            referringProvider_detail.initDataTable(id);
        });

        const id = jQ('#referring-provider-tabs').find('.tabs-title.is-active').data('dt-id');
        referringProvider_detail.initDataTable(id);
    },
    bindReferringProviderMedicalFacilityForm: function() {
        if(jQ('.href-referring-medical-facility-form').length > 0) {

            jQ('.href-referring-medical-facility-form').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: referringProvider_detail.settings.referringMedicalFacilities_formUrl + '/' + 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();
                        referringProvider_detail.bindReferringProviderMedicalFacilityFormAction();
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindReferringProviderMedicalFacilityFormAction: function() {

        jQ('.href-referringProvider-medical-facility-action').unbind('click.referringProviderMedicalFacilityFormAction').bind('click.referringProviderMedicalFacilityFormAction', function(){

            var requestName = 'referringProviderMedicalFacilityFormAction',
                modal = jQ('#modal'),
                modalContent = jQ('#modal-content'),
                _form = jQ('#form-referringMedicalFacility'),
            axn = jQ(this).data('axn');
            _form.find('.form-action').val(axn);

            global.formSubmitted();
            global.ajaxCancel(requestName);

            var settings = {
                url: referringProvider_detail.settings.referringMedicalFacilities_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function(json) {
                    if(json.success) {
                        location.reload();
                    } else {
                        global.formSubmittedReverse();
                        global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },

    bindReferringProviderFileForm: function() {
        if(jQ('.href-referring-provider-file-form').length > 0) {

            jQ('.href-referring-provider-file-form').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: referringProvider_detail.settings.file_formUrl + '/' + jQ(this).data('action') + '/' + jQ(this).data('id'),
                    type: 'GET',
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open').on('closed.zf.reveal', function () {
                            modalContent.html('');
                        });
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        modal.foundation('open').on('closed.zf.reveal', function () {
                            modalContent.html('');
                        });
                        global.bindFormSubmitted();
                        referringProvider_detail.bindReferringProviderFileFormAction();
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindReferringProviderFileFormAction: function() {

        jQ('.href-referring-provider-file-action').unbind('click.referringProviderFileFormAction').bind('click.referringProviderFileFormAction', function(){

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

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

            var formData = new FormData(jQ('#form-referringProviderFile')[0]);
            jQ.ajax({
                url: referringProvider_detail.settings.file_formActionUrl,  //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) {
                        modal.foundation('close');
                        referringProvider_detail.fileDataList.draw();
                        global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'success', json.successMessages);
                    } else {
                        _form.find('.progress').hide();
                        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
            });
        });
    },

    bindReferringProviderNoteForm: function() {
        if(jQ('.href-referring-provider-note-form').length > 0) {

            jQ('.href-referring-provider-note-form').unbind('click').bind('click', function(){
                var dataType = jQ(this).data('type') ;

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: referringProvider_detail.settings.referringProvider_note_formUrl + '/' + jQ(this).data('action') + '/' + jQ(this).data('id'),
                    type: 'GET',
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open').on('closed.zf.reveal', function () {
                            modalContent.html('');
                        });
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        modal.foundation('open').on('closed.zf.reveal', function () {
                            modalContent.html('');
                        });
                        global.bindFormSubmitted();
                        referringProvider_detail.bindReferringProviderNoteFormAction();
                        jQ('#referringProvider_note_type option')
                            .removeAttr('selected')
                            .filter('[value='+dataType+']')
                            .attr('selected', true);
                        if(dataType === '' || dataType === null){
                            jQ('#referringProvider_note_type').removeClass('hide');
                        }
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindReferringProviderNoteFormAction: function() {

        jQ('.href-referring-provider-note-action').unbind('click.referringProviderNoteFormAction').bind('click.referringProviderNoteFormAction', function () {

            var requestName = 'referringProviderNoteFormAction',
                _form = jQ('#form-referringProviderNote'),
                modal = jQ('#modal-small'),
                axn = jQ(this).data('axn');
            _form.find('.form-action').val(axn);

            global.formSubmitted();
            global.ajaxCancel(requestName);

            var settings = {
                url: referringProvider_detail.settings.referringProvider_note_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        referringProvider_detail.noteDataList.draw();
                        if(jQ('#referringProvider_note_type').val() === 'Clinical'){
                            referringProvider_detail.noteClinicalDataList.draw();
                        }
                        if(jQ('#referringProvider_note_type').val() === 'Billing'){
                            referringProvider_detail.noteBillingDataList.draw();
                        }
                        if(jQ('#referringProvider_note_type').val() === 'Appointment'){
                            referringProvider_detail.noteAppointmentDataList.draw();
                        }
                        if(jQ('#referringProvider_note_type').val() === 'Specialist'){
                            referringProvider_detail.noteSpecialistDataList.draw();
                        }
                        if(jQ('#referringProvider_note_type').val() === 'Letter'){
                            referringProvider_detail.noteLetterDataList.draw();
                        }
                        referringProvider_detail.referringProviderHistoryDataList.draw();
                        global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },

    initDataTable: function(dt_id) {

        if (jQ.fn.DataTable.isDataTable('#'+dt_id)) {
            return;
        }

        switch (dt_id) {

            case 'referringHealthFacilityChart-datalist':

                var callBack2 = function() {

                };
                referringProvider_detail.referringProviderChartDataList = jQ('#referringHealthFacilityChart-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': referringProvider_detail.settings.referringProviderChart_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.referring_provider_id = referringProvider_detail.settings.referringProvider_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 5 },
                        { 'searchable': false, 'targets': 5 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack2();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack1);
                            }
                        }
                    }
                });

                break;
            case 'referringProvider-schedule-datalist':

                var callBack4 = function() {
                    // referringProvider_detail.bindReferringProviderAppointmentNoticeFaxForm();
                    // referringProvider_detail.bindReferringProviderAppointmentNoticeFaxRowButton();
                };
                referringProvider_detail.scheduleDataList = jQ('#referringProvider-schedule-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': referringProvider_detail.settings.schedule_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.referring_provider_id = referringProvider_detail.settings.referringProvider_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 8 },
                        { 'searchable': false, 'targets': 8 }
                    ],
                    'orderClasses': false,
                    order: [[2, 'desc']],
                    drawCallback: callBack4,
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack7);
                            }
                        }
                    }
                });

                break;
            case 'file-datalist':

                var callBack3 = function() {
                    referringProvider_detail.bindReferringProviderFileForm();
                };
                referringProvider_detail.fileDataList = jQ('#file-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': referringProvider_detail.settings.file_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.referring_provider_id = referringProvider_detail.settings.referringProvider_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 5 },
                        { 'searchable': false, 'targets': 5 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack3();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack2);
                            }
                        }
                    }
                });

                break;
            case 'panel-notes':

                jQ('#referring-provider-note-tabs').on('change.zf.tabs', function () {
                    const id = jQ(this).find('.tabs-title.is-active').data('dt-id');
                    referringProvider_detail.initDataTable(id);
                });

                const id2 = jQ('#referring-provider-note-tabs').find('.tabs-title.is-active').data('dt-id');
                referringProvider_detail.initDataTable(id2);
                break;
            case 'referringProvider-note-datalist':

                var callBack5 = function() {
                    referringProvider_detail.bindReferringProviderNoteForm();
                };
                referringProvider_detail.noteDataList = jQ('#referringProvider-note-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': referringProvider_detail.settings.note_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.referring_provider_id = referringProvider_detail.settings.referringProvider_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 4 },
                        { 'searchable': false, 'targets': 4 }
                    ],
                    'orderClasses': false,
                    order: [[1, 'desc']],
                    drawCallback: function() {
                        callBack5();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack6);
                            }
                        }
                    }
                });

                break;
        }


        jQ('.content-container').removeClass('has-loading');
        jQ('.content-container-content').removeClass('hide');

        return;

        var callBack1 = function() {
            referringProvider_detail.bindReferringProviderMedicalFacilityForm()
        };
        referringProvider_detail.referringMedicalFacilitiesDataList = jQ('#referringMedicalFacilities-datalist').DataTable({
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': referringProvider_detail.settings.referringMedicalFacilities_ajaxUrl,
                'data': function(d) {
                    d.url = global.settings.url;
                    d.referringProvider_id = referringProvider_detail.settings.referringProvider_id;
                }
            },
            'deferRender': true,
            'columnDefs': [
                { 'orderable': false, 'targets': 8 },
                { 'searchable': false, 'targets': 8 }
            ],
            'orderClasses': false,
            drawCallback: function() {
                callBack1();
            },
            responsive: {
                details: {
                    renderer: function( api,rowIdx ) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBack1);
                    }
                }
            }
        });
    }
};