var referringHealthFacility_detail = {
    settings: {
        referringHealthFacility_id: null,

        referringMedicalFacilities_ajaxUrl: '',
        referringHealthFacilityChart_ajaxUrl: '',
        file_ajaxUrl: '',
        schedule_ajaxUrl: '',
        referringSalesAgent_ajaxUrl: '',

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

        referringMedicalFacilities_formUrl: '',
        referringMedicalFacilities_formActionUrl: '',
        referringSalesAgent_formUrl: '',
        referringSalesAgent_formActionUrl: '',
        file_formUrl: '',
        file_formActionUrl: '',
        referringHealthFacility_note_formUrl: '',
        referringHealthFacility_note_formActionUrl: '',

        note_template_autocomplete_url: '',
        note_template_data_url: '',
    },
    referringMedicalFacilitiesDataList: null,
    referringSalesAgentDataList: null,
    referringHealthFacilityChartDataList: null,
    fileDataList: null,
    scheduleDataList: null,
    noteDataList: null,
    noteClinicalDataList: null,
    noteBillingDataList: null,
    noteAppointmentDataList: null,
    noteSpecialistDataList: null,
    init: function() {
        // referringHealthFacility_detail.initDataTable();
        referringHealthFacility_detail.bindReferringMedicalFacilityProviderForm();
        referringHealthFacility_detail.bindReferringMedicalFacilitySalesAgentForm();
        referringHealthFacility_detail.bindReferringHealthFacilityFileForm();
        referringHealthFacility_detail.bindReferringHealthFacilityNoteForm();

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

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

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: referringHealthFacility_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();
                        referringHealthFacility_detail.bindReferringMedicalFacilityProviderFormAction();
                    }
                };

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

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

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

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

            var settings = {
                url: referringHealthFacility_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);
        });
    },

    bindReferringMedicalFacilitySalesAgentForm: function() {
        if(jQ('.href-referring-sales_agent-form').length > 0) {

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: referringHealthFacility_detail.settings.referringSalesAgent_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();
                        referringHealthFacility_detail.bindReferringMedicalFacilitySalesAgentFormAction();
                    }
                };

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

        jQ('.href-referring-sales-agent-action').unbind('click.referringHealthFacilitySalesAgentFormAction').bind('click.referringHealthFacilitySalesAgentFormAction', function(){

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

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

            var settings = {
                url: referringHealthFacility_detail.settings.referringSalesAgent_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);
        });
    },

    bindReferringHealthFacilityFileForm: function() {
        if(jQ('.href-referring-health-facility-file-form').length > 0) {

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: referringHealthFacility_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();
                        referringHealthFacility_detail.bindReferringHealthFacilityFileFormAction();
                    }
                };

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

        jQ('.href-referring-health-facility-file-action').unbind('click.referringHealthFacilityFileFormAction').bind('click.referringHealthFacilityFileFormAction', function(){

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

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

            var formData = new FormData(jQ('#form-referringHealthFacilityFile')[0]);
            jQ.ajax({
                url: referringHealthFacility_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');
                        referringHealthFacility_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
            });
        });
    },

    bindReferringHealthFacilityNoteForm: function() {
        if(jQ('.href-referring-health-facility-note-form').length > 0) {

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: referringHealthFacility_detail.settings.referringHealthFacility_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();
                        referringHealthFacility_detail.bindReferringHealthFacilityNoteFormAction();
                        jQ('#referringHealthFacility_note_type option')
                            .removeAttr('selected')
                            .filter('[value='+dataType+']')
                            .attr('selected', true);
                        if(dataType === '' || dataType === null){
                            jQ('#referringHealthFacility_note_type').removeClass('hide');
                        }

                        jQ('#referringHealthFacility_note_type').unbind('change').bind('change', function () {
                            if (jQ(this).val() == 'Template') {
                                jQ('#referringHealthFacility_note_note_template_description').removeClass('hide');
                            } else {
                                jQ('#referringHealthFacility_note_note_template_description').addClass('hide');
                            }
                        });

                        global.autocomplete.bind(referringHealthFacility_detail.settings.note_template_autocomplete_url, '#referringHealthFacility_note_note_template_description', '#referringHealthFacility_note_noteTemplate', {
                            onSelect: function (d) {
                                global.ajax({
                                    url: referringHealthFacility_detail.settings.note_template_data_url+'/'+d.noteTemplate_description,
                                    type: 'GET',
                                    beforeSend: function() {
                                        jQ('#referringHealthFacility_note_note').val('');
                                    },
                                    success: function(json) {
                                        jQ('#referringHealthFacility_note_note').val(json.note);
                                    },
                                });
                            }
                        });
                    }
                };

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

        jQ('.href-referring-health-facility-note-action').unbind('click.referringHealthFacilityNoteFormAction').bind('click.referringHealthFacilityNoteFormAction', function () {

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

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

            var settings = {
                url: referringHealthFacility_detail.settings.referringHealthFacility_note_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        referringHealthFacility_detail.noteDataList.draw();
                        if(jQ('#referringHealthFacility_note_type').val() === 'Clinical'){
                            referringHealthFacility_detail.noteClinicalDataList.draw();
                        }
                        if(jQ('#referringHealthFacility_note_type').val() === 'Billing'){
                            referringHealthFacility_detail.noteBillingDataList.draw();
                        }
                        if(jQ('#referringHealthFacility_note_type').val() === 'Appointment'){
                            referringHealthFacility_detail.noteAppointmentDataList.draw();
                        }
                        if(jQ('#referringHealthFacility_note_type').val() === 'Specialist'){
                            referringHealthFacility_detail.noteSpecialistDataList.draw();
                        }
                        if(jQ('#referringHealthFacility_note_type').val() === 'Letter'){
                            referringHealthFacility_detail.noteLetterDataList.draw();
                        }
                        // referringHealthFacility_detail.referringHealthFacilityHistoryDataList.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 callBack3 = function() {

                };
                referringHealthFacility_detail.referringHealthFacilityChartDataList = jQ('#referringHealthFacilityChart-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': referringHealthFacility_detail.settings.referringHealthFacilityChart_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.referring_health_facility_id = referringHealthFacility_detail.settings.referringHealthFacility_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, callBack1);
                            }
                        }
                    }
                });

                break;
            case 'referringHealthFacility-schedule-datalist':

                var callBack5 = function() {
                    // referringHealthFacility_detail.bindReferringHealthFacilityAppointmentNoticeFaxForm();
                    // referringHealthFacility_detail.bindReferringHealthFacilityAppointmentNoticeFaxRowButton();
                };
                referringHealthFacility_detail.scheduleDataList = jQ('#referringHealthFacility-schedule-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': referringHealthFacility_detail.settings.schedule_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.referring_health_facility_id = referringHealthFacility_detail.settings.referringHealthFacility_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 8 },
                        { 'searchable': false, 'targets': 8 }
                    ],
                    'orderClasses': false,
                    order: [[2, 'desc']],
                    drawCallback: callBack5,
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack7);
                            }
                        }
                    }
                });

                break;
            case 'file-datalist':

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

                break;
            case 'panel-notes':

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

                const id2 = jQ('#referring-health-facility-note-tabs').find('.tabs-title.is-active').data('dt-id');
                referringHealthFacility_detail.initDataTable(id2);

                break;
            case 'referringHealthFacility-note-datalist':

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

                break;
            case 'referringProviders-datalist':

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

                break;
        }

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

        return;

        var callBack2 = function() {
            referringHealthFacility_detail.bindReferringMedicalFacilitySalesAgentForm()
        };
        referringHealthFacility_detail.referringSalesAgentDataList = jQ('#referringSalesAgent-datalist').DataTable({
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': referringHealthFacility_detail.settings.referringSalesAgent_ajaxUrl,
                'data': function(d) {
                    d.url = global.settings.url;
                    d.referringHealthFacility_id = referringHealthFacility_detail.settings.referringHealthFacility_id;
                }
            },
            'deferRender': true,
            'columnDefs': [
                { 'orderable': false, 'targets': 3 },
                { 'searchable': false, 'targets': 3 }
            ],
            'orderClasses': false,
            drawCallback: function() {
                callBack2();
            },
            responsive: {
                details: {
                    renderer: function( api,rowIdx ) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBack2);
                    }
                }
            }
        });


    }
};