var patient_chart_form = {
    settings: {
        noteTemplateAccess: '',
        healthFacility_autocomplete_url: '',
        account_user_autocomplete_url: '',
        provider_autocomplete_url: '',
        diagnosis_autocomplete_url: '',
        chart_type_method_autocomplete_url: '',
        chart_type_method_list_url: '',
        methodCtr: '',
        file_ajaxUrl: '',
        medical_diagnosis_ajaxUrl: '',
        medical_diagnosis_medication_ajaxUrl: '',
        file_formUrl: '',
        file_formActionUrl: '',
        patient_chart_id: '',
        patient_id: '',
        patient_diagnosis_formUrl: '',
        patient_diagnosis_formActionUrl: '',
        patient_diagnosis_medication_formActionUrl: '',
        patient_diagnosis_medication_formUrl: '',
        diagnosis_key: '',
        billing_procedure_ajaxUrl: '',
        billing_other_ajaxUrl: '',
        billing_procedure_formUrl: '',
        billing_procedure_formActionUrl: '',
        billing_other_procedure_formUrl: '',
        billing_other_procedure_formActionUrl:'',
        payment_ajaxUrl: '',
        payment_formUrl: '',
        payment_formActionUrl: '',
        chart_note_ajaxUrl: '',
        patient_chart_note_formUrl: '',
        patient_chart_note_formActionUrl: '',
        chart_procedure_autocomplete: '',
        patient_chart_type: '',
        patient_chart_device_ajaxUrl: '',
        patient_chart_isAssessmentUrl: '',
        account_user_ids : [],
        checkExistInitialAssessment : {},

        note_template_autocomplete_url: '',
        note_template_data_url: '',
        noteTemplate_description: '',
    },
    fileDataList: null,
    medicalDiagnosisDataList: null,
    medicalDiagnosisMedicationDataList: null,
    billingProcedureDataList: null,
    billingOtherProcedureDataList: null,
    noteDataList:null,
    init: function() {
        // patient_chart_form.initDataTable();
        patient_chart_form.initAutocomplete();
        patient_chart_form.bindComputeBMI();
        patient_chart_form.bindElements();
        patient_chart_form.bindPatientChartFileForm();
        patient_chart_form.bindPatientMedicalDiagnosisForm();
        patient_chart_form.bindPatientMedicalDiagnosisMedicationForm();
        patient_chart_form.bindPatientChartProcedureForm();
        patient_chart_form.bindPatientChartOtherProcedureForm();
        patient_chart_form.bindPatientChartPaymentForm();
        patient_chart_form.endorsedShowEvent();
        patient_chart_form.bindCcAdd();
        patient_chart_form.bindNoteTemplate();
        if(patient_chart_form.settings.noteTemplateAccess == false) {
            jQ('#patient_chart_note_type').children('option[value=Template]').addClass('hide');
        }

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

        const id = jQ('#patient-chart-tabs').find('.tabs-title.is-active').data('dt-id');
        patient_chart_form.initDataTable(id);
    },
    initAutocomplete: function() {
        global.autocomplete.bind(patient_chart_form.settings.healthFacility_autocomplete_url, '#patient_chart_health_facility_desc', '#patient_chart_health_facility');
        global.autocomplete.bind(patient_chart_form.settings.account_user_autocomplete_url, '#patient_chart_endorsed_by', '#patient_chart_account_user_endorsed_by');
        global.autocomplete.bind(patient_chart_form.settings.provider_autocomplete_url, '#patient_chart_provider_desc', '#patient_chart_provider');
        global.autocomplete.bind(patient_chart_form.settings.ticket_status_autocomplete_url, '#patient_chart_ticket_status', '#patient_chart_ticket_status_id');
        global.autocomplete.bind(patient_chart_form.settings.ticket_severity_autocomplete_url, '#patient_chart_ticket_severity', '#patient_chart_ticket_severity_id');
        global.autocomplete.bind(patient_chart_form.settings.account_user_ar_autocomplete_url, '#patient_chart_billing_full_name', '#patient_chart_account_user_billing');
        global.autocomplete.bind(patient_chart_form.settings.account_user_cbt_autocomplete_url, '#patient_chart_account_staff_full_name', '#patient_chart_account_staff');
    },
    initDataTable: function(dt_id) {

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

        switch (dt_id) {

            case 'patient-chart-file-datalist':

                var callBack1 = function() {
                    patient_chart_form.bindPatientChartFileForm();
                };
                patient_chart_form.fileDataList = jQ('#patient-chart-file-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_chart_form.settings.file_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_chart_id = patient_chart_form.settings.patient_chart_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 4 },
                        { 'searchable': false, 'targets': 4 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack1();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack1);
                            }
                        }
                    }
                });

                break;
            case 'panel-medical':

                jQ('#patient-chart-medical-tabs').on('change.zf.tabs', function () {
                    const id = jQ(this).find('.tabs-title.is-active').data('dt-id');
                    patient_chart_form.initDataTable(id);
                });

                const id2 = jQ('#patient-chart-medical-tabs').find('.tabs-title.is-active').data('dt-id');
                patient_chart_form.initDataTable(id2);
                break;
            case 'patient-chart-medical-diagnosis-datalist':

                var callBack2 = function() {
                    patient_chart_form.bindPatientMedicalDiagnosisForm()
                };
                patient_chart_form.medicalDiagnosisDataList = jQ('#patient-chart-medical-diagnosis-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_chart_form.settings.medical_diagnosis_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_chart_id = patient_chart_form.settings.patient_chart_id;
                            d.patient_id = patient_chart_form.settings.patient_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 4 },
                        { 'searchable': false, 'targets': 4 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack2();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack2);
                            }
                        }
                    }
                });

                var callBack3 = function() {
                    patient_chart_form.bindPatientMedicalDiagnosisMedicationForm();
                };
                for (let i = 0 ; i < patient_chart_form.settings.diagnosis_key ; i++){

                    patient_chart_form.medicalDiagnosisMedicationDataList = jQ('#patient-chart-medical-diagnosis-medication-datalist' + i).DataTable({
                        'processing': true,
                        'serverSide': true,
                        'ajax': {
                            'url': patient_chart_form.settings.medical_diagnosis_medication_ajaxUrl,
                            'data': function(d) {
                                d.url = global.settings.url;
                                d.patientDiagnosis_id = jQ('#patient-chart-medical-diagnosis-medication-datalist' + i).data('id');
                            }
                        },
                        'deferRender': true,
                        'columnDefs': [
                            { 'orderable': false, 'targets': 4 },
                            { 'searchable': false, 'targets': 4 }
                        ],
                        'orderClasses': false,
                        drawCallback: function() {
                            callBack3();
                        },
                        responsive: {
                            details: {
                                renderer: function( api,rowIdx ) {
                                    return global.dataTableResponsiveCallBack(api, rowIdx, callBack3);
                                }
                            }
                        }
                    });
                }

                break;
            case 'patient-chart-note-datalist':

                var callBack7 = function() {
                    patient_chart_form.bindPatientChartNoteForm();
                };
                patient_chart_form.noteDataList = jQ('#patient-chart-note-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_chart_form.settings.chart_note_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patientChart_id = patient_chart_form.settings.patient_chart_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 3 },
                        { 'searchable': false, 'targets': 3 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack7();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack7);
                            }
                        }
                    }
                });

                break;
        }

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

        return;

        var callBack4 = function() {
            patient_chart_form.bindPatientChartProcedureForm();
        };
        patient_chart_form.billingProcedureDataList = jQ('#patient-chart-billing-procedure-datalist').DataTable({
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': patient_chart_form.settings.billing_procedure_ajaxUrl,
                'data': function(d) {
                    d.url = global.settings.url;
                    d.patient_chart_id = patient_chart_form.settings.patient_chart_id;
                }
            },
            'deferRender': true,
            'columnDefs': [
                { 'orderable': false, 'targets': 3 },
                { 'searchable': false, 'targets': 3 }
            ],
            'orderClasses': false,
            drawCallback: function() {
                callBack4();
            },
            responsive: {
                details: {
                    renderer: function( api,rowIdx ) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBack4);
                    }
                }
            }
        });

        var callBack5 = function() {
            patient_chart_form.bindPatientChartOtherProcedureForm();
        };
        patient_chart_form.billingOtherProcedureDataList = jQ('#patient-chart-billing-other-datalist').DataTable({
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': patient_chart_form.settings.billing_other_ajaxUrl,
                'data': function(d) {
                    d.url = global.settings.url;
                    d.patient_chart_id = patient_chart_form.settings.patient_chart_id;
                }
            },
            'deferRender': true,
            'columnDefs': [
                { 'orderable': false, 'targets': 2 },
                { 'searchable': false, 'targets': 2 }
            ],
            'orderClasses': false,
            drawCallback: function() {
                callBack5();
            },
            responsive: {
                details: {
                    renderer: function( api,rowIdx ) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBack5);
                    }
                }
            }
        });

        var callBack6 = function() {
            patient_chart_form.bindPatientChartPaymentForm();
        };
        patient_chart_form.paymentDataList = jQ('#patient-chart-payment-datalist').DataTable({
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': patient_chart_form.settings.payment_ajaxUrl,
                'data': function(d) {
                    d.url = global.settings.url;
                    d.patient_chart_id = patient_chart_form.settings.patient_chart_id;
                }
            },
            'deferRender': true,
            'columnDefs': [
                { 'orderable': false, 'targets': 9 },
                { 'searchable': false, 'targets': 9 }
            ],
            'orderClasses': false,
            drawCallback: function() {
                callBack6();
            },
            responsive: {
                details: {
                    renderer: function( api,rowIdx ) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBack6);
                    }
                }
            }
        });

    },
    bindComputeBMI: function () {
        jQ('.compute-bmi').unbind('keyup').bind('keyup', function(){
            var height = global.parseNum(jQ('#patient_chart_height').val()),
                weight = global.parseNum(jQ('#patient_chart_weight').val()),
                bmi = global.parseNum(((weight / (height*height))*703).toFixed(2));

            jQ('#patient_chart_bmi').val(bmi);
        });
    },
    bindElements: function(){
        jQ('#patient_chart_chart_type').on('change', function () {
            global.ajax({
                url: patient_chart_form.settings.chart_type_method_list_url,
                type: 'GET',
                data: {
                    id : jQ(this).val(),
                },
                success: function (data) {
                    jQ('#tbody-chart-type-method').html('');
                    const methods = data.methods;
                    for (let i = 0 ; i < methods.length ; i++){
                        var hasAssessment = methods[i].has_initial_assessment;
                        const idx = parseInt(patient_chart_form.settings.methodCtr) + i;

                        var tr = jQ('<tr/>').attr({id: 'tr-chart-type-method-' + idx}),
                            td1 = jQ('<td/>'),
                            td2 = jQ('<td/>'),
                            td3 = jQ('<td/>'),
                            td4 = jQ('<td/>'),
                            td5 = jQ('<td/>'),
                            td6 = jQ('<td/>'),
                            td7 = jQ('<td/>'),
                            td8 = jQ('<td/>'),
                            td10 = jQ('<td/>'),
                            td11 = jQ('<td/>'),
                            td12 = jQ('<td/>'),
                            td13 = jQ('<td/>'),
                            td14 = jQ('<td/>'),
                            td15 = jQ('<td/>'),
                            td16 = jQ('<td/>'),
                            td17 = jQ('<td/>'),
                            td18 = jQ('<td/>'),
                            hidId = jQ('<input/>').attr({
                                type: 'hidden',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][id]'
                            }),
                            hid1Id = 'patient_chart_chartTypeMethods_' + idx + '_chart_type_method',
                            hid1 = jQ('<input/>').attr({
                                type: 'hidden',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][chart_type_method]',
                                id: hid1Id,
                                value: methods[i].id
                            }),
                            txt1 = jQ('<label style="font-weight: bold;">').text(methods[i].description),
                            txt2Id = 'patient_chart_chartTypeMethods_' + idx + '_note',
                            txt2 = jQ('<textarea/>').attr({
                                type: 'text',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][note]',
                                id: txt2Id
                            }),
                            txt3Label = jQ('<label style="text-align: left;">').text('Pressure Range From'),
                            txt3Id = 'patient_chart_chartTypeMethods_' + idx + '_pressureRangeFrom',
                            txt3 = jQ('<input/>').attr({
                                type: 'text',
                                class: 'quantity',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][pressureRangeFrom]',
                                id: txt3Id
                            }),
                            txt4Label = jQ('<label style="text-align: left;">').text('Avg Hours Usage/night'),
                            txt4Id = 'patient_chart_chartTypeMethods_' + idx + '_averageCPAPUsage',
                            txt4 = jQ('<input/>').attr({
                                type: 'text',
                                class: 'amount',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][averageCPAPUsage]',
                                id: txt4Id
                            }),
                            txt5Label = jQ('<label style="text-align: left;">').text('Pressure Range To'),
                            txt5Id = 'patient_chart_chartTypeMethods_' + idx + '_pressureRangeTo',
                            txt5 = jQ('<input/>').attr({
                                type: 'text',
                                class: 'quantity',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][pressureRangeTo]',
                                id: txt5Id
                            }),
                            txt6Label = jQ('<label style="text-align: left;">').text('Mask Leak'),
                            txt6Id = 'patient_chart_chartTypeMethods_' + idx + '_maskLeak',
                            txt6 = jQ('<input/>').attr({
                                type: 'text',
                                class: 'amount',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][maskLeak]',
                                id: txt6Id
                            }),
                            txt7Label = jQ('<label style="text-align: left;">').text('Current AHI'),
                            txt7Id = 'patient_chart_chartTypeMethods_' + idx + '_currentAHI',
                            txt7 = jQ('<input/>').attr({
                                type: 'text',
                                class: 'quantity',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][currentAHI]',
                                id: txt7Id
                            }),
                            txt8Label = jQ('<label style="text-align: left;">').text('Last Time Accessories Replaced'),
                            txt8Id = 'patient_chart_chartTypeMethods_' + idx + '_lastDeviceReplaced',
                            txt8 = jQ('<input/>').attr({
                                type: 'text',
                                class: 'date',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][lastDeviceReplaced]',
                                id: txt8Id
                            }),
                            txt10Label = jQ('<label style="text-align: left;">').text('Current RDI'),
                            txt10Id = 'patient_chart_chartTypeMethods_' + idx + '_currentRDI',
                            txt10 = jQ('<input/>').attr({
                                type: 'text',
                                class: 'quantity',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][currentRDI]',
                                id: txt10Id
                            }),
                            txt11Label = jQ('<label style="text-align: left;">').text('Initial Berlin Questionnaire Score'),
                            txt11Id = 'patient_chart_chartTypeMethods_' + idx + '_initialBerlinQuestionnaireScore',
                            txt11 = jQ('<input/>').attr({
                                type: 'text',
                                class: '',
                                value: patient_chart_form.settings.ifBQS ? patient_chart_form.settings.ifBQS : '',
                                readonly: patient_chart_form.settings.ifBQS ? true : false,
                                name: 'patient_chart[chartTypeMethods][' + idx + '][initialBerlinQuestionnaireScore]',
                                id: txt11Id
                            }),
                            txt12Label = jQ('<label style="text-align: left;">').text('Initial Epworth Sleepness Scale'),
                            txt12Id = 'patient_chart_chartTypeMethods_' + idx + '_initialEpworthSleepnessScale',
                            txt12 = jQ('<input/>').attr({
                                type: 'text',
                                class: '',
                                value: patient_chart_form.settings.ifIESS ? patient_chart_form.settings.ifIESS : '',
                                readonly: patient_chart_form.settings.ifIESS ? true : false,
                                name: 'patient_chart[chartTypeMethods][' + idx + '][initialEpworthSleepnessScale]',
                                id: txt12Id
                            }),
                            txt13Label = jQ('<label style="text-align: left;">').text('% time < 90% SpO2'),
                            txt13Id = 'patient_chart_chartTypeMethods_' + idx + '_timeNinetyPercentSpotwo',
                            txt13 = jQ('<input/>').attr({
                                type: 'text',
                                class: '',
                                value: patient_chart_form.settings.ifTNPS ? patient_chart_form.settings.ifTNPS : '',
                                readonly: patient_chart_form.settings.ifTNPS ? true : false,
                                name: 'patient_chart[chartTypeMethods][' + idx + '][timeNinetyPercentSpotwo]',
                                id: txt13Id
                            }),
                            txt14Label = jQ('<label style="text-align: left;">').text('Initial Mean SpO2'),
                            txt14Id = 'patient_chart_chartTypeMethods_' + idx + '_initialMeanSpotwo',
                            txt14 = jQ('<input/>').attr({
                                type: 'text',
                                class: '',
                                value: patient_chart_form.settings.ifIMS ? patient_chart_form.settings.ifIMS : '',
                                readonly: patient_chart_form.settings.ifIMS ? true : false,
                                name: 'patient_chart[chartTypeMethods][' + idx + '][initialMeanSpotwo]',
                                id: txt14Id
                            }),
                            txt15Label = jQ('<label style="text-align: left;">').text('Initial AHI'),
                            txt15Id = 'patient_chart_chartTypeMethods_' + idx + '_initialAhi',
                            txt15 = jQ('<input/>').attr({
                                type: 'text',
                                class: '',
                                value: patient_chart_form.settings.ifInitialAHI ? patient_chart_form.settings.ifInitialAHI : '',
                                readonly: patient_chart_form.settings.ifInitialAHI ? true : false,
                                name: 'patient_chart[chartTypeMethods][' + idx + '][initialAhi]',
                                id: txt15Id
                            }),
                            txt16Label = jQ('<label style="text-align: left;">').text('Initial RDI'),
                            txt16Id = 'patient_chart_chartTypeMethods_' + idx + '_initialRdi',
                            txt16 = jQ('<input/>').attr({
                                type: 'text',
                                class: '',
                                value: patient_chart_form.settings.ifInitialRDI ? patient_chart_form.settings.ifInitialRDI : '',
                                readonly: patient_chart_form.settings.ifInitialRDI ? true : false,
                                name: 'patient_chart[chartTypeMethods][' + idx + '][initialRdi]',
                                id: txt16Id
                            }),
                            txt17Label = jQ('<label style="text-align: left;">').text('Neck Size (Inches)'),
                            txt17Id = 'patient_chart_chartTypeMethods_' + idx + '_neckSize',
                            txt17 = jQ('<input/>').attr({
                                type: 'text',
                                class: '',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][neckSize]',
                                id: txt17Id
                            }),
                            txt18Label = jQ('<label style="text-align: left;">').text('ESS'),
                            txt18Id = 'patient_chart_chartTypeMethods_' + idx + '_ess',
                            txt18 = jQ('<input/>').attr({
                                type: 'text',
                                class: '',
                                name: 'patient_chart[chartTypeMethods][' + idx + '][ess]',
                                id: txt18Id
                            }),

                            tr2 = jQ('<tr>'),
                            tr3 = jQ('<tr style="background-color: white;">'),
                            tr4 = jQ('<tr style="background-color: white;">'),
                            tr5 = jQ('<tr style="background-color: white;">'),

                            txt9 = jQ('<table width="100%">');

                        hasAssessment == 1 ? tr2 : tr2.addClass('hide');
                        hasAssessment == 1 ? tr3 : tr3.addClass('hide');


                        hid1.appendTo(td1);
                        hidId.appendTo(td1);
                        txt3Label.appendTo(td3);
                        txt3.appendTo(td3);
                        txt4Label.appendTo(td4);
                        txt4.appendTo(td4);
                        txt5Label.appendTo(td5);
                        txt5.appendTo(td5);
                        txt6Label.appendTo(td6);
                        txt6.appendTo(td6);
                        txt7Label.appendTo(td7);
                        txt7.appendTo(td7);
                        txt8Label.appendTo(td8);
                        txt8.appendTo(td8);
                        txt10Label.appendTo(td10);
                        txt10.appendTo(td10);

                        txt11Label.appendTo(td11);
                        txt11.appendTo(td11);
                        txt12Label.appendTo(td12);
                        txt12.appendTo(td12);
                        txt13Label.appendTo(td13);
                        txt13.appendTo(td13);
                        txt14Label.appendTo(td14);
                        txt14.appendTo(td14);
                        txt15Label.appendTo(td15);
                        txt15.appendTo(td15);
                        txt16Label.appendTo(td16);
                        txt16.appendTo(td16);
                        txt17Label.appendTo(td17);
                        txt17.appendTo(td17);
                        txt18Label.appendTo(td18);
                        txt18.appendTo(td18);


                        //Initial
                        td11.appendTo(tr2);
                        td12.appendTo(tr2);
                        td13.appendTo(tr3);
                        td14.appendTo(tr3);
                        td15.appendTo(tr3);
                        td16.appendTo(tr3);

                        //Current
                        td3.appendTo(tr4);
                        td5.appendTo(tr4);
                        td4.appendTo(tr4);
                        td7.appendTo(tr4);
                        td10.appendTo(tr4);

                        td6.appendTo(tr5);
                        td8.appendTo(tr5);
                        td17.appendTo(tr5);
                        td18.appendTo(tr5);


                        tr2.appendTo(txt9);
                        tr3.appendTo(txt9);
                        tr4.appendTo(txt9);
                        tr5.appendTo(txt9);
                        txt9.appendTo(td1);
                        txt1.appendTo(td1);
                        txt2.appendTo(td1);
                        td1.appendTo(tr);
                        td2.appendTo(tr);

                        tr.appendTo(jQ('#tbody-chart-type-method'));
                        CKEDITOR.replace(txt2Id);
                        global.maskInput();
                    }
                },
            }, 'chartTypeMethodList');
        });
        jQ('.note-ckeditor-field').each(function(){
            var idx = jQ(this).data('idx');
            CKEDITOR.replace('patient_chart_chartTypeMethods_'+ idx +'_note');
        });

        jQ('#patient_chart_chart_status').chained('#patient_chart_chart_type');
    },
    bindPatientChartFileForm: function() {
        if(jQ('.href-patient-chart-file-form').length > 0) {

            jQ('.href-patient-chart-file-form').unbind('click').bind('click', function(){

                var settings = {
                    url: statusReport.settings.statusReport_data_url,
                    data: dataSet,
                    type: 'POST',
                    success: function(json) {
                        if (json.success) {
                        }
                    }
                }

            });
        }
    },
    bindPatientChartFileFormAction: function() {

        jQ('.href-patient-chart-file-action').unbind('click.patientChartFileFormAction').bind('click.patientChartFileFormAction', function(){

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

            _form.find('.form-action').val(axn);
            var formData = new FormData(jQ('#form-patientChartFile')[0]);
            jQ.ajax({
                url: patient_chart_form.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) {
                        patient_chart_form.fileDataList.draw();
                        global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'success', json.successMessages);
                        modal.foundation('close');
                    } else {
                        _form.find('.progress').hide();
                        global.parseFlashMessages('#flash-messages-content-page', '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
            });
        });
    },
    bindPatientMedicalDiagnosisForm: function() {
        if(jQ('.href-patient-chart-medical-diagnosis-form').length > 0) {

            jQ('.href-patient-chart-medical-diagnosis-form').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_chart_form.settings.patient_diagnosis_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();
                        patient_chart_form.bindPatientMedicalDiagnosisFormAction();
                    }
                };

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

    bindPatientMedicalDiagnosisFormAction: function() {

        jQ('.href-patient-diagnosis-action').unbind('click.patientDiagnosisFormAction').bind('click.patientDiagnosisFormAction', function () {

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

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

            var settings = {
                url: patient_chart_form.settings.patient_diagnosis_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_chart_form.medicalDiagnosisDataList.draw();
                        global.parseFlashMessages('#flash-messages-content-page', 'success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.parseFlashMessages('#flash-messages-content-page', 'alert', json.errorMessages);
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindPatientMedicalDiagnosisMedicationForm: function() {
        for (let i = 0 ; i < patient_chart_form.settings.diagnosis_key ; i++){
            if(jQ('.href-patient-chart-medical-diagnosis-medication-form' + jQ('#patient-chart-medical-diagnosis-medication-datalist' + i).data('id')).length > 0) {

                jQ('.href-patient-chart-medical-diagnosis-medication-form' + jQ('#patient-chart-medical-diagnosis-medication-datalist' + i).data('id')).unbind('click').bind('click', function(){

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

                    global.ajaxCancel(requestName);

                    var settings = {
                        url: patient_chart_form.settings.patient_diagnosis_medication_formUrl + '/' + jQ(this).data('pd-id') + '/' + 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();
                            jQ(this).data('pd-id');
                            patient_chart_form.bindPatientMedicalDiagnosisMedicationFormAction();
                        }
                    };

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

    bindPatientMedicalDiagnosisMedicationFormAction: function() {

        jQ('.href-patient-diagnosis-medication-action').unbind('click.patientDiagnosisMedicationFormAction').bind('click.patientDiagnosisMedicationFormAction', function () {

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

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

            var settings = {
                url: patient_chart_form.settings.patient_diagnosis_medication_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        // modal.foundation('close');
                        // patient_chart_form.medicalDiagnosisMedicationDataList.draw();
                        global.parseFlashMessages('#flash-messages-content-page', 'success', json.successMessages);
                        location.reload();
                    } else {
                        global.parseFlashMessages('#flash-messages-content-page', 'alert', json.errorMessages);
                    }
                    global.formSubmittedReverse();
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindPatientChartProcedureForm: function() {
        if(jQ('.href-patient-chart-billing-procedure-form').length > 0) {

            jQ('.href-patient-chart-billing-procedure-form').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_chart_form.settings.billing_procedure_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();
                        var params = {
                            chart_type : patient_chart_form.settings.patient_chart_type ? patient_chart_form.settings.patient_chart_type : ''
                        };
                        jQ('#patient_chart_procedure_chart_procedure_desc').devbridgeAutocomplete('setOptions', {params: params});
                        // console.log(params);
                        global.autocomplete.bind(patient_chart_form.settings.chart_procedure_autocomplete, '#patient_chart_procedure_chart_procedure_desc', '#patient_chart_procedure_chart_procedure',
                            {

                                onSelect: function (c) {
                                    var amount = c.amount;

                                    jQ('#patient_chart_procedure_amount').val(global.numWithCommas(amount));
                                }

                            });
                        patient_chart_form.bindPatientChartProcedureFormAction();
                    }
                };

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

    bindPatientChartProcedureFormAction: function() {

        jQ('.href-patient-chart-billing-procedure-action').unbind('click.patientChartProcedureFormAction').bind('click.patientChartProcedureFormAction', function () {

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

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

            var settings = {
                url: patient_chart_form.settings.billing_procedure_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_chart_form.billingProcedureDataList.draw();
                        global.parseFlashMessages('#flash-messages-content-page', 'success', json.successMessages);
                    } else {
                        global.parseFlashMessages('#flash-messages-content-page', 'alert', json.errorMessages);
                    }
                    global.formSubmittedReverse();
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindPatientChartOtherProcedureForm: function() {
        if(jQ('.href-patient-chart-billing-other-procedure-form').length > 0) {

            jQ('.href-patient-chart-billing-other-procedure-form').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_chart_form.settings.billing_other_procedure_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();
                        patient_chart_form.bindPatientChartOtherProcedureFormAction();
                    }
                };

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

        jQ('.href-patient-chart-billing-other-procedure-action').unbind('click.patientChartOtherProcedureFormAction').bind('click.patientChartOtherProcedureFormAction', function () {


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

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

            var settings = {
                url: patient_chart_form.settings.billing_other_procedure_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_chart_form.billingOtherProcedureDataList.draw();
                        global.parseFlashMessages('#flash-messages-content-page', 'success', json.successMessages);
                    } else {
                        global.parseFlashMessages('#flash-messages-content-page', 'alert', json.errorMessages);
                    }
                    global.formSubmittedReverse();
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindPatientChartPaymentForm: function() {
        if(jQ('.href-patient-chart-payment-form').length > 0) {

            jQ('.href-patient-chart-payment-form').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_chart_form.settings.payment_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();
                        patient_chart_form.bindPatientChartPaymentFormAction();
                    }
                };

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

        jQ('.href-patient-chart-payment-action').unbind('click.patientChartPaymentFormAction').bind('click.patientChartPaymentFormAction', function () {


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

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

            var settings = {
                url: patient_chart_form.settings.payment_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_chart_form.paymentDataList.draw();
                        global.parseFlashMessages('#flash-messages-content-page', 'success', json.successMessages);
                    } else {
                        global.parseFlashMessages('#flash-messages-content-page', 'alert', json.errorMessages);
                    }
                    global.formSubmittedReverse();
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindPatientChartNoteForm: function() {
        if(jQ('.href-patient-chart-note-form').length > 0) {

            jQ('.href-patient-chart-note-form').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_chart_form.settings.patient_chart_note_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();
                        patient_chart_form.bindPatientChartNoteFormAction();
                    }
                };

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

    bindPatientChartNoteFormAction: function() {

        jQ('.href-patient-chart-note-action').unbind('click.patientNoteFormAction').bind('click.patientNoteFormAction', function () {

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

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

            var settings = {
                url: patient_chart_form.settings.patient_chart_note_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        global.parseFlashMessages('#flash-messages-content-page', 'success', json.successMessages);
                        patient_chart_form.noteDataList.draw();
                    } else {
                        global.parseFlashMessages('#flash-messages-content-page', 'alert', json.errorMessages);
                    }
                    global.formSubmittedReverse();
                }
            };

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

    jQ('#patient_chart_is_endorsed').unbind('click').bind('click', function () {
        if(this.checked){
            jQ('#patient_chart_endorsed_by').fadeIn(300);
            jQ('#label_status').fadeIn(300);
            jQ('#label_severity').fadeIn(300);
            jQ('#patient_chart_ticket_status').fadeIn(300);
            jQ('#patient_chart_ticket_severity').fadeIn(300);
            jQ('.cc_form').fadeIn(300);
            jQ('.patient_chart_au_accountUser_fullName').fadeIn(300);
            jQ('.btn-account-user-list-remove').fadeIn(300);
        }else{
            jQ('#patient_chart_endorsed_by').slideUp(300);
            jQ('#patient_chart_endorsed_by').val(null);
            jQ('#label_status').slideUp(300);
            jQ('#patient_chart_ticket_status').slideUp(300);
            jQ('.cc_form').slideUp(300);
            jQ('.patient_chart_au_accountUser_fullName').slideUp(300);
            jQ('.btn-account-user-list-remove').slideUp(300);
            jQ('#patient_chart_ticket_status').val(null);
            jQ('#label_severity').slideUp(300);
            jQ('#patient_chart_ticket_severity').slideUp(300);
            jQ('#patient_chart_ticket_severity').val(null);
        }
    });

    if(jQ('#patient_chart_is_endorsed').prop('checked')){
        jQ('#patient_chart_endorsed_by').fadeIn(300);
        jQ('#label_status').fadeIn(300);
        jQ('#patient_chart_ticket_status').fadeIn(300);
        jQ('#label_severity').fadeIn(300);
        jQ('#patient_chart_ticket_severity').fadeIn(300);
    }
    },
    bindCcAdd: function() {
        let idx = jQ('#tbody-account-user-list tr').length;

        const bindRemove = function() {
            jQ('.btn-account-user-list-remove').unbind('click').bind('click', function() {
                const tr = jQ(this).parent().parent();
                tr.find('.patient_chart_au_accountUser_fullName').devbridgeAutocomplete('dispose');
                tr.remove();
                var au_id = jQ(this).parent().parent().find('.patient_chart_au_accountUser').val();
                var index = patient_chart_form.settings.account_user_ids.indexOf(au_id);
                if (index !== -1) patient_chart_form.settings.account_user_ids.splice(index, 1);
            });
        };
        bindRemove();

        jQ('#tbody-account-user-list').each(function(i){

            // We need to use enclosure in because onSelect listener takes only the last idx
            (function(idx){
                global.autocomplete.bind(patient_chart_form.settings.account_user_autocomplete_url, 'input[name="patient_chart[patientChartCcs][' + idx + '][patientChartCcs_accountUser_fullName]"]', 'input[name="patient_chart[patientChartCcs][' + idx + '][accountUser]"]', {
                    onSelect: function (d) {
                        patient_chart_form.settings.account_user_ids.push(d.id);
                    }
                });
            })(i);
        });

        jQ('#btn-patient-chart-add-cc').unbind('click').bind('click', function(){
            idx++;
            const trHtml =
                '<tr>' +
                '<td>' +
                '<input name="patient_chart[patientChartCcs][' + idx + '][patientChartCcs_accountUser_fullName]" type="text" class="patient_chart_au_accountUser_fullName" placeholder="CC" />' +
                '<input name="patient_chart[patientChartCcs][' + idx + '][accountUser]" type="hidden" class="patient_chart_au_accountUser" />' +
                '</td>' +
                '<td>' +
                '<a href="javascript:void(0)" class="btn-account-user-list-remove">X</a>' +
                '<input name="patient_chart[patientChartCcs][' + idx + '][id]" type="hidden" class="patientChart_au_id" />' +
                '</td>' +
                '</tr>';

            jQ(trHtml).appendTo(jQ('#tbody-account-user-list'));

            // We need to use enclosure in because onSelect listener takes only the last idx
            (function(idx){

                global.autocomplete.bind(patient_chart_form.settings.account_user_autocomplete_url, 'input[name="patient_chart[patientChartCcs][' + idx + '][patientChartCcs_accountUser_fullName]"]', 'input[name="patient_chart[patientChartCcs][' + idx + '][accountUser]"]', {
                    onSelect: function (d) {
                        patient_chart_form.settings.account_user_ids.push(d.id);
                    }
                });
            })(idx);
            bindRemove();
        });
    },
    bindNoteTemplate: function () {
        jQ('#patient_chart_note_type').unbind('change').bind('change', function () {
            if (jQ(this).val() == 'Template') {
                jQ('#patient_chart_note_template_description').removeClass('hide');
            } else {
                jQ('#patient_chart_note_template_description').addClass('hide');
            }
        });

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