var patient_detail = {
    settings: {
        Ids: [],
        tranType: '',
        patient_id: '',
        patient_id_decoded: '',
        patient_appointment_id: '',
        patient_appointment_id_decoded: '',
        chart_ajaxUrl: '',
        file_ajaxUrl: '',
        fileFromImport_ajaxUrl: '',
        chart_formUrl: '',
        file_formUrl: '',
        file_formActionUrl: '',
        medical_diagnosis_ajaxUrl: '',
        medical_diagnosis_medication_ajaxUrl: '',
        diagnosis_key: '',
        insurance_ajaxUrl: '',
        patient_insurance_formUrl: '',
        patient_insurance_formActionUrl: '',
        note_ajaxUrl: '',
        note_clinical_ajaxUrl: '',
        note_billing_ajaxUrl: '',
        note_appointment_ajaxUrl: '',
        note_specialist_ajaxUrl: '',
        note_letter_ajaxUrl: '',
        patient_note_formUrl: '',
        patient_note_formActionUrl: '',
        patient_billing_ajaxUrl: '',
        patient_billing_formUrl: '',
        patient_billing_formActionUrl: '',
        patient_billing_void_formActionUrl: '',
        patient_payment_ajaxUrl: '',
        patient_payment_formUrl: '',
        patient_payment_formActionUrl: '',
        patient_payment_void_formActionUrl: '',
        patient_payment_billing_breakdownUrl: '',
        schedule_ajaxUrl: '',
        appointmentNoticeFax_ajaxUrl: '',
        patient_letter_formActionUrl: '',
        patient_letter_formUrl: '',
        patient_letter_ajaxUrl: '',
        patient_letter_pdf: '',
        patient_appointment_notice_fax_pdf: '',
        patient_appointment_notice_fax_formUrl: '',
        patient_letter_preview: '',
        patient_referring_health_facility_ajaxUrl: '',
        patient_referring_health_facility_formUrl: '',
        patient_referring_health_facility_formActionUrl: '',
        patient_referring_provider_ajaxUrl: '',
        patient_referring_provider_formUrl: '',
        patient_referring_provider_formActionUrl: '',
        patient_history_ajaxUrl: '',
        patient_red_flag_ajaxUrl: '',
        patient_red_flag_formUrl: '',
        patient_red_flagTab_reloadAction: '',
        patient_red_flag_formActionUrl: '',
        patient_health_facility_ajaxUrl: '',
        patient_health_facility_formUrl: '',
        patient_health_facility_formActionUrl: '',
        patient_specialist_ajaxUrl: '',
        patient_specialist_formUrl: '',
        patient_specialist_formActionUrl: '',

        patient_services_ajaxUrl: '',
        patient_services_formUrl: '',
        patient_services_formActionUrl: '',

        patient_services_other_ajaxUrl: '',
        patient_services_other_formUrl: '',
        patient_services_other_formActionUrl: '',

        patient_billing_refund_ajaxUrl: '',
        patient_billing_refund_formUrl: '',
        patient_billing_refund_formActionUrl: '',
        patient_billing_refund_breakdownUrl: '',

        patient_rental_ajaxUrl: '',
        patient_rental_formUrl: '',
        patient_rental_formActionUrl: '',

        patient_reminder_ajaxUrl: '',
        patient_reminder_formUrl: '',
        patient_reminder_formActionUrl: '',

        patient_treatment_consideration_ajaxUrl: '',
        patient_treatment_consideration_formUrl: '',
        patient_treatment_consideration_formActionUrl: '',

        patient_treatment_plan_ajaxUrl: '',
        patient_treatment_plan_formUrl: '',
        patient_treatment_plan_formActionUrl: '',

        patient_letter_note_formUrl: '',
        patient_letter_note_formActionUrl: '',

        patient_ticket_ajaxUrl: '',
        accountUser_autocompleteUrl: '',
        healthFacility_autocompleteUrl: '',

        patient_transfer_formUrl: '',
        patient_transfer_formActionUrl: '',

        letter_template_data_url: '',
        patient_linked_referring_health_facility_and_provider_formUrl: '',

        note_template_autocomplete_url: '',
        note_template_data_url: '',

        patient_purchased_items_ajaxUrl: '',

        patient_email_ajaxUrl: '',
        patient_email_formUrl: '',
        patient_email_formActionUrl: '',
        email_template_autocomplete_url: '',

        invoiceNo: '',
        letterId: '',
        patientLocation: [],
        noteTemplateAccess: '',

        // fax_cover_body : '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;"><div><strong>Notes:</strong></div>' +
        //     '<div style="margin: 0;">Good day, {{RECEVIER-FULLNAME}}.</div>' +
        //     '<div style="margin: 0;">Thank you for your referral.</div>' +
        //     '<div style="margin: 0;">Please find attached letter regarding your patient {{PATIENT-FULLNAME}}.</div>' +
        //     '<div style="margin: 0;">Kind Regards,</div>' +
        //     '<br>' +
        //     '<div style="margin: 0;">{{USERDATA-FULLNAME}}<br>Dynamic Sleep & Respiratory Care</div></div>',

        fax_cover_body : '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;"><div><strong>Notes:</strong></div>' +
            '<p style="margin: -2px;">Good day, {{RECEVIER-FULLNAME}}.</p>' +
            '<p style="margin: -2px;">Thank you for your referral. </p>' +
            '<p style="margin: -2px;">Please find attached a letter regarding your patient {{PATIENT-FULLNAME}}. </p>' +
            '<p style="margin: -2px;">Kind Regards, </p>' +
            '<br>' +
            '<div style="margin: 0;">{{USERDATA-FULLNAME}}<br>Dynamic Sleep & Respiratory Care</div></div>',

        fax_cover_body_prescription : '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;"><div><strong>Notes:</strong></div>' +
            '<p style="margin: -2px;">Good day, {{RECEVIER-FULLNAME}}.</p>' +
            '<p style="margin: -2px;">Thank you for your referral. </p>' +
            '<p style="margin: -2px;">Please find attached <b>SLEEP STUDY RESULT</b> regarding your patient {{PATIENT-FULLNAME}}. </p>' +
            '<p style="margin: -2px;">Kind Regards, </p>' +
            '<br>' +
            '<div style="margin: 0;">{{USERDATA-FULLNAME}}<br>Dynamic Sleep & Respiratory Care</div>',

        fax_cover_body_sleep_specialist : '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;"><div><strong>Notes:</strong></div>' +
            '<p style="margin: -2px;">Good day, {{RECEVIER-FULLNAME}}.</p>' +
            '<p style="margin: -2px;">Thank you for your referral. </p>' +
            '<p style="margin: -2px;">Please find attached <b>SLEEP SPECIALIST REFERRAL FORM</b> of your patient {{PATIENT-FULLNAME}}. </p>' +
            '<p style="margin: -2px;">Kind Regards, </p>' +
            '<br>' +
            '<div style="margin: 0;">{{USERDATA-FULLNAME}}<br>Dynamic Sleep & Respiratory Care</div>',

        fax_cover_acknowledgement : '<h3 style="font-size:20px;">Dear {{RECEVIER-FULLNAME}},</h3>' +
            '<h3 style="font-size:20px;">We have received your referral. We are currently doing our best to contact and book the patient for Home Sleep Apnea Testing (HSAT).</h3>' +
            '<h3 style="font-size:20px;">We will be sending an Appointment Notice once the patient have been booked.</h3><br>' +
            '<h3 style="font-size:20px;">Thank you!</h3>',

        patient_letter_types: {
            'Prescription (FRSC)' : {
                body: null,
                recommendation: '<div>Interpreting Physician: {{INTERPRETATION-DOCTOR}}</div>'
            },
            'Prescription (FRSC) v2' : {
                body: null,
                recommendation: ''
            },
            'Alice Night One (FRSC)' : {
                body: null,
                recommendation: ''
            },
            'General Prescription (FRSC)' : {
                body: null,
            },
            'Prescription (PSS)' : {
                body: null,
                recommendation: '<div>Interpreting Physician: {{INTERPRETATION-DOCTOR}}</div>'
            },
            'Refusal of Care Against Medical Advice (FRSC)' : {
                body: null
            },
            'HSAT - No Book (FRSC)' : {
                body: null
            },
            'HSAT Refuse to repeat HSAT (FRSC)' : {
                body: null
            },
            'HSAT Unable to Contact (FRSC)' : {
                body: null
            },
            'HST Refuse - Wants to speak with their Doctor first (FRSC)' : {
                body: null
            },
            'HST Refuse - Had HSAT Already (FRSC)' : {
                body: null
            },
            'HST Refuse - No Coverage-No Insurance (FRSC)' : {
                body: null
            },
            'Negative OSA (FRSC)' : {
                body: null
            },
            'Negative OSA (No RDI) (FRSC)' : {
                body: null
            },
            'Oximetry Inconclusive (FRSC)' : {
                body: null
            },
            'Oximetry Negative (FRSC)' : {
                body: null
            },
            'FAX for Referral Acknowledgement (FRSC)' : {
                body: null
            },
            'No Booking Under 18 years of age (FSRC)' : {
                body: null
            },
            'Acknowledgement' : {
              body: '<h3 style="font-size:20px;">Dear {{RECEVIER-FULLNAME}},</h3>' +
                  '<h3 style="font-size:20px;">We have received your referral. We are currently doing our best to contact and book the patient for Home Sleep Apnea Testing (HSAT).</h3>' +
                  '<h3 style="font-size:20px;">We will be sending an Appointment Notice once the patient have been booked.</h3><br>' +
                  '<h3 style="font-size:20px;">Thank you!</h3>',
            },
            'Adherence': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.<br></p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I wanted to provide you with an update on {{PATIENT-FIRSTNAME}}, who has now been on CPAP Therapy for __ months. {{PATIENT-FIRSTNAME}}\’s Initial AHI = __ and has currently decreased to ___.  We are encouraging the patient to have more consistent usage. Please see the attached Summary Adherence Report for more details.</p>' +
                    '</div>' +              
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +  
                    '<p style="margin:2px">We felt it was important to give you an update. If there is anything we can do to further support your patient, please let us know. We will continue to monitor {{PATIENT-FIRSTNAME}} via our Sleep Assure Program.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'AISH (Cgy)': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Thank you for your referral. We would like to inform you that we weren’t able to book {{PATIENT-FIRSTNAME}} for the Home Sleep Apnea Test (HSAT). We have contacted {{PATIENT-FIRSTNAME}} case worker and they indicated that {{PATIENT-GENDER}} will need a Level I PSG. If an AISH patients BMI is over 37 or they have a history of cardiovascular disease they would also need a Level I PSG and cannot proceed with a HSAT.</p>' +
                    '</div>'
            },
            'AISH (Edm)': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Thank you for your referral. We would like to inform you that we weren’t able to book {{PATIENT-FIRSTNAME}} for the Home Sleep Apnea Test (HSAT). We have contacted {{PATIENT-FIRSTNAME}} case worker and they indicated that {{PATIENT-GENDER}} will need a Level I PSG. If an AISH patients BMI is over 37 or they have a history of cardiovascular disease they would also need a Level I PSG and cannot proceed with a HSAT.</p>' +
                    '</div>'
            },
            // 'ALBERTA WORKS (Cgy)':{
            //     body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">Thank you for your referral. We would like to inform you that we weren\’t able to book {{PATIENT-FULLNAME}} for the Home Sleep Apnea Test (HSAT) at this time as {{PATIENT-GENDER}} is under ALBERTA WORKS. If {{PATIENT-FULLNAME}}\’s results come back positive, {{PATIENT-GENDER}} would need funding in order to purchase {{PATIENT-GENDER3}} own CPAP machine. In order for {{PATIENT-GENDER2}} to be funded by the government, {{PATIENT-GENDER}} would require a Level 1 Sleep Study. We have advised {{PATIENT-FULLNAME}} to contact {{PATIENT-GENDER3}} case worker regarding this matter. </p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">In the past, to have the Level 1 PSG performed, you could contact the Sleep Disorders Lab at the Foothlls Medical Centre, 1403 29St NW, Calgary, AB T2N 2T9 at 403-944-2404 or Fax 403-270-2718 for a Consult Request. </p>' +
            //         '</div>'
            // },
            // 'ALBERTA WORKS (Edm)':{
            //     body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">Thank you for your referral. We would like to inform you that we weren\’t able to book {{PATIENT-FULLNAME}} for the Home Sleep Apnea Test (HSAT) at this time as {{PATIENT-GENDER}} is under ALBERTA WORKS. If {{PATIENT-FULLNAME}}\’s results come back positive, {{PATIENT-GENDER}} would need funding in order to purchase his own CPAP machine. In order for {{PATIENT-GENDER2}} to be funded by the government, {{PATIENT-GENDER}} would require a Level 1 Sleep Study. We have advised {{PATIENT-FULLNAME}} to contact {{PATIENT-GENDER3}} case worker regarding this matter. </p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">In the past, to have the Level 1 PSG performed, you could contact the Sleep Disorders Lab at the Edmonton General Hospital Department 8C, 11111 Jasper Ave at 780-342-8310 or Fax 780-342- 8323 for a Consult Request. </p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">While we work towards offering Level 1 PSG Studies, an alternative may be a private sleep facility, such as Advanced Respiratory Care in Sherwood Park, 780-449-1434 or the Northern Alberta Sleep Clinic,780-756-5350.</p>' +
            //         '</div>'
            // },
            'CPAP Pressure Change':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to give you an update regarding {{PATIENT-FIRSTNAME}}. {{PATIENT-GENDER4}} came in to our clinic to be set-up on CPAP Therapy on _________. {{PATIENT-FIRSTNAME}}\’s current CPAP therapeutic pressure range is __cmH2O to __cmH2O. Based on the download, {{PATIENT-FIRSTNAME}} is maxing out {{PATIENT-GENDER3}} pressure. We suggest increasing the maximum pressure to __cmH2O.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We have been able to adjust {{PATIENT-FIRSTNAME}} maximum CPAP pressure now and will continue to {{PATIENT-GENDER3}} progress via Sleep Assure Program.</p>' +
                    '</div>'
            },
            'CPAP refuse -- Medical issues':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on _________ and based on the interpretation provided by our Sleep Physician Dr. _____________, {{PATIENT-FIRSTNAME}}\’s study indicated _________________ Obstructive Sleep Apnea (AHI=__ and RDI=__).</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We advised {{PATIENT-FIRSTNAME}} of {{PATIENT-GENDER3}} results and {{PATIENT-GENDER}} elected not to go forward with an evaluation of CPAP therapy at this time. {{PATIENT-FIRSTNAME}} stated that {{PATIENT-GENDER}} has other medical concerns at this time that need to be addressed. We felt it was important to make you aware of the situation. If {{PATIENT-FIRSTNAME}} changes {{PATIENT-GENDER3}} mind in the future, we would be happy to extend {{PATIENT-GENDER2}} a CPAP Evaluation anytime.</p>' +
                    '</div>'
            },
            'CPAP refuse -- No Funds-No Insurance-Note About Discussion Regarding Financing Options':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on _______ and based on the interpretation provided by our Sleep Physician Dr. ___________, {{PATIENT-FIRSTNAME}}\’s study indicated ________________ Obstructive Sleep Apnea (AHI=__ and RDI=__).</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We advised {{PATIENT-FIRSTNAME}} of {{PATIENT-GENDER3}} results and {{PATIENT-GENDER}} elected not to go forward with a CPAP Evaluation at this time because {{PATIENT-GENDER}} was concerned that {{PATIENT-GENDER}} would not be able to afford the treatment. We offered an interest free payment plan as well as long term rental option, however {{PATIENT-FIRSTNAME}} was not interested and decided to delay treatment.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated OSA and suggested that {{PATIENT-FIRSTNAME}} consider alternative treatments including an Oral Appliance if {{PATIENT-GENDER}} is unable to tolerate CPAP. We are now also offering Oventus Optima Oral Appliances through our Dentist Dr. Al-Ashi.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} was also encouraged to follow up with you in the near future. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'CPAP refuse -- Wants alternative therapy -consult ENT':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on ________ and based on the interpretation provided by our Sleep Physician Dr. _______________, {{PATIENT-FIRSTNAME}}\’s study indicated _______________________ Obstructive Sleep Apnea (AHI=__ and RDI=__).</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We advised {{PATIENT-FIRSTNAME}} of {{PATIENT-GENDER3}} results and {{PATIENT-GENDER}} elected not to go forward with an evaluation of CPAP therapy at this time. {{PATIENT-FIRSTNAME}} stated that {{PATIENT-GENDER}} would rather seek an ENT consult and will call us back if {{PATIENT-GENDER}} wants to be rebooked.</p>' +
                    '</div>'
            },
            'CPAP refuse -- Wants alternative therapy - Oral Appliance':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on ________ and based on the interpretation provided by our Sleep Physician Dr. _____________, {{PATIENT-FIRSTNAME}}\’s study indicated _____________________ Obstructive Sleep Apnea (AHI=__ and RDI=__).</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We advised {{PATIENT-FIRSTNAME}} of {{PATIENT-GENDER3}} results and {{PATIENT-GENDER}} elected not to go forward with CPAP evaluation at this time. Instead, {{PATIENT-FIRSTNAME}} wanted to be booked to see our Dentist Dr. Al-Ashi about an Oral Appliance. We are now able to offer Oventus Optima Oral Appliance to those patients unable to tolerate CPAP Therapy.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} was also encouraged to follow up with you in the near future. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'CPAP refuse -- Wants to Talk to Dr. prior to starting therapy (Very Mild to Moderate)': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on _________ and based on the interpretation provided by our Sleep Physician Dr. __________, {{PATIENT-FIRSTNAME}}\’s study indicated ______________________ Obstructive Sleep Apnea (AHI=__ and RDI=__). We informed {{PATIENT-FIRSTNAME}} of {{PATIENT-GENDER3}} results and {{PATIENT-GENDER}} elected not to go forward with a CPAP Evaluation at this time. {{PATIENT-GENDER4}} wants to speak with you first before beginning therapy.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated Obstructive Sleep Apnea and suggested that {{PATIENT-FIRSTNAME}} consider alternatives to CPAP if {{PATIENT-GENDER}} is unable to tolerate CPAP Therapy. We now also offer Oventus Optima Oral Appliances through Dr. Al-Ashi.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'CPAP refuse -- Wants to Talk to Dr. prior to starting therapy (Severe & Very Severe)': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on ___________ and based on the interpretation provided by our Sleep Physician Dr. ___________, {{PATIENT-FIRSTNAME}}\’s study indicated __________________________ Obstructive Sleep Apnea (AHI=__ and RDI=__). We informed {{PATIENT-FIRSTNAME}} of {{PATIENT-GENDER3}} results and {{PATIENT-GENDER}} elected not to go forward with a CPAP Evaluation at this time. {{PATIENT-GENDER4}} wants to speak with you first before beginning therapy.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated Obstructive Sleep Apnea and suggested that {{PATIENT-FIRSTNAME}} consider alternatives to CPAP if {{PATIENT-GENDER}} is unable to tolerate CPAP Therapy. Due to the severity of {{PATIENT-FIRSTNAME}}\’s Sleep Apnea a referral to one of our Sleep Specialists is also recommended.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'CPAP refuse -- Wants to think about it (Severe & Very Severe)': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care. </p>'+
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on __________ and based on the interpretation provided by our Sleep Physician Dr. ______________, {{PATIENT-FIRSTNAME}}\’s study indicated ___________________________ Obstructive Sleep Apnea (AHI=__ and RDI=__).</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We advised {{PATIENT-FIRSTNAME}} of {{PATIENT-GENDER3}} results and {{PATIENT-GENDER}} wanted to think about it before going forward with an Evaluation of CPAP at this time.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated Obstructive Sleep Apnea and suggested that {{PATIENT-FIRSTNAME}} also consider alternative treatments if {{PATIENT-GENDER}} is unable to tolerate CPAP Therapy.  Due to the severity of {{PATIENT-FIRSTNAME}}\’s Sleep Apnea a referral to one of our Sleep Specialists is also recommended.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} was also encouraged to follow up with you in the near future. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>',
                fax_cover : '<p><strong>Notes:</strong></p>\n' +
                    '<p>Good day, {{ receiverFullName }}.</p>\n' +
                    '<p>Thank you for your referral.</p>\n' +
                    '<p>Please find attached letter regarding your patient {{PATIENT-FULLNAME}}.</p>\n' +
                    '<p>Kind regards,</p>\n' +
                    '<br>\n' +
                    '<p style="margin:0;">{{USERDATA-FULLNAME}}</p>\n' +
                    '<p style="margin:0;">Dynamic Sleep Respiratory Care</p>'
            },
            'CPAP refuse -- Wants to think about it (Very Mild to Moderate)': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on _________ and based on the interpretation provided by our Sleep Physician Dr. ____________, {{PATIENT-FIRSTNAME}}\’s study indicated ___________ Obstructive Sleep Apnea (AHI=__ and RDI=__).</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We advised {{PATIENT-FIRSTNAME}} of {{PATIENT-GENDER3}} results and {{PATIENT-GENDER}} wanted to think about it before going forward with an Evaluation of CPAP at this time.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated Obstructive Sleep Apnea and suggested that {{PATIENT-FIRSTNAME}} also consider alternative treatments including an Oral Appliance if {{PATIENT-GENDER}} is unable to tolerate CPAP Therapy. We are now working with Dr. Al-Ashi a Doctor to offer Oventus Optima Oral Appliances.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} was also encouraged to follow up with you in the near future. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>',
                fax_cover : '<p><strong>Notes:</strong></p>\n' +
                    '<p>Good day, {{ receiverFullName }}.</p>\n' +
                    '<p>Thank you for your referral.</p>\n' +
                    '<p>Please find attached letter regarding your patient {{PATIENT-FULLNAME}}.</p>\n' +
                    '<p>Kind regards,</p>\n' +
                    '<br>\n' +
                    '<p style="margin:0;">{{USERDATA-FULLNAME}}</p>\n' +
                    '<p style="margin:0;">Dynamic Sleep Respiratory Care</p>'
            },
            'CPAP no book':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on _______ and based on the interpretation provided by our Sleep Physician Dr. _____________, {{PATIENT-FIRSTNAME}}\’s study indicated _________________________ Obstructive Sleep Apnea (AHI=__ and RDI=__).</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We have tried contacting {{PATIENT-FIRSTNAME}} several times and have been unsuccessful in booking {{PATIENT-GENDER2}} for CPAP Setup/Therapy Education. We have left multiple messages and still have not heard back from {{PATIENT-GENDER2}}. We felt it was important to make you aware of the situation and provide an update. If {{PATIENT-FIRSTNAME}} contacts us in the future, we would be happy to extend a 2 week CPAP Evaluation.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} was also encouraged to follow up with you in the near future. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'CPAP no-rebook':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on ___________ and based on the interpretation provided by our Sleep Physician Dr. _____________, {{PATIENT-FIRSTNAME}}\’s study indicated _________________________ Obstructive Sleep Apnea (AHI=__ and RDI=__). We have tried several times to schedule {{PATIENT-FIRSTNAME}} for a CPAP evaluation, however {{PATIENT-GENDER}} has not shown up to {{PATIENT-GENDER3}} previous appointments.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We have tried to get in touch with {{PATIENT-GENDER2}} again to reschedule but have been unsuccessful. We felt it was important to make you aware of the situation and provide an update. If {{PATIENT-FIRSTNAME}} contacts us in the future, we would be happy to extend a 2-week CPAP Evaluation.</p>' +
                    '</div>'
            },
            'CPAP -- refused not interested (Severe to Very Severe)': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on ________ and based on the interpretation provided by our Sleep Physician Dr. __________, {{PATIENT-FIRSTNAME}}\’s study indicated __________ Obstructive Sleep Apnea (AHI=__ and RDI=__).</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} advised us that {{PATIENT-GENDER}} is not interested in evaluating CPAP Therapy at this time. We felt it was important to make you aware of the situation and provide an update. If {{PATIENT-FIRSTNAME}} changes {{PATIENT-GENDER3}} mind in the future, we would be happy to extend a CPAP Evaluation.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated OSA and suggested that {{PATIENT-FIRSTNAME}}\’s consider alternative treatments including an Oral Appliance if {{PATIENT-GENDER}} is unable to tolerate CPAP.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Due to the severity of {{PATIENT-FIRSTNAME}}\’s Sleep Apnea a referral to one of our Sleep Specialists is also recommended.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} was also encouraged to follow up with you in the near future. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'CPAP -- refused not interested (Very Mild to Moderate)': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} had a Home Sleep Apnea Test (HSAT) on ____________ and based on the interpretation provided by our Sleep Physician Dr. ________, {{PATIENT-FIRSTNAME}}\’s study indicated _______________ Obstructive Sleep Apnea (AHI=__ and RDI=__). </p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We advised {{PATIENT-FIRSTNAME}} of {{PATIENT-GENDER3}} results and {{PATIENT-GENDER}} wanted to think about it before going forward with an Evaluation of CPAP at this time.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated Obstructive Sleep Apnea and suggested that {{PATIENT-FIRSTNAME}} also consider alternative treatments including an Oral Appliance if {{PATIENT-GENDER}} is unable to tolerate CPAP Therapy. We are now working with Dr. Al-Ashi a Doctor to offer Oventus Optima Oral Appliances.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} was also encouraged to follow up with you in the near future. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'HSAT Refuse -- Had HSAT already':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We were able to talk to {{PATIENT-FIRSTNAME}} and {{PATIENT-GENDER}} advised us that {{PATIENT-GENDER}} does not want to go forward with testing for Obstructive Sleep Apnea with us because {{PATIENT-GENDER}} already had the test with a different company.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'HSAT Refuse -- No coverage-No Insurance': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} came to the Clinic and once {{PATIENT-GENDER}} found out there could be a cost associated with being treated post screening {{PATIENT-GENDER}} declined testing.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'HSAT Refuse -- Not interested at this time. Wants to go back and speak with their Doctor first': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} has indicated that {{PATIENT-GENDER}} is not interested in taking part in a Home Sleep Apnea Test (HSAT) at this time. {{PATIENT-GENDER4}} would like to speak with you first to clarify the need and discuss options.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'HSAT Refuse to Repeat HSAT': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">There was not enough sleep data for our Sleep Doctor to interpret the test. We were able to talk to {{PATIENT-FIRSTNAME}} and {{PATIENT-GENDER}} advised us that {{PATIENT-GENDER}} does not want to repeat testing at this time.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'HSAT No Book': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We have tried contacting {{PATIENT-FIRSTNAME}} several times and have been unsuccessful in booking {{PATIENT-GENDER2}} for a Home Sleep Apnea Test (HSAT). We have left multiple messages and still have not heard back from {{PATIENT-GENDER2}}.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of this situation and provide an update. If you discover that {{PATIENT-GENDER}} would still like to be tested, please have {{PATIENT-GENDER2}} call us as we would be happy to proceed with testing.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'HSAT No Rebook': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We have tried several times to schedule {{PATIENT-FIRSTNAME}} for a Home Sleep Apnea Test (HSAT), however {{PATIENT-GENDER}} has not shown up to {{PATIENT-GENDER3}} appointments. We have tried to get in touch with {{PATIENT-GENDER2}} again to reschedule but have been unsuccessful.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'HSAT Unable to Contact': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We have tried contacting {{PATIENT-FULLNAME}} several times and have been unsuccessful in booking {{PATIENT-GENDER2}} for a Home Sleep Apnea Test (HSAT) because the contact number provided is not in service. We also contacted your office to get an alternative contact number, but the same contact information was provided.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of this situation and provide an update. If you discover that {{PATIENT-GENDER}} would still like to be tested, please have {{PATIENT-GENDER2}} call us as we would be happy to proceed with testing.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Indian Affairs': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We would like to inform you that we were unable to book {{PATIENT-FIRSTNAME}} for the Home Sleep Apnea Test (HSAT) at this time, as {{PATIENT-GENDER}} is under Indian Affairs. Unfortunately, our Clinic does not have approval to deal with this type of insurance at this time. We have directed {{PATIENT-FIRSTNAME}} to Medigas or Vital Aire as both these companies have contract with Indian Affair patients.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Negative OSA (No RDI)':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that your patient {{PATIENT-FIRSTNAME}} recently had a Home Sleep Apnea Test (HSAT) performed on _____________.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Our Sleep Physician Dr. _______________ has indicated clinically significant sleep disordered breathing was not identified. {{PATIENT-FIRSTNAME}} is considered negative for Obstructive Sleep Apnea (AHI=2) and does not require treatment at this time.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Negative OSA (RDI and AHI)':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> We are writing to inform you that {{PATIENT-FIRSTNAME}} has recently had a Home Sleep Apnea Test (HSAT) performed on _________________.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Our Sleep Physician Dr. __________________ did not identify any clinically significant sleep disordered breathing. Therefore, the patient is considered negative for Obstructive Sleep Apnea (AHI=__, RDI=__), and does not require treatment at this time.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Negative OSA':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> We are writing to inform you that {{PATIENT-FIRSTNAME}} has recently had a Home Sleep Apnea Test (HSAT) performed on _________________.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Our Sleep Physician Dr. ____________ has indicated clinically significant sleep disordered breathing was not identified. {{PATIENT-FIRSTNAME}} is considered negative for Obstructive Sleep Apnea (AHI=__, RDI=__), and does not require treatment at this time.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Negative Inconclusive':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that your patient {{PATIENT-FIRSTNAME}} recently had a Home Sleep Apnea Test (HSAT) performed on _____________.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">The screen for Obstructive Sleep Apnea came back negative however due to the symptoms reported the diagnosis is inconclusive and it’s recommended that your patient see our Sleep Specialist in Clinic for further assessment. There is a possibility that your patient has a different sleep disorder and might need further screening (Level 1 PSG).</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">If your original referral was on the old version of the DSRC Referral Form we will attach a Specialist Referral Form for you to sign. If your Referral was on the newly updated DSRC Referral then we won’t need to send you the additional paperwork prior to booking.</p>' +
                    '</div>'
            },
            'Oximetry Inconclusive':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> {{PATIENT-FIRSTNAME}} completed an Overnight Oximetry done on ____________. Our Sleep Physician Dr. ___________________ has reviewed and interpreted the Oximetry Study.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> Please see the interpretation page included. Dr. ___________ found that {{PATIENT-FIRSTNAME}}\’s results were inconclusive of Obstructive Sleep Apnea with recommendations including considering a Level 1 PSG if symptoms persist. There was also mention of optimization of sleep hygiene and how positional therapy or side lying sleep may be of benefit.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Oximetry Negative':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> {{PATIENT-FIRSTNAME}} completed an Overnight Oximetry done on _____________. Our Sleep Physician Dr. ___________________ has reviewed and interpreted the Oximetry Study. Dr. __________ found that Clinically Significant Sleep Disordered Breathing was NOT identified. {{PATIENT-FIRSTNAME}} is considered negative for OSA and does not require treatment at this time.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Oximetry Positive':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} completed an Overnight Oximetry done on __________________. Our Sleep Physician Dr. ______________ has reviewed and interpreted the Oximetry Study.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> Please see the interpretation page included. Dr. ____________ found that {{PATIENT-GENDER3}} results indicated evidence of Obstructive Sleep Apnea with recommendations including considering an ENT consult for examination of the upper airway or a Level 1 PSG (sleep study). Also, there was mention of optimization of sleep hygiene and how positional therapy or side lying sleep may be of benefit.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Oximetry Refuse':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We were able to talk to {{PATIENT-FIRSTNAME}}\’s father/mother and {{PATIENT-GENDER}} advised us that they decided not to have the overnight oximetry done at this time.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and provide an update. If {{PATIENT-FIRSTNAME}}\’s parents/guardian chooses to go forward in the future, we will be happy to proceed with testing.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Oximetry No Book':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We have spoken with the patient\'s parent and explained the procedure. However, since that time we have tried contacting the parent and have left several messages but have been unsuccessful in booking the patient for the Overnight Oximetry.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> We felt it was important to make you aware of this situation and provide an update. If {{PATIENT-FIRSTNAME}}\’s parent returns to your clinic and you discover that they would still like their child to be tested, please have them call us as we would be happy to proceed with testing.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Prescription':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Please find attached <b>Abnormal Sleep Study</b> Report for your patient.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We have also provided the Recommendations of our Sleep Physician Dr. _______________. </p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> In order to facilitate the initiation of CPAP Therapy, we require one of your physicians to </p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><b>PLEASE SIGN AND FAX BACK THE ABNORMAL SLEEP STUDY RESULTS PAGE.</b></p>' +
                    '</div>'
            },
            'Return CPAP -- Buy Online': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that {{PATIENT-FIRSTNAME}} has decided to return {{PATIENT-GENDER3}} CPAP machine. After coaching along with support via our Sleep Assure Program, {{PATIENT-GENDER}} wanted to return our machine and purchase one online.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FULLNAME}} completed {{PATIENT-GENDER3}} Sleep Study on ______ and {{PATIENT-GENDER}} was diagnosed with ________ Obstructive Sleep Apnea (AHI=__, RDI=__). After using {{PATIENT-GENDER3}} CPAP for __ nights/weeks with an average usage of __ hours, {{PATIENT-FIRSTNAME}}\’s AHI dropped to __.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We can continue to offer support and even set {{PATIENT-GENDER2}} up on the machine purchased online however; we will have to charge a $150.00 for the Clinical time. If {{PATIENT-GENDER}} decides to remain in our care, we can offer unlimited clinical visits and follow up care calls under our Sleep Assure Program at $99.00/year.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated OSA and suggested that {{PATIENT-FIRSTNAME}} consider alternative treatments including oral Appliance. We are now working with Dr. Al- Ashi a Dentist to offer Oventus Optima Oral Appliance to those patients unable to tolerate CPAP Therapy. {{PATIENT-FIRSTNAME}} was also encouraged to follow up with you in the near future.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Return CPAP -- No Funds': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that your patient {{PATIENT-FIRSTNAME}} has decided to return {{PATIENT-GENDER3}} CPAP machine. {{PATIENT-FIRSTNAME}} has no funds at the moment to pay for CPAP Therapy. We discussed an interest free finance plan as well as long term rental option with {{PATIENT-FIRSTNAME}} but {{PATIENT-GENDER}} still declined.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} competed {{PATIENT-GENDER3}} Sleep Study on ___________ and {{PATIENT-GENDER}} was diagnosed with __________________ Obstructive Sleep Apnea (AHI=__, RDI=__). After using {{PATIENT-GENDER3}} CPAP for __ nights with an average usage of __ hours, {{PATIENT-FIRSTNAME}} AHI dropped to __.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated OSA and suggested that {{PATIENT-FIRSTNAME}} consider alternative treatments including an Oral Appliance if {{PATIENT-GENDER}} is unable to tolerate CPAP. We are ow working with Dentist, Dr. Al-Ashi to offer Oventus Optima Oral Appliance.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Return CPAP -- No Insurance': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that your patient {{PATIENT-FIRSTNAME}} has decided to return {{PATIENT-GENDER3}} CPAP machine. {{PATIENT-FIRSTNAME}} has no insurance coverage to help pay for CPAP Therapy. We discussed an interest free finance plan as well as long term rental option with {{PATIENT-FIRSTNAME}} but {{PATIENT-GENDER}} still declined.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} completed {{PATIENT-GENDER3}} Sleep Study on ____________ and {{PATIENT-GENDER}} was diagnosed with ____________ Obstructive Sleep Apnea (AHI=__, RDI=__). After using {{PATIENT-GENDER3}} CPAP for __ nights with an average usage of __ hours, {{PATIENT-FIRSTNAME}}\’s AHI dropped to __.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated OSA and suggested that {{PATIENT-FIRSTNAME}} consider alternative treatments including an Oral Appliance if {{PATIENT-GENDER}} is unable to tolerate CPAP. We are now working with Dr. Al-Ashi to offer Oventus Optima Oral Appliances.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt that it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Specialist Referral':{
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">As per the initial assessment of your patient, (HE/SHE) scored __ on the Stop Bang Questionnaire. We would like to request that patient will be seen first by our Sleep Specialist.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">If you would like your patient to be seen by our Sleep Specialist, kindly sign and fax back the attached Specialist Referral Form.</p>' +
                    '</div>'
            },
            // THEY DID NOT INCLUDE THIS ON THEIR LATEST LIST
            // 'Return CPAP -- Try alternative': {
            //     body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">Thank you for referring your patient {{PATIENT-FULLNAME}} to our clinic.</p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">I am writing to inform you that your patient {{PATIENT-FULLNAME}} has decided to return {{PATIENT-GENDER3}} CPAP machine. After coaching along with support via our Sleep Assure Program, {{PATIENT-FULLNAME}} wanted to try an alternative therapy.</p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">{{PATIENT-FULLNAME}} had {{PATIENT-GENDER3}} Sleep Study completed and {{PATIENT-GENDER}} was diagnosed with Obstructive Sleep Apnea (AHI=___, RDI=___). After using {{PATIENT-GENDER3}} CPAP for _____ with an average usage of ___, {{PATIENT-FULLNAME}}\'s AHI dropped to ___.</p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">We spent time discussing the implications of untreated OSA and suggested that {{PATIENT-FULLNAME}} consider alternative treatments including a mandibular advancement splint or possible ENT consult if {{PATIENT-GENDER}} is unable to tolerate CPAP. {{PATIENT-FULLNAME}} was also encouraged to follow up with you in the near future.</p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
            //         '</div>'
            //  },
            'Return CPAP -- Unable to Tolerate': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that your patient {{PATIENT-FIRSTNAME}} has decided to return {{PATIENT-GENDER3}} CPAP machine. After coaching along with support via our Sleep Assure Program, {{PATIENT-FIRSTNAME}} was still unable to tolerate CPAP Therapy.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">{{PATIENT-FIRSTNAME}} completed {{PATIENT-GENDER3}} Sleep Study on ______________ and {{PATIENT-GENDER}} was diagnosed with _______________ Obstructive Sleep Apnea (AHI=__, RDI=__). After using {{PATIENT-GENDER3}} CPAP for __ nights with an average usage of __ hours, {{PATIENT-FIRSTNAME}}\’s AHI dropped to __.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated OSA and suggested that {{PATIENT-FIRSTNAME}} consider alternative treatments including an Oral Appliance if {{PATIENT-GENDER}} is unable to tolerate CPAP. We are now working with Dr. Al-Ashi to offer Oventus Optima Oral Appliances. If {{PATIENT-FIRSTNAME}} decides for Oral Appliance, we can schedule {{PATIENT-GENDER2}} for an appointment.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt that it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Return CPAP -- (No Stats) Buy online': {
                 body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that {{PATIENT-FIRSTNAME}} has decided to return {{PATIENT-GENDER3}} CPAP machine. After coaching along with support via our Sleep Assure Program, {{PATIENT-FIRSTNAME}} wanted to return our machine and purchase one online.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We can continue to offer support and even set {{PATIENT-GENDER2}} up on the machine purchased online however; we will have to charge a $150.00 for the Clinical time.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">If {{PATIENT-GENDER}} decides to remain in our care, we can offer unlimited clinical visits and follow up care calls under our Sleep Assure Program at $99.00/year.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Return CPAP -- (No Stats) No insurance': {
                 body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that {{PATIENT-FIRSTNAME}} has decided to return {{PATIENT-GENDER3}} CPAP machine. {{PATIENT-FIRSTNAME}} has no insurance coverage right now to help pay for CPAP Therapy. We discussed an interest free finance plan as well as long term rental option with {{PATIENT-FIRSTNAME}}, but {{PATIENT-GENDER}} still declined.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Return CPAP -- (No Stats) No Funds': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> I am writing to inform you that {{PATIENT-FIRSTNAME}} has decided to return {{PATIENT-GENDER3}} CPAP machine. {{PATIENT-FIRSTNAME}} has no funds at the moment to pay for CPAP Therapy. We discussed an interest free finance plan as well as long term rental option with {{PATIENT-FIRSTNAME}} but {{PATIENT-GENDER}} still declined.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> We felt it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Return CPAP -- (No Stats) Try alternative treatment': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that {{PATIENT-FIRSTNAME}} has decided to return {{PATIENT-GENDER3}} CPAP machine. After coaching along with support via our Sleep Assure Program, {{PATIENT-FIRSTNAME}} was still unable to tolerate CPAP Therapy. {{PATIENT-FIRSTNAME}} wanted to try an alternative therapy.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We are now working with Dr. Al-Ashi to offer Oventus Optima Oral Appliances. If {{PATIENT-FIRSTNAME}} decides for Oral Appliance, we can schedule her for an appointment.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt that it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Return CPAP -- (No Stats) Unable to tolerate (Severe to Very Severe)': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that {{PATIENT-FIRSTNAME}} has decided to return {{PATIENT-GENDER3}} CPAP machine. After coaching along with support via our Sleep Assure Program, {{PATIENT-FIRSTNAME}} was still unable to tolerate CPAP Therapy.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> Due to the severity of {{PATIENT-FIRSTNAME}}\’s Sleep Apnea we recommend a referral to one of our Sleep Specialist.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> We spent time discussing the implications of untreated OSA and suggested that {{PATIENT-FIRSTNAME}} also consider alternative treatments including an Oral Appliance if {{PATIENT-GENDER}} is unable to tolerate CPAP. We are now working with a Dentist Dr. Al-Ashi to offer Oventus Optima Dental Appliances.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"> We felt that it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Return CPAP -- (No Stats) Unable to tolerate (Very Mild to Moderate)': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that {{PATIENT-FIRSTNAME}} has decided to return {{PATIENT-GENDER3}} CPAP machine. After coaching along with support via our Sleep Assure Program, First Name was still unable to tolerate CPAP Therapy.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We spent time discussing the implications of untreated OSA and suggested that {{PATIENT-FIRSTNAME}} also consider alternative treatments including an Oral Appliance if {{PATIENT-GENDER}} is unable to tolerate CPAP. We are now working with a Dentist Dr. Al-Ashi to offer Oventus Optima Dental Appliances.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">We felt that it was important to make you aware of the situation and give you an update. Should you have questions or if we can be of any further assistance, please do not hesitate to contact us.</p>' +
                    '</div>'
            },
            'Negative Inconclusive': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Thank you for referring your patient {{PATIENT-FULLNAME}} to our clinic.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">I am writing to inform you that your patient {{PATIENT-FULLNAME}} recently had a Home Sleep Apnea Test (HSAT) performed on (DATE)</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">The screen for Obstructive Sleep Apnea came back negative however due to the symptoms reported the diagnosis is inconclusive and it’s recommended that your patient see our Sleep Specialist in Clinic for further assessment. There is a possibility that your patient has a different sleep disorder and might need further screening (Level 1 PSG).</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">If your original HSAT referral was on the old version of the DSRC Referral Form we will attach a Specialist Referral Form for you to sign. If your Referral was on the newly updated DSRC Referral then we won’t need to send you the additional paperwork prior to booking.</p>' +
                    '</div>'
            },
            // 'Oral Appliance': {
            //     body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">Thank you for referring your patient {{PATIENT-FULLNAME}} to our clinic.</p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">{{PATIENT-FULLNAME}} had a Home Sleep Apnea Test (HSAT) and based on the interpretation provided by our Sleep Physician, your patient may benefit from an Oral Appliance.</p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">We are now working closely with dentistry services in both Edmonton and Calgary and have the ability to offer digital scans along with custom dental appliance fittings right inside some of our clinics under the supervision of a Dentist. </p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">Since your patient has indicated they are interested in pursuing this form of treatment we can schedule {{PATIENT-GENDER2}} to see our Sleep Specialist in order to find out if {{PATIENT-GENDER}} is a good candidate for Oral Appliance Therapy</p>' +
            //         '</div>'
            // },
            // 'Devices and Pediatric Oximetry Letter': {
            //     body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">We regret to inform you that we are no longer accepting referrals for Overnight Oximetry (Home Sleep Apnea Test for patients 16 years old and below), as our sleep doctor is not eligible to interpret results for that age bracket.</p>' +
            //         '</div>' +
            //         '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
            //         '<p style="margin:2px">Should you have any questions or if we could be of further assistance, please do not hesitate to contact us.</p>' +
            //         '</div>'                   
            // },
            'Unable to Proceed HSAT Due to High BMI': {
                body: '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px"><br>Thank you for referring your patient {{PATIENT-FULLNAME}} to Dynamic Sleep & Respiratory Care.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">Your patient came in to see us today in clinic and unfortunately, we were unable to proceed with the Home Sleep Apnea Study (HSAT). Based on the policy developed in accordance with our Medical Director and the College of Physicians patients with BMI of 50 or greater need to be seen first by one of our Sleep Specialists prior to testing.</p>' +
                    '</div>' + 
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">There is extra concern for these patients due to risk for hypoventilation. In keeping with best practices and patient safety we request your permission to have your patient seen by one of our Sleep Physicians prior to testing.</p>' +
                    '</div>' +
                    '<div style="width: 100%; height: auto; text-align:left;margin-top: 20px;">' +
                    '<p style="margin:2px">If your original referral was on the old version of the DSRC Referral Form, we will attach a Specialist Referral Form for you to sign. If your Referral was on the newly updated DSRC Referral, then we won’t need to send you the additional paperwork prior to the booking.</p>' +
                    '</div>'                   
            },
        },
        patient_referring_provider_autocompleteUrl: '',
        patient_referring_health_facility_autocompleteUrl: '',
        patient_insurance_autocompleteUrl: '',
        patient_chart_autocompleteUrl: '',
        chart_procedure_autocompleteUrl: '',
        item_autocompleteUrl: '',
        itemCategory_autocompleteUrl: '',
        patient_export_hl7_formUrl: '',
        patient_export_hl7_formActionUrl: '',
        patient_for_billing_autocompleteUrl: '',

        fax_cover_patient_referring_provider_autocompleteUrl: '',
        fax_cover_accountUser_autocompleteUrl: '',
        fax_cover_patient_autocompleteUrl: '',
        fax_cover_patient_insurance_autocompleteUrl: '',
    },
    chartDataList: null,
    fileDataList: null,
    fileFromImportDataList: null,
    medicalDiagnosisDataList: null,
    medicalDiagnosisMedicationDataList: null,
    insuranceDataList: null,
    noteDataList: null,
    noteClinicalDataList: null,
    noteBillingDataList: null,
    noteAppointmentDataList: null,
    noteSpecialistDataList: null,
    noteLetterDataList: null,
    letterDataList: null,
    scheduleDataList: null,
    referringHealthFacilityDataList: null,
    referringProviderDataList: null,
    healthFacilityDataList: null,
    patientServicesDataList: null,
    specialistDataList: null,
    billingDataList: null,
    paymentDataList: null,
    patientHistoryDataList: null,
    patientRedFlagDataList: null,
    patientPurchasedItemsDataList: null,
    ticketDataList: null,
    patientServicesOtherDataList: null,
    patientBillingRefundDataList: null,
    patientReminderDataList: null,
    patientRentalDataList: null,
    patientTreatmentConsiderationDataList: null,
    patientTreatmentPlanDataList: null,
    patientEmailDataList: null,

    //google map
    currentAjaxName: null,
    patientDetails: {
        map: null,
        pMarker: null,
        hfMarker: null
    },
    init: function() {
        patient_detail.initDataTable();
        patient_detail.bindPatientChartForm();
        patient_detail.bindPatientFileForm();
        patient_detail.bindPatientMedicalDiagnosisForm();
        patient_detail.bindPatientMedicalDiagnosisMedicationForm();
        patient_detail.bindPatientInsuranceForm();
        patient_detail.bindPatientNoteForm();
        patient_detail.bindPatientLetterForm();
        patient_detail.bindPatientReferringHealthFacilityForm();
        patient_detail.bindPatientReferringProviderForm();
        patient_detail.bindPatientAppointmentNoticeFaxForm();
        patient_detail.bindPatientBillingForm();
        patient_detail.bindPatientPaymentForm();
        patient_detail.bindPatientBillingRefundForm();
        patient_detail.bindPatientReminderForm();
        patient_detail.bindPatientTreatmentConsiderationForm();
        patient_detail.bindPatientTreatmentPlanForm();
        //patient_detail.bindPatientLocation();
        patient_detail.bindPatientRedFlagForm();
        patient_detail.bindPatientExportHl7();
        patient_detail.bindPatientHealthFacilityForm();
        patient_detail.bindAddReminderForm();
        patient_detail.bindPatientLinkedReferringHealthFacilityAndProviderForm();
        patient_detail.bindPatientEmailForm();
        // patient_detail.bindLetterTemplateAction();

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

        const id = jQ('#patient-tabs').find('.tabs-title.is-active').data('dt-id');
        patient_detail.initDataTable(id);
    },
    bindAddReminderForm: function(){
        if(jQ(".href-add-reminder-action").length > 0){
            jQ(".href-add-reminder-action").unbind('click').bind('click', function(e){
                e.preventDefault();
                global_reminder.form('n', 0, patient_detail.settings.patient_id);
            });
        }
    },
    bindPatientChartForm: function() {
        if(jQ('.href-chart-form').length > 0) {

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.chart_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();
                    }
                };

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

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_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();
                        patient_detail.bindPatientFileFormAction();
                    }
                };

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

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

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

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

            var formData = new FormData(jQ('#form-patientFile')[0]);
            jQ.ajax({
                url: patient_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');
                        patient_detail.fileDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        _form.find('.progress').hide();
                        global.flashMessage('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_detail.settings.patient_diagnosis_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();
                        patient_detail.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_detail.settings.patient_diagnosis_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.medicalDiagnosisDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientTreatmentConsiderationForm: function() {
        if(jQ('.href-patient-treatment-consideration-form').length > 0) {

            jQ('.href-patient-treatment-consideration-form').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_treatment_consideration_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();
                        patient_detail.bindPatientTreatmentConsiderationFormAction();
                    }
                };

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

        jQ('.href-patient-treatment-consideration-action').unbind('click.patientTreatmentConsiderationFormAction').bind('click.patientTreatmentConsiderationFormAction', function () {

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

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

            var settings = {
                url: patient_detail.settings.patient_treatment_consideration_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.patientTreatmentConsiderationDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientTreatmentPlanForm: function() {
        if(jQ('.href-patient-treatment-plan-form').length > 0) {

            jQ('.href-patient-treatment-plan-form').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_treatment_plan_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();
                        patient_detail.bindPatientTreatmentPlanFormAction();
                    }
                };

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

        jQ('.href-patient-treatment-plan-action').unbind('click.patientTreatmentPlanFormAction').bind('click.patientTreatmentPlanFormAction', function () {

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

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

            var settings = {
                url: patient_detail.settings.patient_treatment_plan_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.patientTreatmentPlanDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

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

                jQ('.href-patient-chart-medical-diagnosis-medication-form' + jQ('#patient-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_detail.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').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();
                            jQ(this).data('pd-id');
                            patient_detail.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_detail.settings.patient_diagnosis_medication_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        // modal.foundation('close');
                        patient_detail.medicalDiagnosisMedicationDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                        location.reload();
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_insurance_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();
                        patient_detail.bindPatientInsuranceFormAction();
                    }
                };

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

    bindPatientInsuranceFormAction: function() {

        jQ('.href-patient-insurance-action').unbind('click.patientInsuranceFormAction').bind('click.patientInsuranceFormAction', function () {

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

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

            var settings = {
                url: patient_detail.settings.patient_insurance_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.insuranceDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_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();
                        patient_detail.bindPatientNoteFormAction();

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

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

                        jQ('#patient_note_type option')
                            .removeAttr('selected')
                            .filter('[value='+dataType+']')
                            .attr('selected', true);
                        if(dataType === '' || dataType === null){
                            jQ('#patient_note_type').removeClass('hide');
                        }

                        if(patient_detail.settings.noteTemplateAccess == false) {
                            jQ('#patient_note_type').children('option[value=Template]').addClass('hide');
                        }
                    }
                };

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

    bindPatientNoteFormAction: function() {

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

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

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

            var settings = {
                url: patient_detail.settings.patient_note_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.noteDataList.draw();
                        if(jQ('#patient_note_type').val() === 'Clinical'){
                            patient_detail.noteClinicalDataList.draw();
                        }
                        if(jQ('#patient_note_type').val() === 'Billing'){
                            patient_detail.noteBillingDataList.draw();
                        }
                        if(jQ('#patient_note_type').val() === 'Appointment'){
                            patient_detail.noteAppointmentDataList.draw();
                        }
                        if(jQ('#patient_note_type').val() === 'Specialist'){
                            patient_detail.noteSpecialistDataList.draw();
                        }
                        if(jQ('#patient_note_type').val() === 'Letter'){
                            patient_detail.noteLetterDataList.draw();
                        }
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

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

                var requestName = 'patientLetterForm',
                    modal = jQ('#modal-small'),
                    modalContent = jQ('#modal-content-small');
                modal.addClass('modalTop');

                global.ajaxCancel(requestName);
                var axn = jQ(this).data('action');
                var settings = {
                    url: patient_detail.settings.patient_letter_formUrl + '/' + axn + '/' + 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();
                        patient_detail.bindPatientLetterFormAction();
                        var
                            params = {
                                patient_id : patient_detail.settings.patient_id_decoded,
                            };
                        global.autocomplete.bind(patient_detail.settings.patient_referring_provider_autocompleteUrl, '#patient_letter_patient_referring_provider_desc', '#patient_letter_patient_referring_provider', {});
                        global.autocomplete.bind(patient_detail.settings.patient_healthFacility_autocompleteUrl, '#patient_letter_healthFacility_desc', '#patient_letter_healthFacility');
                        global.autocomplete.bind(patient_detail.settings.patient_referring_health_facility_autocompleteUrl, '#patient_letter_patient_referring_health_facility_desc', '#patient_letter_patient_referring_health_facility');
                        global.autocomplete.bind(patient_detail.settings.patient_insurance_autocompleteUrl, '#patient_letter_patient_insurance_desc', '#patient_letter_patient_insurance');
                        global.autocomplete.bind(patient_detail.settings.accountUser_autocompleteUrl, '#patient_letter_accountUser_fullName', '#patient_letter_accountUser', {
                            onSelect: function (d) {
                                let statuses = {};
                                jQ('#patient_letter_patientLetterStatus option').each(
                                    function () {
                                        statuses[jQ(this).text()] = jQ(this).attr('value');
                                    });
                                if(d.data !== 'Jesse (QSC) Tallon'){
                                    jQ('#patient_letter_patientLetterStatus').val(statuses['Pending']);
                                }else{
                                    jQ('#patient_letter_patientLetterStatus').val(statuses['For Approval']);
                                }
                            }
                        });

                        // global.autocomplete.bind(patient_detail.settings.fax_cover_patient_autocompleteUrl, '#patient_letter_recipient', '#');
                        // global.autocomplete.bind(patient_detail.settings.fax_cover_accountUser_autocompleteUrl, '#patient_letter_name', '#');
                        // global.autocomplete.bind(patient_detail.settings.fax_cover_patient_referring_provider_autocompleteUrl, '#patient_letter_attention', '#');

                        jQ('#patient_letter_patient_referring_provider_desc').devbridgeAutocomplete('setOptions', {params: params});
                        jQ('#patient_letter_patient_referring_health_facility_desc').devbridgeAutocomplete('setOptions', {params: params});
                        jQ('#patient_letter_patient_insurance_desc').devbridgeAutocomplete('setOptions', {params: params});

                        jQ("#patient_letter_affiliate_type").unbind('change').bind('change',function () {
                            if(jQ(this).val() === 'Insurance'){
                                jQ('#affiliate-Insurance').removeClass('hide');
                                jQ('#affiliate-Referring-HealthFacility, #affiliate-Referring-Provider').addClass('hide');
                                jQ('#patient_letter_patient_referring_health_facility_desc, #patient_letter_patient_referring_health_facility, #patient_letter_patient_referring_provider_desc, #patient_letter_patient_referring_provider').val(null);
                            }else if(jQ(this).val() === 'Referring Health Facility'){
                                jQ('#affiliate-Referring-HealthFacility').removeClass('hide');
                                jQ('#affiliate-Referring-Provider, #affiliate-Insurance').addClass('hide');
                                jQ('#patient_letter_patient_insurance_desc, #patient_letter_patient_insurance, #patient_letter_patient_referring_provider_desc, #patient_letter_patient_referring_provider').val(null);
                            }else{
                                jQ('#affiliate-Referring-Provider').removeClass('hide');
                                jQ('#affiliate-Referring-HealthFacility, #affiliate-Insurance').addClass('hide');
                                jQ('#patient_letter_patient_insurance_desc, #patient_letter_patient_insurance, #patient_letter_patient_referring_health_facility_desc, #patient_letter_patient_referring_health_facility').val(null);
                            }
                        });

                        if(axn === 'n'){
                            jQ('#affiliate-Insurance').removeClass('hide');
                        }else{
                            if(jQ('#patient_letter_patient_referring_provider').val() !== '' && jQ('#patient_letter_patient_referring_provider').val() !== null){
                                jQ('#affiliate-Referring-Provider').removeClass('hide');
                                jQ('#patient_letter_affiliate_type').val('Referring Provider');
                            }else if(jQ('#patient_letter_patient_referring_health_facility').val() !== '' && jQ('#patient_letter_patient_referring_health_facility').val() !== null){
                                jQ('#affiliate-Referring-HealthFacility').removeClass('hide');
                                jQ('#patient_letter_affiliate_type').val('Referring Health Facility');
                            }else {
                                jQ('#affiliate-Insurance').removeClass('hide');
                                jQ('#patient_letter_affiliate_type').val('Insurance');
                            }
                        }

                        const editor = CKEDITOR.replace('patient_letter_custom_body');
                        editor.on('change', function () {
                            editor.updateElement();
                        });

                        const fax_cover_body_editor = CKEDITOR.replace('patient_letter_fax_cover_custom_body');
                        fax_cover_body_editor.on('change', function () {
                            fax_cover_body_editor.updateElement();
                        });

                        const patient_prescription_recommendation_editor = CKEDITOR.replace('patient_prescription_recommendation_textarea');
                        patient_prescription_recommendation_editor.on('change', function () {
                            patient_prescription_recommendation_editor.updateElement();
                        });

                        const patient_prescription_frsi_recommendation_editor = CKEDITOR.replace('patient_prescription_frsi_recommendation_textarea');
                        patient_prescription_frsi_recommendation_editor.on('change', function () {
                            patient_prescription_frsi_recommendation_editor.updateElement();
                        });

                        const patient_prescription_frsi_v2_recommendation_editor = CKEDITOR.replace('patient_prescription_frsi_v2_recommendation_textarea');
                        patient_prescription_frsi_v2_recommendation_editor.on('change', function () {
                            patient_prescription_frsi_v2_recommendation_editor.updateElement();
                        });

                        const alice_night_one_editor = CKEDITOR.replace('alice_night_one_recommendation_textarea');
                        alice_night_one_editor.on('change', function () {
                            alice_night_one_editor.updateElement();
                        });

                        const patient_prescription_pss_recommendation_editor = CKEDITOR.replace('patient_prescription_pss_recommendation_textarea');
                        patient_prescription_pss_recommendation_editor.on('change', function () {
                            patient_prescription_pss_recommendation_editor.updateElement();
                        });

                        const patient_specialist_referral_note_editor = CKEDITOR.replace('patient_specialist_referral_note_textarea');
                        patient_specialist_referral_note_editor.on('change', function () {
                            patient_specialist_referral_note_editor.updateElement();
                        });

                        const patient_general_prescription_frsi_recommendation_editor = CKEDITOR.replace('patient_general_prescription_frsi_recommendation_textarea');
                        patient_general_prescription_frsi_recommendation_editor.on('change', function () {
                            patient_general_prescription_frsi_recommendation_editor.updateElement();
                        });


                        jQ('#patient_letter_letter_type').unbind('change').bind('change', function () {

                            if(undefined !== patient_detail.settings.patient_letter_types[jQ(this).val()]){
                                console.log(jQ(this).val());
                                //jQ('#patient_letter_custom_body').val(patient_detail.settings.patient_letter_types[jQ(this).val()].body);
                                editor.setData(patient_detail.settings.patient_letter_types[jQ(this).val()].body);
                                jQ('.prescriptionForm').addClass('hide');
                                jQ('.prescriptionFrsiForm').addClass('hide');
                                jQ('.prescriptionPssForm').addClass('hide');
                                jQ('.specialistReferralForm').addClass('hide');
                                jQ('.refusalCareForm').addClass('hide');
                                jQ('.generalPrescriptionFrsi').addClass('hide');
                                jQ('.prescriptionFrsiV2Form').addClass('hide');
                                jQ('.aliceNightOneForm').addClass('hide');

                                if (jQ(this).val() === 'Prescription') {
                                    fax_cover_body_editor.setData(patient_detail.settings.fax_cover_body_prescription);
                                    jQ('.prescriptionForm').removeClass('hide');
                                    jQ('.prescriptionFrsiForm').addClass('hide');
                                    jQ('.prescriptionFrsiV2Form').addClass('hide');
                                    jQ('.prescriptionPssForm').addClass('hide');
                                    jQ('.specialistReferralForm').addClass('hide');
                                    jQ('#faxCoverCustomBody').removeClass('hide');
                                    jQ('.refusalCareForm').addClass('hide');
                                    jQ('.generalPrescriptionFrsi').addClass('hide');
                                    jQ('.aliceNightOneForm').addClass('hide');
                                } else if (jQ(this).val() === 'General Prescription (FRSC)') {
                                    // fax_cover_body_editor.setData(patient_detail.settings.fax_cover_body_prescription);
                                    jQ('.prescriptionForm').addClass('hide');
                                    jQ('.prescriptionFrsiForm').addClass('hide');
                                    jQ('.prescriptionFrsiV2Form').addClass('hide');
                                    jQ('.prescriptionPssForm').addClass('hide');
                                    jQ('.specialistReferralForm').addClass('hide');
                                    jQ('#faxCoverCustomBody').removeClass('hide');
                                    jQ('.refusalCareForm').addClass('hide');
                                    jQ('.generalPrescriptionFrsi').removeClass('hide');
                                    jQ('.aliceNightOneForm').addClass('hide');
                                } else if(jQ(this).val() === 'Prescription (FRSC)') {
                                    // fax_cover_body_editor.setData(patient_detail.settings.fax_cover_body_sleep_specialist);
                                    patient_prescription_frsi_recommendation_editor.setData(patient_detail.settings.patient_letter_types[jQ(this).val()].recommendation);
                                    jQ('.prescriptionForm').addClass('hide');
                                    jQ('.prescriptionFrsiForm').removeClass('hide');
                                    jQ('.prescriptionFrsiV2Form').addClass('hide');
                                    jQ('.prescriptionPssForm').addClass('hide');
                                    jQ('.specialistReferralForm').addClass('hide');
                                    jQ('#faxCoverCustomBody').removeClass('hide');
                                    jQ('.refusalCareForm').addClass('hide');
                                    jQ('.generalPrescriptionFrsi').addClass('hide');
                                    jQ('.aliceNightOneForm').addClass('hide');
                                } else if(jQ(this).val() === 'Prescription (FRSC) v2') {
                                    patient_prescription_frsi_v2_recommendation_editor.setData(patient_detail.settings.patient_letter_types[jQ(this).val()].recommendation);
                                    jQ('.prescriptionForm').addClass('hide');
                                    jQ('.prescriptionFrsiForm').addClass('hide');
                                    jQ('.prescriptionFrsiV2Form').removeClass('hide');
                                    jQ('.prescriptionPssForm').addClass('hide');
                                    jQ('.specialistReferralForm').addClass('hide');
                                    jQ('#faxCoverCustomBody').removeClass('hide');
                                    jQ('.refusalCareForm').addClass('hide');
                                    jQ('.generalPrescriptionFrsi').addClass('hide');
                                    jQ('.aliceNightOneForm').addClass('hide');
                                } else if(jQ(this).val() === 'Alice Night One (FRSC)') {
                                    alice_night_one_editor.setData(patient_detail.settings.patient_letter_types[jQ(this).val()].recommendation);
                                    jQ('.aliceNightOneForm').removeClass('hide');
                                    jQ('.prescriptionForm').addClass('hide');
                                    jQ('.prescriptionFrsiForm').addClass('hide');
                                    jQ('.prescriptionFrsiV2Form').addClass('hide');
                                    jQ('.prescriptionPssForm').addClass('hide');
                                    jQ('.specialistReferralForm').addClass('hide');
                                    jQ('#faxCoverCustomBody').addClass('hide');
                                    jQ('.refusalCareForm').addClass('hide');
                                    jQ('.generalPrescriptionFrsi').addClass('hide');
                                } else if(jQ(this).val() === 'Prescription (PSS)') {
                                    patient_prescription_pss_recommendation_editor.setData(patient_detail.settings.patient_letter_types[jQ(this).val()].recommendation);
                                    jQ('.prescriptionForm').addClass('hide');
                                    jQ('.prescriptionFrsiForm').addClass('hide');
                                    jQ('.prescriptionFrsiV2Form').addClass('hide');
                                    jQ('.prescriptionPssForm').removeClass('hide');
                                    jQ('.specialistReferralForm').addClass('hide');
                                    jQ('#faxCoverCustomBody').removeClass('hide');
                                    jQ('.refusalCareForm').addClass('hide');
                                    jQ('.generalPrescriptionFrsi').addClass('hide');
                                    jQ('.aliceNightOneForm').addClass('hide');
                                } else if(jQ(this).val() === 'Specialist Referral') {
                                    fax_cover_body_editor.setData(patient_detail.settings.fax_cover_body_sleep_specialist);
                                    jQ('.prescriptionForm').addClass('hide');
                                    jQ('.prescriptionFrsiForm').addClass('hide');
                                    jQ('.prescriptionFrsiV2Form').addClass('hide');
                                    jQ('.prescriptionPssForm').addClass('hide');
                                    jQ('.specialistReferralForm').removeClass('hide');
                                    jQ('#faxCoverCustomBody').removeClass('hide');
                                    jQ('.refusalCareForm').addClass('hide');
                                    jQ('.generalPrescriptionFrsi').addClass('hide');
                                    jQ('.aliceNightOneForm').addClass('hide');
                                } else if(jQ(this).val() === 'Acknowledgement') {
                                    jQ('.prescriptionForm').addClass('hide');
                                    jQ('.specialistReferralForm').addClass('hide');
                                    jQ('.prescriptionFrsiForm').addClass('hide');
                                    jQ('.prescriptionFrsiV2Form').addClass('hide');
                                    jQ('.prescriptionPssForm').addClass('hide');
                                    jQ('#faxCoverCustomBody').addClass('hide');
                                    jQ('.refusalCareForm').addClass('hide');
                                    jQ('.generalPrescriptionFrsi').addClass('hide');
                                    jQ('.aliceNightOneForm').addClass('hide');
                                } else if(jQ(this).val() === 'Refusal of Care Against Medical Advice (FRSC)') {
                                    jQ('.prescriptionForm').addClass('hide');
                                    jQ('.specialistReferralForm').addClass('hide');
                                    jQ('.prescriptionFrsiForm').addClass('hide');
                                    jQ('.prescriptionFrsiV2Form').addClass('hide');
                                    jQ('.prescriptionPssForm').addClass('hide');
                                    jQ('#faxCoverCustomBody').removeClass('hide');
                                    jQ('.refusalCareForm').removeClass('hide');
                                    jQ('.generalPrescriptionFrsi').addClass('hide');
                                    jQ('.aliceNightOneForm').addClass('hide');
                                } else {
                                    jQ('.prescriptionForm').addClass('hide');
                                    jQ('.specialistReferralForm').addClass('hide');
                                    jQ('#faxCoverCustomBody').removeClass('hide');
                                    jQ('.prescriptionFrsiForm').addClass('hide');
                                    jQ('.prescriptionFrsiV2Form').addClass('hide');
                                    jQ('.prescriptionPssForm').addClass('hide');
                                    jQ('.refusalCareForm').addClass('hide');
                                    jQ('.generalPrescriptionFrsi').addClass('hide');
                                    jQ('.aliceNightOneForm').addClass('hide');
                                    fax_cover_body_editor.setData(patient_detail.settings.fax_cover_body);
                                }
                            }else{
                                editor.setData('');
                                fax_cover_body_editor.setData('');
                            }

                            global.ajax({
                                url: patient_detail.settings.letter_template_data_url+'/'+jQ(this).val(),
                                type: 'GET',
                                beforeSend: function() {
                                    fax_cover_body_editor.setData('');
                                    editor.setData('');
                                },
                                success: function(json) {
                                    fax_cover_body_editor.setData(json.fax_cover_body);
                                    editor.setData(json.body);
                                },
                            })
                        });
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindPatientLetterFormAction: function() {
        jQ('.href-patient-letter-action').unbind('click.patientLetterFormAction').bind('click.patientLetterFormAction', function () {
            var requestName = 'patientLetterFormAction',
                _form = jQ('#form-patientLetter'),
                modal = jQ('#modal-small'),
                axn = jQ(this).data('axn');
            _form.find('.form-action').val(axn);

            var formData = new FormData(jQ('#form-patientLetter')[0]);
            jQ.ajax({
                url: patient_detail.settings.patient_letter_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');
                        patient_detail.letterDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        _form.find('.progress').hide();
                        global.flashMessage('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
            });
        });

        let initialIdx = jQ(".cc_row").length;
        let bindRemoveCc = function(){
            jQ(".patientLetter_removeCc_btn").unbind('click').bind('click', function(e){
                let idx = parseInt(jQ(this).data('idx'));
                jQ(`.cc_row[data-idx="${idx}"]`).remove();
            });
            console.debug('bind remove');
        }, bindAutoComplete = function(){
            jQ(".cc_row").each(function(i, el){
                let idxx = parseInt(jQ(el).data('idx')),
                    params =  {patient_id : patient_detail.settings.patient_id_decoded,};
                global.autocomplete.bind(patient_detail.settings.patient_referring_provider_autocompleteUrl, `#patientLetter_patientLetterCc_${idxx}_patient_referring_provider_desc`, `#patientLetter_patientLetterCc_${idxx}_patient_referring_provider`, {});
                //global.autocomplete.bind(patient_detail.settings.patient_referring_health_facility_autocompleteUrl, `#patientLetter_patientLetterCc_${idxx}_patient_referring_health_facility_desc`, `#patientLetter_patientLetterCc_${idxx}_patient_referring_health_facility`);
                global.autocomplete.bind(patient_detail.settings.patient_insurance_autocompleteUrl, `#patientLetter_patientLetterCc_${idxx}_patient_insurance_desc`, `#patientLetter_patientLetterCc_${idxx}_patient_insurance`);
                jQ(`#patientLetter_patientLetterCc_${idxx}_patient_referring_provider_desc`).devbridgeAutocomplete('setOptions', {params: params});
                //jQ(`#patientLetter_patientLetterCc_${idxx}_patient_referring_health_facility_desc`).devbridgeAutocomplete('setOptions', {params: params});
                jQ(`#patientLetter_patientLetterCc_${idxx}_patient_insurance_desc`).devbridgeAutocomplete('setOptions', {params: params});

                jQ(`#patient_letter_cc_affiliate_type_${idxx}`).unbind('change').bind('change',function () {
                    jQ(`.hidden-cc-${idxx}`).addClass('hide');
                    jQ(`#patientLetter_patientLetterCc_${idxx}_patient_referring_provider_desc, #patientLetter_patientLetterCc_${idxx}_patient_referring_provider, #patientLetter_patientLetterCc_${idxx}_patient_insurance_desc, #patientLetter_patientLetterCc_${idxx}_patient_insurance`).val('');
                    if(jQ(this).val() === 'Insurance'){
                        jQ(`#patientLetter_patientLetterCc_${idxx}_patient_insurance_label, #patientLetter_patientLetterCc_${idxx}_patient_insurance_desc`).removeClass('hide');
                    }else if(jQ(this).val() === 'Referring Health Facility'){
                    }else{
                        jQ(`#patientLetter_patientLetterCc_${idxx}_patient_referring_provider_label, #patientLetter_patientLetterCc_${idxx}_patient_referring_provider_desc`).removeClass('hide');
                    }
                });
            });
            console.debug('bind autocomplete');
        };


        jQ("#patientLetter_addCc_btn").unbind('click').bind('click', function(e){
            let lastIdx = initialIdx;
            jQ(".cc_row").each(function(i, el){
                lastIdx = parseInt(jQ(el).data('idx'));
            });
            let idx = lastIdx + 1,
                params =  {patient_id : patient_detail.settings.patient_id_decoded,},
                row = jQ("<div>").attr({
                    class: 'cc_row row',
                    'data-idx': idx,
                }),
                col1 = jQ("<div>").attr({
                    class: 'cc_col1 small-6 columns',
                    'data-idx': idx,
                }),
                col2 = jQ("<div>").attr({
                    class: 'cc_col2 small-6 columns',
                    'data-idx': idx,
                }),
                closeBtn = `<span class="patientLetter_removeCc_btn" data-idx="${idx}"><i class="fa fa-times-circle"></i></span>`,
                selectLabel = jQ("<label>").attr({
                    for: `patient_letter_cc_affiliate_type_${idx}`,
                }).html('Affiliates'),
                selectOption1 = jQ("<option>").attr({
                    value: 'Insurance',
                }).html('Insurance'),
                selectOption2 = jQ("<option>").attr({
                    value: 'Referring Provider',
                }).html('Referring Provider'),
                select = jQ("<select>").attr({
                    id: `patient_letter_cc_affiliate_type_${idx}`,
                    name: `patient_letter[patientLetterCcs][${idx}][affiliate_type]`,
                    'data-idx': idx,
                }),
                insuranceLabel = jQ("<label>").attr({
                    for: `patientLetter_patientLetterCc_${idx}_patient_insurance_desc`,
                    class: `hidden-cc-${idx}`,
                    id: `patientLetter_patientLetterCc_${idx}_patient_insurance_label`
                }).html('Insurance'),
                insuranceTxt = jQ("<input>").attr({
                    type: 'text',
                    name: `patient_letter[patientLetterCcs][${idx}][patient_insurance_desc]`,
                    id: `patientLetter_patientLetterCc_${idx}_patient_insurance_desc`,
                    class: `patientLetter_patientLetterCc_patient_insurance_desc hidden-cc-${idx}`,
                }),
                insuranceIdTxt = jQ("<input>").attr({
                    type: 'hidden',
                    name: `patient_letter[patientLetterCcs][${idx}][patient_insurance]`,
                    id: `patientLetter_patientLetterCc_${idx}_patient_insurance`,
                }),
                refProvLabel = jQ("<label>").attr({
                    for: `patientLetter_patientLetterCc_${idx}_patient_referring_provider_desc`,
                    class: `hide hidden-cc-${idx}`,
                    id: `patientLetter_patientLetterCc_${idx}_patient_referring_provider_label`
                }).html('Referring Provider'),
                refProvIdTxt = jQ("<input>").attr({
                    type: 'hidden',
                    name: `patient_letter[patientLetterCcs][${idx}][patient_referring_provider]`,
                    id: `patientLetter_patientLetterCc_${idx}_patient_referring_provider`,
                }),
                refProvTxt = jQ("<input>").attr({
                    type: 'text',
                    name: `patient_letter[patientLetterCcs][${idx}][patient_referring_provider_desc]`,
                    id: `patientLetter_patientLetterCc_${idx}_patient_referring_provider_desc`,
                    class: `patientLetter_patientLetterCc_patient_referring_provider_desc hide hidden-cc-${idx}`,
                }),
                idTxt = jQ("<input>").attr({
                    type: 'hidden',
                    name: `patient_letter[patientLetterCcs][${idx}][id]`,
                    id: `patientLetter_patientLetterCc_${idx}_id`,
                });
            selectOption1.appendTo(select);
            selectOption2.appendTo(select);
            selectLabel.appendTo(col1);
            select.appendTo(col1);
            col1.appendTo(row);
            col2.append(closeBtn);
            insuranceLabel.appendTo(col2);
            insuranceTxt.appendTo(col2);
            insuranceIdTxt.appendTo(col2);
            refProvLabel.appendTo(col2);
            refProvTxt.appendTo(col2);
            refProvIdTxt.appendTo(col2);
            idTxt.appendTo(col2);
            col2.appendTo(row);
            row.appendTo("#cc_container");

            bindRemoveCc();
            bindAutoComplete();
            console.debug('bind add');
        });

        bindRemoveCc();
        bindAutoComplete();


    },
    bindPatientLetterRowButton: function(){
        jQ('.href-patient-letter-pdf-fax').on('click', function () {
            var value = jQ(this).data('value');
            var conf = confirm('Are you sure you want to send fax?');
            if(conf){
                location.href = patient_detail.settings.patient_letter_pdf + '?file=' + value;
            }
        });
        jQ('.href-patient-letter-pdf-preview').on('click', function () {
            var value = jQ(this).data('value');
            window.open(patient_detail.settings.patient_letter_preview + '?file=' + value,'_blank');
        });
    },

    //Appointment Notice Fax -start
    bindPatientAppointmentNoticeFaxForm: function() {
        if(jQ('.href-patient-appointment-notice-form').length > 0) {

            jQ('.href-patient-appointment-notice-form').unbind('click').bind('click', function(){

                var requestName = 'patientAppointmentNoticeFaxForm',
                    modal = jQ('#modal-small'),
                    modalContent = jQ('#modal-content-small');
                global.ajaxCancel(requestName);
                var axn = jQ(this).data('action'),
                    patientId = jQ(this).data('patient-id'),
                    scheduleId = jQ(this).data('schedule-id');
                var settings = {
                    url: patient_detail.settings.patient_appointment_notice_fax_formUrl,
                    type: 'GET',
                    data: {
                        patient_id: jQ(this).data('patient-id'),
                        schedule_id: jQ(this).data('schedule-id')
                    },
                    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();
                        patient_detail.bindPatientAppointmentNoticeFaxFormAction();
                        var
                            params = {
                                patient_id : patientId,
                                schedule_id: scheduleId
                            };

                        global.autocomplete.bind(patient_detail.settings.patient_referring_provider_autocompleteUrl, '#appointment_notice_fax_patient_referring_provider_desc', '#appointment_notice_fax_patient_referring_provider', {});
                        global.autocomplete.bind(patient_detail.settings.patient_referring_health_facility_autocompleteUrl, '#appointment_notice_fax_patient_referring_health_facility_desc', '#appointment_notice_fax_patient_referring_health_facility');
                        global.autocomplete.bind(patient_detail.settings.patient_insurance_autocompleteUrl, '#appointment_notice_fax_patient_insurance_desc', '#appointment_notice_fax_patient_insurance');
                        jQ('#appointment_notice_fax_patient_referring_provider_desc').devbridgeAutocomplete('setOptions', {params: params});
                        jQ('#appointment_notice_fax_patient_referring_health_facility_desc').devbridgeAutocomplete('setOptions', {params: params});
                        jQ('#appointment_notice_fax_patient_insurance_desc').devbridgeAutocomplete('setOptions', {params: params});

                        jQ("#appointment_notice_fax_affiliate_type").unbind('change').bind('change',function () {
                            if(jQ(this).val() === 'Insurance'){
                                jQ('#affiliate-Insurance').removeClass('hide');
                                jQ('#affiliate-Referring-HealthFacility, #affiliate-Referring-Provider').addClass('hide');
                                jQ('#appointment_notice_fax_patient_referring_health_facility_desc, #appointment_notice_fax_patient_referring_health_facility, #appointment_notice_fax_patient_referring_provider_desc, #appointment_notice_fax_patient_referring_provider').val(null);
                            }else if(jQ(this).val() === 'Referring Affiliate'){
                                jQ('#affiliate-Referring-HealthFacility').removeClass('hide');
                                jQ('#affiliate-Referring-Provider, #affiliate-Insurance').addClass('hide');
                                jQ('#patient_letter_patient_insurance_desc, #patient_letter_patient_insurance, #appointment_notice_fax_patient_referring_provider_desc, #appointment_notice_fax_patient_referring_provider').val(null);
                            }else{
                                jQ('#affiliate-Referring-Provider').removeClass('hide');
                                jQ('#affiliate-Referring-HealthFacility, #affiliate-Insurance').addClass('hide');
                                jQ('#appointment_notice_fax_patient_insurance_desc, #appointment_notice_fax_patient_insurance, #appointment_notice_fax_patient_referring_health_facility_desc, #appointment_notice_fax_patient_referring_health_facility').val(null);
                            }
                        });

                        if(axn === 'n'){
                            jQ('#affiliate-Insurance').removeClass('hide');
                        }else{
                            if(jQ('#patient_letter_patient_referring_provider').val() !== '' && jQ('#patient_letter_patient_referring_provider').val() !== null){
                                jQ('#affiliate-Referring-Provider').removeClass('hide');
                                jQ('#appointment_notice_fax_affiliate_type').val('Referring Physician');
                            }else if(jQ('#patient_letter_patient_referring_health_facility').val() !== '' && jQ('#patient_letter_patient_referring_health_facility').val() !== null){
                                jQ('#affiliate-Referring-HealthFacility').removeClass('hide');
                                jQ('#appointment_notice_fax_affiliate_type').val('Referring Affiliate');
                            }else {
                                jQ('#affiliate-Insurance').removeClass('hide');
                                jQ('#appointment_notice_fax_affiliate_type').val('Insurance');
                            }
                        }
                        // const editor = CKEDITOR.replace('patient_letter_custom_body');
                        // editor.on('change', function () {
                        //     editor.updateElement();
                        // });
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindPatientAppointmentNoticeFaxFormAction: function() {
        jQ('.href-patient-appointment-notice-fax-action').unbind('click.appointmentNoticeFaxFormAction').bind('click.appointmentNoticeFaxFormAction', function () {
            var requestName = 'appointmentNoticeFaxFormAction',
                _form = jQ('#form-patientAppointmentNoticeFax'),
                modal = jQ('#modal-small'),
                axn = jQ(this).data('axn');
            _form.find('.form-action').val(axn);

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

            var settings = {
                url: patient_detail.settings.patient_appointment_notice_fax_formUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.scheduleDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindPatientAppointmentNoticeFaxRowButton: function(){
        jQ('.href-appointment-notice-pdf-fax').on('click', function () {
            var value = jQ(this).data('value');
            var conf = confirm('Are you sure you want to send fax?');
            if(conf){
                location.href = patient_detail.settings.patient_appointment_notice_fax_pdf + '?file=' + value;
            }
        });
        // jQ('.href-patient-letter-pdf-preview').on('click', function () {
        //     var value = jQ(this).data('value');
        //     window.open(patient_detail.settings.patient_letter_preview + '?file=' + value,'_blank');
        // });
    },
    //Appointment Notice Fax -end

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

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_referring_health_facility_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();
                        patient_detail.bindPatientReferringHealthFacilityFormAction();
                    }
                };

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

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

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

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

            var settings = {
                url: patient_detail.settings.patient_referring_health_facility_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.referringHealthFacilityDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        patient_detail.letterDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

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

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_referring_provider_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();
                        patient_detail.bindPatientReferringProviderFormAction();
                    }
                };

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

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

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

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

            var settings = {
                url: patient_detail.settings.patient_referring_provider_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.referringProviderDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientLinkedReferringHealthFacilityAndProviderForm: function() {
        if(jQ('.href-patient-linked-referring-health-facility-and-provider-form').length > 0) {

            jQ('.href-patient-linked-referring-health-facility-and-provider-form').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_linked_referring_health_facility_and_provider_formUrl + '/' + jQ(this).data('action') + '/' + '0',
                    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();
                        patient_detail.bindPatientLinkedReferringHealthFacilityAndProviderFormAction();
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindPatientLinkedReferringHealthFacilityAndProviderFormAction: function(){
        jQ('.href-patient-linked-referring-health-facility-and-provider-action').unbind('click.patientLinkedReferringHealthFacilityAndProviderFormAction').bind('click.patientLinkedReferringHealthFacilityAndProviderFormAction', function () {
            var requestName = 'patientLinkedReferringHealthFacilityAndProviderFormAction',
                _form = jQ('#form-patientLinkedReferringHealthFacilityAndProvider'),
                modal = jQ('#modal-small'),
                axn = jQ(this).data('axn');
            _form.find('.form-action').val(axn);

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

            var settings = {
                url: patient_detail.settings.patient_linked_referring_health_facility_and_provider_formUrl + '/' + 'n' + '/' + '0',
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.referringHealthFacilityDataList.draw();
                        patient_detail.referringProviderDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    patientBillingForm: function (action, id, callBack = null) {
        var requestName = 'patientBillingForm',
            modal = jQ('#modal-full'),
            modalContent = jQ('#modal-content-full');
        modal.addClass('modalTop');

        global.ajaxCancel(requestName);

        var settings = {
            url: patient_detail.settings.patient_billing_formUrl,
            type: 'GET',
            data: {
                patient_id: patient_detail.settings.patient_id,
                action: action,
                id: id
            },
            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();
                patient_detail.bindPatientBillingAddBreakdown();
                patient_detail.bindPatientBillingFormAction();
                patient_detail.bindPatientBillingVoidAction();
                patient_detail.bindPatientBillingItemRefundAction();
                CKEDITOR.replace('patientBilling_comment');
                if (callBack !== null && typeof callBack ===  'function') {
                    callBack();
                }
            }
        };

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

        if(!jQ('.href-patient-billing-form').length) {
            return;
        }

        jQ('.href-patient-billing-form').unbind('click').bind('click', function(){
            patient_detail.patientBillingForm(jQ(this).data('action'), jQ(this).data('id'))
        });
    },
    bindPatientBillingVoidAction: function() {

        jQ('.href-patient-billing-void-action').unbind('click.patientBillingVoidAction').bind('click.patientBillingVoidAction', function () {
            var requestName = 'patientBillingVoidAction',
                _form = jQ('#form-patientBilling-void'),
                modal = jQ('#modal'),
                axn = jQ(this).data('axn');
            _form.find('.form-action').val(axn);

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

            var settings = {
                url: patient_detail.settings.patient_billing_void_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.billingDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindPatientBillingFormAction: function() {
        if(jQ('#patientBilling_healthFacilityForAddress_desc').val() === 'Dyna Sleep Sales'){
            // jQ('#comment-container').slideDown(300)
        }else{
            // jQ('#comment-container').slideUp(300)
        }

        jQ(".price-covered-txt").unbind('keyup').bind('keyup', function(e){
            let qty = global.zapParseAmount(jQ(this).data('qty')),
                val = global.zapParseAmount(jQ(this).val());
            jQ(this).parent().next().children('.amount-covered-txt').val(global.zapNumWithCommasAndDecimal(val * qty));
        });

        global.autocomplete.bind(
            patient_detail.settings.patient_insurance_autocompleteUrl,
            '#patientBilling_patientInsurance_insurance_description',
            '#patientBilling_patientInsurance'
        );
        global.autocomplete.bind(
            patient_detail.settings.patient_for_billing_autocompleteUrl,
            '#patientBilling_patient_fullName',
            '#patientBilling_patient'
        );
        global.autocomplete.bind(
            patient_detail.settings.healthFacility_autocompleteUrl,
            '#patientBilling_healthFacility_desc',
            '#patientBilling_healthFacility'
        );
        global.autocomplete.bind(
            patient_detail.settings.healthFacility_autocompleteUrl,
            '#patientBilling_healthFacilityForAddress_desc',
            '#patientBilling_healthFacilityForAddress',
            {
                onSelect: function (d) {
                    // console.log(d);
                    if(d.data === 'Dyna Sleep Sales'){
                        // console.log(d);
                        // jQ('#comment-container').slideDown(300)
                    }else{
                        // jQ('#comment-container').slideUp(300)
                    }
                }
            }
        );
        jQ('#patientBilling_patientInsurance_insurance_description').devbridgeAutocomplete('setOptions', {
            params: {
                patient_id: patient_detail.settings.patient_id_decoded,
                refDate: jQ('#patientBilling_billing_date').val()
            }
        });
        if(jQ('#patientBilling_action').val() !== 'u'){
            jQ('#patientBilling_billing_date').mask('99/99/9999').datepicker({
                changeMonth: true,
                changeYear: true,
                onSelect: function() {
                    jQ('#patientBilling_patientInsurance_insurance_description').devbridgeAutocomplete('setOptions', {
                        params: {
                            patient_id: patient_detail.settings.patient_id_decoded,
                            refDate: jQ('#patientBilling_billing_date').val()
                        }
                    });
                }
            });
        }
        /*if('Self Pay' === jQ('#patientBilling_payer_type').val()) {
            jQ('#patientBillingForm-patientInsurance-container').addClass('hide');
            jQ('#patientBilling_patientInsurance').val('');
        } else {
            jQ('#patientBillingForm-patientInsurance-container').removeClass('hide');
        }*/
        jQ('#patientBilling_payer_type').unbind('change').bind('change', function(){
            if('Insurance' !== jQ(this).val()) {
                jQ('#patientBillingForm-patientInsurance-container').addClass('hide');
                jQ('#insurance_package').addClass('hide');
                jQ('#patientBilling_patientInsurance').val('');
            }else {
                jQ('#insurance_package').removeClass('hide');
                jQ('#patientBillingForm-patientInsurance-container').removeClass('hide');
            }
        });


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

            var requestName = 'patientBillingFormAction',
                _form = jQ('#form-patientBilling'),
                modal = jQ('#modal-full'),
                axn = jQ(this).data('axn'),
                close_modal = jQ(this).data('close_modal');
            _form.find('.form-action').val(axn);

            // global.formSubmitted();
            // global.ajaxCancel(requestName);
            CKEDITOR.instances.patientBilling_comment.updateElement();

            // var settings = {
            //     url: patient_detail.settings.patient_billing_formActionUrl,
            //     type: 'POST',
            //     data: _form.serialize(),
            //     success: function (json) {
            //         if(json.success) {
            //             modal.foundation('close');
            //             patient_detail.billingDataList.draw();
            //             patient_detail.paymentDataList.draw();
            //             patient_detail.patientHistoryDataList.draw();
            //             global.flashMessage('success', json.successMessages);
            //         } else {
            //             global.formSubmittedReverse();
            //             global.flashMessage('alert', json.errorMessages);
            //         }
            //     }
            // };

            var formData = new FormData(jQ('#form-patientBilling')[0]);
            jQ.ajax({
                url: patient_detail.settings.patient_billing_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) {
                    if(json.success) {
                        if(json.action === 'n') {
                            global.flashMessage('success', json.successMessages, false);
                            patient_detail.patientBillingForm('u', json['patient_billing_id'], function () {
                                jQ('#modal-full .close-button, #modal-full .pb_form_close-button').hide();
                            });
                        } else {
                            global.flashMessage('success', json.successMessages);
                            if (close_modal !== undefined || json['patient_billing_id'] === undefined) {
                                modal.foundation('close');
                            } else {
                                patient_detail.patientBillingForm('u', json['patient_billing_id']);
                            }
                            patient_detail.billingDataList.draw();
                            patient_detail.paymentDataList.draw();
                            patient_detail.fileDataList.draw();
                            patient_detail.patientHistoryDataList.draw();
                        }
                    } else {
                        _form.find('.progress').hide();
                        global.flashMessage('alert', json.errorMessages);
                        global.formSubmittedReverse();
                    }
                },
                error: function(xhr, response_text) {
                    global.formSubmittedReverse();
                    global.flashMessage('alert', json.errorMessages);
                    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
            });

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

        let idx = jQ('#tbody-billing-breakdown tr').length;
        const doCompute = function() {

            let tAmt = 0;

            jQ('#tbody-billing-breakdown tr').each(function(){

                let qty, price, amt;
                qty = global.parseNum(jQ(this).find('.pb_pbb_quantity').val());
                price = global.parseNum(jQ(this).find('.pb_pbb_price').val());
                amt = qty * price;

                tAmt += amt;

                jQ(this).find('.pb_pbb_amount').val(amt);
                jQ(this).find('.pb_pbb_amount_td').text(global.numWithCommas(amt.toFixed(2)));
            });

            jQ('#patientBilling_amount_due').val(tAmt);
            jQ('#td-billing-amount-due, #td-billing-total-amount').text(global.numWithCommas(tAmt.toFixed(2)));
        };

        const bindCompute = function() {
            jQ('.txt-billing-for-computation').unbind('keyup').bind('keyup', doCompute);
        };

        const bindRemove = function() {
            jQ('.btn-billing-remove-breakdown').unbind('click').bind('click', function() {

                const tr = jQ(this).parent().parent(),
                    type = tr.find('.pb_pbb_type').val();
                tr.find('.pb_pbb_patientChart_chartNo').devbridgeAutocomplete('dispose');
                if('Chart Procedure' === type) {
                    tr.find('.pb_pbb_chartProcedure_description').devbridgeAutocomplete('dispose');
                } else if('Item' === type) {
                    tr.find('.item_description').devbridgeAutocomplete('dispose');
                }
                tr.remove();
                doCompute();
            });
        };

        bindCompute();
        bindRemove();

        jQ('#tbody-billing-breakdown tr').each(function(i){

            const type = jQ(this).find('.pb_pbb_type').val();

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

                global.autocomplete.bind(
                    patient_detail.settings.patient_chart_autocompleteUrl,
                    'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]"]',
                    'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart]"]',
                    {
                        onSelect: function(data) {
                            if('Chart Procedure' === type) {
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][quantity]"]').val('');
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][price]"]').val('');
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]').val('');
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure]"]').val('');
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]').devbridgeAutocomplete('setOptions', {params: {chartType_id: data.chartType_id}});
                                doCompute();
                            }
                        }
                    }
                );
                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]"]').devbridgeAutocomplete('setOptions', {params: {patient_id: patient_detail.settings.patient_id_decoded}});

                if('Chart Procedure' === type) {

                    global.autocomplete.bind(
                        patient_detail.settings.chart_procedure_autocompleteUrl,
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]',
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure]"]',
                        {
                            onSelect: function(data) {
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][quantity]"').val(1);
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][price]"').val(data.amount);
                                doCompute();
                            }
                        }
                    );

                } else if('Item' === type) {

                    /*global.autocomplete.bind(
                        patient_detail.settings.itemCategory_autocompleteUrl,
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]',
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory]"]',{
                            onSelect: function(data) {
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][item_description]"]').devbridgeAutocomplete('setOptions', {params: {item_category_id: data.id}});
                            }
                        });*/

                    global.autocomplete.bind(
                        patient_detail.settings.item_autocompleteUrl,
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][item_description]"]',
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][item]"]',{
                            onSelect: function(data) {
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][price]"').val(data.price);
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]').val(data.subCat);
                            }
                        });

                    jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]').unbind('change').bind('change', function () {
                        jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][item_description]"]').devbridgeAutocomplete('setOptions', {params: {item_category_id: ''}})
                    });
                }

            })(i, type);
        });
        jQ('.item_type_header').show();
        jQ('.term_header').show();
        jQ('#btn-billing-add-breakdown').unbind('click').bind('click', function(){

            idx++;
            const type = jQ('#dropdown-billing-breakdown-type').val();
            let tdOfType;

            switch(type) {
                case 'Chart Procedure':
                    // jQ('.item_type_header').hide();
                    // jQ('.term_header').hide();
                    // jQ('.item_type_header').html('');
                    // jQ('.term_header').html('');

                    tdOfType =
                        '<td colspan="2">' +
                        '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]" type="text" class="pb_pbb_patientChart_chartNo" placeholder="Encounter" />' +
                        '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart]" type="hidden" class="pb_pbb_patientChart" />' +
                        '</td>' +
                        '<td colspan="2">' +
                        '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure_description]" type="text" class="pb_pbb_chartProcedure_description" placeholder="Procedure" />' +
                        '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure]" type="hidden" class="pb_pbb_chartProcedure" />' +
                        '</td>';
                    break;
                case 'Item':
                    jQ('.item_type_header').show();
                    jQ('.term_header').show();
                    // jQ('.item_type_header').html('Item Type');
                    // jQ('.term_header').html('Term');

                    tdOfType =
                        '<td width="140px;">' +
                        '<input style="width: 100%;" name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory_desc]" type="text" class="pb_pbb_itemCategory_description" placeholder="Item Subcategory" style="float: left;" readonly />' +
                        '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory]" type="hidden" class="pb_pbb_itemCategory"/>' +
                        '</td>'+
                        '<td data-xwidth="90px;" style="padding:0!important;">' +
                        '<input style="width: 100%;display: none;" name="patientBilling[patientBillingBreakdowns][' + idx + '][serialNumber]" id="serial_number_' +idx+ '" type="text" class="pb_pbb_serial_number hide" placeholder="Serial Number" />' +
                        '<select style="width: 100%;" name="patientBilling[patientBillingBreakdowns][' + idx + '][inventory_serial_no]" id="inventory_serial_no_' +idx+ '" class="pb_pbb_inventory_serial_no hide" ><option value="" hidden selected>Serial Number</option></select>' +
                        '</td>'+
                        '<td width="250px;">' +
                        '<input style="width: 100%;" name="patientBilling[patientBillingBreakdowns][' + idx + '][item_description]" type="text" class="pb_pbb_item_description" placeholder="Item" style="width: 100%; float: left;"/>' +
                        '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][item]" type="hidden" class="pb_pbb_item" />' +
                        '</td>'+
                        '<td>' +
                        '<select name="patientBilling[patientBillingBreakdowns][' + idx + '][term]" id="term_' +idx+ '" style="width: 100%; float: right">' +
                        '<option value="" selected></option>'+
                        '<option value="'+patient_detail.settings.term_rent_to_own+'">'+patient_detail.settings.term_rent_to_own+'</option>'+
                        '<option value="'+patient_detail.settings.term_long_term+'">'+patient_detail.settings.term_long_term+'</option>'+
                        // '<option value="'+patient_detail.settings.term_warranty+'">'+patient_detail.settings.term_warranty+'</option>'+
                        '</select>'+
                        '</td>';
                    break;
                default: // Other
                    // jQ('.term_header').hide();
                    // jQ('.item_type_header').hide();
                    // jQ('.item_type_header').html('');
                    // jQ('.term_header').html('');
                    tdOfType =

                        // '<td>' +
                        // '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]" type="text" class="pb_pbb_patientChart_chartNo" placeholder="Encounter" />' +
                        // '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart]" type="hidden" class="pb_pbb_patientChart" />' +
                        // '</td>' +
                        // '<td>' +
                        // '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][tranDateForOther]" type="text" class="pb_pbb_tranDateForOther" placeholder="MM-DD-YYYY" />' +
                        // '</td>' +
                        // '<td colspan="2">' +
                        '<td colspan="4">' +
                        '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][description]" type="text" class="pb_pbb_description" placeholder="Description" />' +
                        '</td>';
                    break;
            }

            const trHtml =
                '<tr>' +
                '<td>' + type + '</td>' +
                tdOfType +
                '<td>' +
                '<select name="patientBilling[patientBillingBreakdowns][' + idx + '][item_type]" id="item_type_'+ idx +'" style="width: 100%; float: right">' +
                '<option value="" selected></option>'+
                '<option value="'+patient_detail.settings.item_type_cpap_package+'">'+patient_detail.settings.item_type_cpap_package+'</option>'+
                '<option value="'+patient_detail.settings.item_type_accessory+'">'+patient_detail.settings.item_type_accessory+'</option>'+
                '<option value="'+patient_detail.settings.item_type_medical_supplies+'">'+patient_detail.settings.item_type_medical_supplies+'</option>'+
                '<option value="'+patient_detail.settings.item_type_part_of_cpap_package+'">'+patient_detail.settings.item_type_part_of_cpap_package+'</option>'+
                '</select>'+
                '</td>' +
                '<td style="clear: both;">' +
                '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][quantity]" type="text" class="pb_pbb_quantity txt-billing-for-computation" id="quantity_'+ idx +'" style="float: right;" />' +
                '</td>' +
                '<td style="clear: both;">' +
                '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][price]" type="text" class="pb_pbb_price txt-billing-for-computation" id="price_'+ idx +'" style="float: right;" />' +
                '</td>' +
                '<td class="text-right pb_pbb_amount_td">0.00</td>' +
                '<td>' +
                '<a href="javascript:void(0)" class="btn-billing-remove-breakdown">X</a>' +
                '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][amount]" type="hidden" class="pb_pbb_amount" />' +
                '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][type]" type="hidden" class="pb_pbb_type" value="' + type + '" />' +
                '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][id]" type="hidden" class="pb_pbb_id" />' +
                '</td>' +
                '</tr>';

            jQ(trHtml).appendTo('#tbody-billing-breakdown');

            jQ("#quantity_" + idx).maskMoney({precision: 0});
            jQ("#price_" + idx).maskMoney();
            global.maskInput();

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

                global.autocomplete.bind(
                    patient_detail.settings.patient_chart_autocompleteUrl,
                    'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]"]',
                    'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart]"]',
                    {
                        onSelect: function(data) {
                            if('Chart Procedure' === type) {
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][quantity]"]').val('');
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][price]"]').val('');
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]').val('');
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure]"]').val('');
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]').devbridgeAutocomplete('setOptions', {params: {chartType_id: data.chartType_id}});
                                doCompute();
                            }
                        }
                    }
                );
                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]"]').devbridgeAutocomplete('setOptions', {params: {patient_id: patient_detail.settings.patient_id_decoded}});

                if('Chart Procedure' === type) {

                    global.autocomplete.bind(
                        patient_detail.settings.chart_procedure_autocompleteUrl,
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]',
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][chartProcedure]"]',
                        {
                            onSelect: function(data) {
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][quantity]"').val(1);
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][price]"').val(data.amount);
                                doCompute();
                            }
                        }
                    );

                } else if('Item' === type) {
                    /*global.autocomplete.bind(
                        patient_detail.settings.itemCategory_autocompleteUrl,
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]',
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory]"]',{
                            onSelect: function(data) {
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][item_description]"]').devbridgeAutocomplete('setOptions', {params: {item_category_id: data.id}});
                            }
                        });*/
                    global.autocomplete.bind(
                        patient_detail.settings.item_autocompleteUrl,
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][item_description]"]',
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][item]"]',{
                            onSelect: function(data) {
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][price]"').val(data.price);
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]').val(data.subCat);

                                let serialSelect = jQ(`#inventory_serial_no_${idx}`),
                                    serialInput = jQ(`#serial_number_${idx}`);

                                if(data['is_itemised'] === "1") {
                                    let serialNos = data['serialNos'].split(',');

                                    serialInput.val('');
                                    serialSelect.show();
                                    serialInput.hide();

                                    serialSelect.html(`<option value="" hidden selected>Serial Number</option>`);

                                    for(let i=0; i< serialNos.length; i++) {
                                        let arr = serialNos[i].split('~');
                                        serialSelect.append(`<option value="${arr[0]}">${arr[1]}</option>`)
                                    }
                                } else {

                                    serialSelect.val('');
                                    serialSelect.hide();
                                    serialInput.show();

                                }
                            }
                        });
                    jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]').unbind('change').bind('change', function () {
                        jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][item_description]"]').devbridgeAutocomplete('setOptions', {params: {item_category_id: ''}})
                    });
                }

            })(idx, type);
            bindCompute();
            bindRemove();
        });


    },
    bindPatientBillingItemRefundAction: function() {

        jQ('.href-patient-item-return-action').unbind('click.patientBillingItemReturnAction').bind('click.patientBillingItemReturnAction', function () {
            var requestName = 'patientBillingItemReturnAction',
                _form = jQ('#form-patientBilling'),
                modal = jQ('#modal'),
                axn = jQ(this).data('axn');
            _form.find('.form-action').val(axn);

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

            var settings = {
                url: global.settings.url +'/main/patient/patient_billing/item_return/save_action/'+jQ(this).data('id'),
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.billingDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindPatientBillingAmountCoverageTable: function(){
        jQ('#tbody-billing-breakdown tr').each(function(i, el){


        });
    },
    //Patient Refund
    bindPatientRentalForm: function() {

        if(!jQ('.href-patient-rental-form').length) {
            return;
        }

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

            var requestName = 'patientRentalForm',
                modal = jQ('#modal'),
                modalContent = jQ('#modal-content');
            modal.addClass('modalTop');

            global.ajaxCancel(requestName);

            var settings = {
                url: patient_detail.settings.patient_rental_formUrl,
                type: 'GET',
                data: {
                    patient_id: patient_detail.settings.patient_id,
                    action: jQ(this).data('action'),
                    id: jQ(this).data('id')
                },
                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();
                    patient_detail.bindPatientRentalAddBreakdown();
                    patient_detail.bindPatientRentalFormAction();
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindPatientRentalFormAction: function() {
        if(jQ('#patientRental_healthFacilityRentalForAddress_desc').val() === 'Dyna Sleep Sales'){
            // jQ('#comment-container').slideDown(300)
        }else{
            // jQ('#comment-container').slideUp(300)
        }

        global.autocomplete.bind(
            patient_detail.settings.patient_insurance_autocompleteUrl,
            '#patientRental_patientInsurance_insurance_description',
            '#patientRental_patientInsurance'
        );
        global.autocomplete.bind(
            patient_detail.settings.patient_for_billing_autocompleteUrl,
            '#patientRental_patient_fullName',
            '#patientRental_patient'
        );
        global.autocomplete.bind(
            patient_detail.settings.healthFacility_autocompleteUrl,
            '#patientRental_healthFacility_desc',
            '#patientRental_healthFacility'
        );
        global.autocomplete.bind(
            patient_detail.settings.healthFacility_autocompleteUrl,
            '#patientRental_healthFacilityRentalForAddress_desc',
            '#patientRental_healthFacilityRentalForAddress',
            {
                onSelect: function (d) {
                    // console.log(d);
                    if(d.data === 'Dyna Sleep Sales'){
                        // console.log(d);
                        // jQ('#comment-container').slideDown(300)
                    }else{
                        // jQ('#comment-container').slideUp(300)
                    }
                }
            }
        );
        jQ('#patientRental_patientInsurance_insurance_description').devbridgeAutocomplete('setOptions', {
            params: {
                patient_id: patient_detail.settings.patient_id_decoded,
                refDate: jQ('#patientRental_start_date').val()
            }
        });
        if(jQ('#patientRental_action').val() !== 'u'){
            jQ('#patientRental_start_date').mask('99/99/9999').datepicker({
                changeMonth: true,
                changeYear: true,
                onSelect: function() {
                    jQ('#patientRental_patientInsurance_insurance_description').devbridgeAutocomplete('setOptions', {
                        params: {
                            patient_id: patient_detail.settings.patient_id_decoded,
                            refDate: jQ('#patientRental_start_date').val()
                        }
                    });
                }
            });
        }
        /*if('Self Pay' === jQ('#patientBilling_payer_type').val()) {
            jQ('#patientBillingForm-patientInsurance-container').addClass('hide');
            jQ('#patientBilling_patientInsurance').val('');
        } else {
            jQ('#patientBillingForm-patientInsurance-container').removeClass('hide');
        }*/
        jQ('#patientRental_payer_type').unbind('change').bind('change', function(){
            if('Insurance' !== jQ(this).val()) {
                jQ('#patientRentalForm-patientInsurance-container').addClass('hide');
                jQ('#patientRental_patientInsurance').val('');
            }else {
                jQ('#patientRentalForm-patientInsurance-container').removeClass('hide');
            }
        });


        jQ('.href-patient-rental-action').unbind('click.patientRentalFormAction').bind('click.patientRentalFormAction', function () {

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

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

            var settings = {
                url: patient_detail.settings.patient_rental_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if(json.success) {
                        modal.foundation('close');
                        patient_detail.patientRentalDataList.draw();
                        patient_detail.paymentDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

        let idx = jQ('#tbody-rental-breakdown tr').length - 2; // minus 2 because last row is not included
        const doCompute = function() {

            let tAmt = 0;

            jQ('#tbody-rental-breakdown tr:NOT(:last)').each(function(){

                let qty, price, amt;

                qty = global.parseNum(jQ(this).find('.pb_pbb_quantity').val());
                price = global.parseNum(jQ(this).find('.pb_pbb_price').val());
                amt = qty * price;

                tAmt += amt;

                jQ(this).find('.pb_pbb_amount').val(amt);
                jQ(this).find('.pb_pbb_amount_td').text(global.numWithCommas(amt.toFixed(2)));
            });

            jQ('#patientRental_amount_due').val(tAmt);
            jQ('#td-rental-amount-due').text(global.numWithCommas(tAmt.toFixed(2)));
        };

        const bindCompute = function() {
            jQ('.txt-rental-for-computation').unbind('keyup').bind('keyup', doCompute);
        };

        const bindRemove = function() {
            jQ('.btn-rental-remove-breakdown').unbind('click').bind('click', function() {

                const tr = jQ(this).parent().parent(),
                    type = tr.find('.pb_pbb_type').val();
                tr.find('.pb_pbb_patientChart_chartNo').devbridgeAutocomplete('dispose');
                if('Chart Procedure' === type) {
                    tr.find('.pb_pbb_chartProcedure_description').devbridgeAutocomplete('dispose');
                } else if('Item' === type) {
                    tr.find('.item_description').devbridgeAutocomplete('dispose');
                }
                tr.remove();
                doCompute();
            });
        };

        bindCompute();
        bindRemove();

        jQ('#tbody-rental-breakdown tr:NOT(:last)').each(function(i){

            const type = jQ(this).find('.pb_pbb_type').val();

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

                global.autocomplete.bind(
                    patient_detail.settings.patient_chart_autocompleteUrl,
                    'input[name="patientRental[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]"]',
                    'input[name="patientRental[patientBillingBreakdowns][' + idx + '][patientChart]"]',
                    {
                        onSelect: function(data) {
                            if('Chart Procedure' === type) {
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][quantity]"]').val('');
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][price]"]').val('');
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]').val('');
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure]"]').val('');
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]').devbridgeAutocomplete('setOptions', {params: {chartType_id: data.chartType_id}});
                                doCompute();
                            }
                        }
                    }
                );
                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]"]').devbridgeAutocomplete('setOptions', {params: {patient_id: patient_detail.settings.patient_id_decoded}});

                if('Chart Procedure' === type) {

                    global.autocomplete.bind(
                        patient_detail.settings.chart_procedure_autocompleteUrl,
                        'input[name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]',
                        'input[name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure]"]',
                        {
                            onSelect: function(data) {
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][quantity]"').val(1);
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][price]"').val(data.amount);
                                doCompute();
                            }
                        }
                    );

                } else if('Item' === type) {

                    /*global.autocomplete.bind(
                        patient_detail.settings.itemCategory_autocompleteUrl,
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]',
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory]"]',{
                            onSelect: function(data) {
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][item_description]"]').devbridgeAutocomplete('setOptions', {params: {item_category_id: data.id}});
                            }
                        });*/

                    global.autocomplete.bind(
                        patient_detail.settings.item_autocompleteUrl,
                        'input[name="patientRental[patientBillingBreakdowns][' + idx + '][item_description]"]',
                        'input[name="patientRental[patientBillingBreakdowns][' + idx + '][item]"]',{
                            onSelect: function(data) {
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][price]"').val(data.price);
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]').val(data.subCat);
                            }
                        });

                    jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]').unbind('change').bind('change', function () {
                        jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][item_description]"]').devbridgeAutocomplete('setOptions', {params: {item_category_id: ''}})
                    });
                }

            })(i, type);
        });
        jQ('.item_type_header').show();
        jQ('.term_header').show();
        jQ('#btn-rental-add-breakdown').unbind('click').bind('click', function(){

            idx++;
            const type = jQ('#dropdown-rental-breakdown-type').val();
            let tdOfType;

            switch(type) {
                case 'Chart Procedure':
                    // jQ('.item_type_header').hide();
                    // jQ('.term_header').hide();

                    tdOfType =
                        '<td colspan="2">' +
                        '<input name="patientRental[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]" type="text" class="pb_pbb_patientChart_chartNo" placeholder="Encounter" />' +
                        '<input name="patientRental[patientBillingBreakdowns][' + idx + '][patientChart]" type="hidden" class="pb_pbb_patientChart" />' +
                        '</td>' +
                        '<td colspan="2">' +
                        '<input name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure_description]" type="text" class="pb_pbb_chartProcedure_description" placeholder="Procedure" />' +
                        '<input name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure]" type="hidden" class="pb_pbb_chartProcedure" />' +
                        '</td>';
                    break;
                case 'Item':
                    // jQ('.item_type_header').show();
                    // jQ('.term_header').show();

                    tdOfType =
                        '<td>' +
                        '<input name="patientRental[patientBillingBreakdowns][' + idx + '][itemCategory_desc]" type="text" class="pb_pbb_itemCategory_description" placeholder="Item Subcategory" style="float: left;" readonly />' +
                        '<input name="patientRental[patientBillingBreakdowns][' + idx + '][itemCategory]" type="hidden" class="pb_pbb_itemCategory"/>' +
                        '</td>'+
                        '<td>' +
                        '<input name="patientRental[patientBillingBreakdowns][' + idx + '][serialNumber]" id="serial_number_' +idx+ '" type="text" class="pb_pbb_serial_number" placeholder="Serial no." style="float: left;" />' +
                        '</td>'+
                        '<td>' +
                        '<input name="patientRental[patientBillingBreakdowns][' + idx + '][item_description]" type="text" class="pb_pbb_item_description" placeholder="Item" style="width: 100%; float: left;"/>' +
                        '<input name="patientRental[patientBillingBreakdowns][' + idx + '][item]" type="hidden" class="pb_pbb_item" />' +
                        '</td>'+
                        '<td>' +
                        '<select name="patientRental[patientBillingBreakdowns][' + idx + '][term]" id="term_' +idx+ '" style="width: 100%; float: right">' +
                        '<option value="" selected hidden>Choose Term</option>'+
                        // '<option value="'+patient_detail.settings.term_warranty+'">'+patient_detail.settings.term_warranty+'</option>'+
                        '<option value="'+patient_detail.settings.term_long_term+'">'+patient_detail.settings.term_long_term+'</option>'+
                        '</select>'+
                        '</td>';
                    break;
                default: // Other
                    // jQ('.item_type_header').hide();
                    // jQ('.term_header').hide();
                    tdOfType =

                        // '<td>' +
                        // '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]" type="text" class="pb_pbb_patientChart_chartNo" placeholder="Encounter" />' +
                        // '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][patientChart]" type="hidden" class="pb_pbb_patientChart" />' +
                        // '</td>' +
                        // '<td>' +
                        // '<input name="patientBilling[patientBillingBreakdowns][' + idx + '][tranDateForOther]" type="text" class="pb_pbb_tranDateForOther" placeholder="MM-DD-YYYY" />' +
                        // '</td>' +
                        '<td colspan="4">' +
                        '<input name="patientRental[patientBillingBreakdowns][' + idx + '][description]" type="text" class="pb_pbb_description" placeholder="Description" />' +
                        '</td>';
                    break;
            }

            const trHtml =
                '<tr>' +
                '<td>' + type + '</td>' +
                tdOfType +
                '<td>' +
                '<select name="patientRental[patientBillingBreakdowns][' + idx + '][item_type]" id="item_type_'+ idx +'" style="width: 100%; float: right">' +
                '<option value="" selected hidden>Choose Item Type</option>'+
                '<option value="'+patient_detail.settings.item_type_cpap_package+'">'+patient_detail.settings.item_type_cpap_package+'</option>'+
                '<option value="'+patient_detail.settings.item_type_accessory+'">'+patient_detail.settings.item_type_accessory+'</option>'+
                '<option value="'+patient_detail.settings.item_type_medical_supplies+'">'+patient_detail.settings.item_type_medical_supplies+'</option>'+
                '</select>'+
                '</td>' +
                '<td style="clear: both;">' +
                '<input name="patientRental[patientBillingBreakdowns][' + idx + '][quantity]" type="text" class="pb_pbb_quantity txt-rental-for-computation" id="quantity_'+ idx +'" style="width: 50px; float: right;" />' +
                '</td>' +
                '<td style="clear: both;">' +
                '<input name="patientRental[patientBillingBreakdowns][' + idx + '][price]" type="text" class="pb_pbb_price txt-rental-for-computation" id="price_'+ idx +'" style="width: 75px; float: right;" />' +
                '</td>' +
                '<td class="text-right pb_pbb_amount_td">0.00</td>' +
                '<td>' +
                '<a href="javascript:void(0)" class="btn-rental-remove-breakdown">X</a>' +
                '<input name="patientRental[patientBillingBreakdowns][' + idx + '][amount]" type="hidden" class="pb_pbb_amount" />' +
                '<input name="patientRental[patientBillingBreakdowns][' + idx + '][type]" type="hidden" class="pb_pbb_type" value="' + type + '" />' +
                '<input name="patientRental[patientBillingBreakdowns][' + idx + '][id]" type="hidden" class="pb_pbb_id" />' +
                '</td>' +
                '</tr>';

            jQ(trHtml).insertBefore(jQ('#tbody-rental-breakdown tr:last'));
            jQ("#quantity_" + idx).maskMoney({precision: 0});
            jQ("#price_" + idx).maskMoney();

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

                global.autocomplete.bind(
                    patient_detail.settings.patient_chart_autocompleteUrl,
                    'input[name="patientRental[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]"]',
                    'input[name="patientRental[patientBillingBreakdowns][' + idx + '][patientChart]"]',
                    {
                        onSelect: function(data) {
                            if('Chart Procedure' === type) {
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][quantity]"]').val('');
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][price]"]').val('');
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]').val('');
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure]"]').val('');
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]').devbridgeAutocomplete('setOptions', {params: {chartType_id: data.chartType_id}});
                                doCompute();
                            }
                        }
                    }
                );
                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][patientChart_chartNo]"]').devbridgeAutocomplete('setOptions', {params: {patient_id: patient_detail.settings.patient_id_decoded}});

                if('Chart Procedure' === type) {

                    global.autocomplete.bind(
                        patient_detail.settings.chart_procedure_autocompleteUrl,
                        'input[name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure_description]"]',
                        'input[name="patientRental[patientBillingBreakdowns][' + idx + '][chartProcedure]"]',
                        {
                            onSelect: function(data) {
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][quantity]"').val(1);
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][price]"').val(data.amount);
                                doCompute();
                            }
                        }
                    );

                } else if('Item' === type) {
                    /*global.autocomplete.bind(
                        patient_detail.settings.itemCategory_autocompleteUrl,
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]',
                        'input[name="patientBilling[patientBillingBreakdowns][' + idx + '][itemCategory]"]',{
                            onSelect: function(data) {
                                jQ('input[name="patientBilling[patientBillingBreakdowns][' + idx + '][item_description]"]').devbridgeAutocomplete('setOptions', {params: {item_category_id: data.id}});
                            }
                        });*/
                    global.autocomplete.bind(
                        patient_detail.settings.item_autocompleteUrl,
                        'input[name="patientRental[patientBillingBreakdowns][' + idx + '][item_description]"]',
                        'input[name="patientRental[patientBillingBreakdowns][' + idx + '][item]"]',{
                            onSelect: function(data) {
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][price]"').val(data.price);
                                jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]').val(data.subCat);

                            }
                        });
                    jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][itemCategory_desc]"]').unbind('change').bind('change', function () {
                        jQ('input[name="patientRental[patientBillingBreakdowns][' + idx + '][item_description]"]').devbridgeAutocomplete('setOptions', {params: {item_category_id: ''}})
                    });
                }

            })(idx, type);
            bindCompute();
            bindRemove();
        });


    },

    bindPatientPaymentForm: function() {

        if(!jQ('.href-patient-payment-form').length) {
            return;
        }

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

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

            global.ajaxCancel(requestName);

            var settings = {
                url: patient_detail.settings.patient_payment_formUrl,
                type: 'GET',
                data: {
                    patient_id: patient_detail.settings.patient_id,
                    action: jQ(this).data('action'),
                    id: jQ(this).data('id')
                },
                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();
                    patient_detail.bindPatientPaymentFormAction();
                    patient_detail.bindPatientPaymentVoidAction();
                    patient_detail.bindPatientPaymentComputeTotalAmt();
                    if(jQ('#patientPayment_pay_type').val() === 'Financing' ){
                        jQ('.type-financing').removeClass('hide');
                    }else{
                        jQ('.type-financing, .type-financing-payment-plan').addClass('hide');
                        jQ('#patientPayment_financingCompany').val('');
                        jQ('#patientPayment_is_payment_plan').attr('checked', false);
                    }
                    jQ('#patientPayment_pay_type').unbind('change').bind('change', function () {
                        if(jQ(this).val() === 'Financing' ){
                            jQ('.type-financing').removeClass('hide');
                        }else{
                            jQ('.type-financing, .type-financing-payment-plan').addClass('hide');
                            jQ('#patientPayment_financingCompany').val('');
                            jQ('#patientPayment_is_payment_plan').attr('checked', false);
                        }
                        jQ("#patientPayment_pay_type_for_print").val(jQ(this).val())
                    });
                    jQ('#patientPayment_is_payment_plan').unbind('change').bind('change', function () {
                        if(jQ(this).is(':checked') ){
                            jQ('.type-financing-payment-plan').removeClass('hide');
                        }else{
                            jQ('.type-financing-payment-plan').addClass('hide');
                        }
                    });
                }
            };

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

    bindPatientPaymentVoidAction: function() {

        jQ('.href-patient-payment-void-action').unbind('click.patientPaymentVoidAction').bind('click.patientPaymentVoidAction', function () {
            var requestName = 'patientPaymentVoidAction',
                _form = jQ('#form-patientPayment-void'),
                modal = jQ('#modal'),
                axn = jQ(this).data('axn');
            _form.find('.form-action').val(axn);

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

            var settings = {
                url: patient_detail.settings.patient_payment_void_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.paymentDataList.draw();
                        patient_detail.billingDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientPaymentFormAction: function() {

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

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

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

            var settings = {
                url: patient_detail.settings.patient_payment_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    // console.log(json) ;
                    if(json.success) {
                        modal.foundation('close');
                        patient_detail.paymentDataList.draw();
                        patient_detail.billingDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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


        jQ("#patientPayment_patientBilling").unbind('change').bind('change', function(e){
            let value = jQ(this).val(),
                requestName = 'getPatientBillingBreakdown',
                settings = {
                    url: patient_detail.settings.patient_payment_billing_breakdownUrl,
                    method: 'POST',
                    data: {
                        id: value
                    },
                    beforeSend: function(){
                        jQ("#patientPaymentPatientBillingBreakdownContainer").html('').addClass('has-loading');
                        jQ("#patientPayment_amount").val(0);
                    },
                    success: function (json) {
                        if(json.success){
                            jQ("#patientPaymentPatientBillingBreakdownContainer").removeClass('has-loading').html(json.html);
                            global.maskInput();
                            patient_detail.bindPatientPaymentComputeTotalAmt();
                        } else {
                            alert(json.error);
                        }
                    }
                };
            global.ajaxCancel(requestName);
            global.ajax(settings, requestName);
        });
    },

    //Payment
    bindPatientPaymentComputeTotalAmt: function(){
        jQ(".patientPaymentBreakdown_amount").unbind('keyup').bind('keyup', function(e){
            patient_detail.patientPaymentComputeTotalAmt();
        });
    },

    patientPaymentComputeTotalAmt: function(){
        let totalAmt = 0;
        jQ(".patientPaymentBreakdown_amount").each(function(i,e){
            totalAmt += global.zapParseAmount(jQ(e).val());
        });

        jQ("#patientPayment_amount").val(global.zapNumWithCommasAndDecimal(totalAmt));
    },

    bindPatientBillingRefundForm: function() {

        if(!jQ('.href-patient-billing-refund-form').length) {
            return;
        }

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

            var requestName = 'patientBillingRefundForm',
                modal = jQ('#modal'),
                modalContent = jQ('#modal-content');
                modal.addClass('modalTop');

            global.ajaxCancel(requestName);

            var settings = {
                url: patient_detail.settings.patient_billing_refund_formUrl,
                type: 'GET',
                data: {
                    patient_id: patient_detail.settings.patient_id,
                    action: jQ(this).data('action'),
                    id: jQ(this).data('id')
                },
                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();
                    patient_detail.bindPatientBillingRefundFormAction();
                }
            };

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

    bindPatientBillingRefundFormAction: function() {

        jQ('.href-patient-billing-refund-action').unbind('click.patientBillingRefundFormAction').bind('click.patientBillingRefundFormAction', function () {

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

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

            var settings = {
                url: patient_detail.settings.patient_billing_refund_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if(json.success) {
                        modal.foundation('close');
                        patient_detail.paymentDataList.draw();
                        patient_detail.billingDataList.draw();
                        patient_detail.patientBillingRefundDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

        jQ("#patientBillingRefund_patientBilling").unbind('change').bind('change', function(e){
            let value = jQ(this).val(),
                requestName = 'getPatientBillingBreakdown',
                settings = {
                    url: patient_detail.settings.patient_billing_refund_breakdownUrl,
                    method: 'POST',
                    data: {
                        id: value
                    },
                    beforeSend: function(){
                        jQ("#patientRefundPatientBillingBreakdownContainer").html('').addClass('has-loading');
                        jQ("#patientRefund_amount").val(0);
                    },
                    success: function (json) {
                        if(json.success){
                            jQ("#patientRefundPatientBillingBreakdownContainer").removeClass('has-loading').html(json.html);
                            global.maskInput();
                            patient_detail.bindPatientRefundComputeTotalAmt();
                        } else {
                            alert(json.error);
                        }
                    }
                };
            global.ajaxCancel(requestName);
            global.ajax(settings, requestName);
        });
    },

    //Refund
    bindPatientRefundComputeTotalAmt: function(){
        jQ(".patientRefundBreakdown_amount").unbind('keyup').bind('keyup', function(e){
            patient_detail.patientRefundComputeTotalAmt();
        });
    },

    patientRefundComputeTotalAmt: function(){
        let totalAmt = 0;
        jQ(".patientRefundBreakdown_amount").each(function(i,e){
            totalAmt += global.zapParseAmount(jQ(e).val());
        });
        jQ("#patientBillingRefund_amount").val(global.zapNumWithCommasAndDecimal(totalAmt));
    },

    bindPatientReminderForm: function() {

        if(!jQ('.href-patient-reminder-form').length) {
            return;
        }

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

            var requestName = 'patientReminder',
                modal = jQ('#modal-small'),
                modalContent = jQ('#modal-content-small');
            modal.addClass('modalTop');

            global.ajaxCancel(requestName);

            var settings = {
                url: patient_detail.settings.patient_reminder_formUrl + '/' + jQ(this).data('action') + '/' + jQ(this).data('id'),
                type: 'GET',
                data: {
                    patient_id: patient_detail.settings.patient_id,
                    action: jQ(this).data('action'),
                    id: jQ(this).data('id')
                },
                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();
                    patient_detail.bindPatientReminderFormAction();
                }
            };

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

    bindPatientReminderFormAction: function() {

        jQ('.href-patient-reminder-action').unbind('click.patientReminderFormAction').bind('click.patientReminderFormAction', function () {

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

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

            var settings = {
                url: patient_detail.settings.patient_reminder_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if(json.success) {
                        modal.foundation('close');
                        patient_detail.patientReminderDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientLocation: function() {
        var myLatLng = {lat: parseFloat(patient_detail.settings.patientLocation.geoLat), lng: parseFloat(patient_detail.settings.patientLocation.geoLong)};

        var mapProp= {
            center: new google.maps.LatLng(patient_detail.settings.patientLocation.geoLat, patient_detail.settings.patientLocation.geoLong),
            zoom:17,
            disableDefaultUI: true,
            zoomControl: false,
        };

        map = new google.maps.Map(document.getElementById("patientLocationMap") ,mapProp);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
        });

        marker.setMap(map);
    },

    bindPatientRedFlagForm: function() {
        if(jQ('.href-patient-red-flag-form').length > 0) {

            jQ('.href-patient-red-flag-form').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_red_flag_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();
                        patient_detail.bindPatientRedFlagFormAction();
                    }
                };

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

    bindPatientPurchasedItemsForm: function() {
        if(jQ('.href-patient-purchased-items-form').length > 0) {

            jQ('.href-patient-purchased-items-form').unbind('click').bind('click', function(){
                patient_detail.patientBillingForm('u', jQ(this).data('billing_id'))
            });
        }
    },

    bindPatientRedFlagFormAction: function() {

        jQ('.href-patient-red-flag-action').unbind('click.patientRedFlagFormAction').bind('click.patientRedFlagFormAction', function () {
            var requestName = 'patientRedFlagFormAction',
                _form = jQ('#form-patientRedFlag'),
                modal = jQ('#modal'),
                axn = jQ(this).data('axn');
            _form.find('.form-action').val(axn);

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

            var settings = {
                url: patient_detail.settings.patient_red_flag_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if(json.success) {
                        modal.foundation('close');
                        window.location.reload(patient_detail.settings.patient_red_flagTab_reloadAction);
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientHealthFacilityForm: function() {
        if(jQ('.href-patient-health-facility-form').length > 0) {

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_health_facility_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();
                        patient_detail.bindPatientHealthFacilityFormAction();
                    }
                };

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

        jQ('.href-patient-health-facility-action').unbind('click.patientHealthFacilityFormAction').bind('click.patientHealthFacilityFormAction', function () {

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

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

            var settings = {
                url: patient_detail.settings.patient_health_facility_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.healthFacilityDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientSpecialistForm: function() {
        if(jQ('.href-patient-specialist-form').length > 0) {

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_specialist_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();
                        patient_detail.bindPatientSpecialistFormAction();
                    }
                };

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

        jQ('.href-patient-specialist-action').unbind('click.patientSpecialistFormAction').bind('click.patientSpecialistFormAction', function () {

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

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

            var settings = {
                url: patient_detail.settings.patient_specialist_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.specialistDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientServicesForm: function() {
        if(jQ('.href-patient-services-form').length > 0) {

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_services_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();
                        patient_detail.bindPatientServicesFormAction();
                    }
                };

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

        jQ('.href-patient-services-action').unbind('click.patientServicesFormAction').bind('click.patientServicesFormAction', function () {

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

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

            var settings = {
                url: patient_detail.settings.patient_services_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.patientServicesDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientServicesOtherForm: function() {
        if(jQ('.href-patient-services-other-form').length > 0) {

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_services_other_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();
                        patient_detail.bindPatientServicesOtherFormAction();
                    }
                };

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

        jQ('.href-patient-services-other-action').unbind('click.patientServicesOtherFormAction').bind('click.patientServicesOtherFormAction', function () {

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

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

            var settings = {
                url: patient_detail.settings.patient_services_other_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.patientServicesOtherDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientLetterNoteForm: function() {
        if(jQ('.href-patient-letter-note-form').length > 0) {

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

                var requestName = 'patient_letter_note',
                    modal = jQ('#modal-small'),
                    modalContent = jQ('#modal-content-small');
                modal.addClass('modalTop');

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_letter_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();
                        patient_detail.bindPatientLetterNoteFormAction();
                    }
                };

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

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

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

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

            var settings = {
                url: patient_detail.settings.patient_letter_note_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.patientHistoryDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientTransferForm: function() {
        if(jQ('.href-patient-transfer-form').length > 0) {

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_transfer_formUrl,
                    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();
                        patient_detail.bindPatientTransferFormAction();
                    }
                };

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

        jQ('.href-patient-transfer-action').unbind('click.patientTransferFormAction').bind('click.patientTransferFormAction', function () {

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

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

            var settings = {
                url: patient_detail.settings.patient_transfer_formActionUrl,
                type: 'POST',
                // data: _form.serialize(),
                data: {
                    patient_id : jQ('#patient-id').val(),
                    ids: patient_detail.settings.Ids,
                    type: patient_detail.settings.tranType
                },
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        patient_detail.chartDataList.draw();
                        patient_detail.fileDataList.draw();
                        patient_detail.letterDataList.draw();
                        patient_detail.billingDataList.draw();
                        patient_detail.ticketDataList.draw();
                        patient_detail.patientRedFlagDataList.draw();
                        patient_detail.patientReminderDataList.draw();
                        patient_detail.noteDataList.draw();
                        patient_detail.noteLetterDataList.draw();
                        patient_detail.noteSpecialistDataList.draw();
                        patient_detail.noteLetterDataList.draw();
                        patient_detail.noteAppointmentDataList.draw();
                        patient_detail.noteBillingDataList.draw();
                        patient_detail.noteClinicalDataList.draw();
                        patient_detail.patientHistoryDataList.draw();
                        patient_detail.settings.Ids = [];
                        patient_detail.settings.tranType = '';
                        global.flashMessage('success', json.successMessages);
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                    }
                }
            };

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

    bindPatientEmailForm: function() {
        if(jQ('.href-patient-email-form').length > 0) {

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_email_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();

                        const emailBody = CKEDITOR.replace('patient_email_customBody');
                        emailBody.on('change', function () {
                            emailBody.updateElement();
                        });


                        global.autocomplete.bind(patient_detail.settings.email_template_autocomplete_url,
                            '#patient_email_email_template_description',
                            '#patient_email_emailTemplate',
                            {
                                onSelect: function (d) {
                                    emailBody.setData(d.body);
                                }
                            }
                        );

                        patient_detail.bindPatientEmailFormAction();
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindPatientEmailFormAction: function() {
        jQ('.href-patient-email-action').unbind('click.patientEmailFormAction').bind('click.patientEmailFormAction', function () {
            var requestName = 'patientEmailFormAction',
                _form = jQ('#form-patientEmail'),
                modal = jQ('#modal-small'),
                axn = jQ(this).data('axn');
            _form.find('.form-action').val(axn);

            var formData = new FormData(jQ('#form-patientEmail')[0]);
            jQ.ajax({
                url: patient_detail.settings.patient_email_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');
                        patient_detail.patientEmailDataList.draw();
                        global.flashMessage('success', json.successMessages);
                    } else {
                        _form.find('.progress').hide();
                        global.flashMessage('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
            });
        });

        let initialIdx = jQ(".cc_row").length;
        let bindRemoveCc = function(){
            jQ(".patientEmail_removeCc_btn").unbind('click').bind('click', function(e){
                let idx = parseInt(jQ(this).data('idx'));
                jQ(`.cc_row[data-idx="${idx}"]`).remove();
            });
            console.debug('bind remove');
        };

        bindRemoveCc();

        jQ("#patientEmail_addCc_btn").unbind('click').bind('click', function(e){
            let lastIdx = initialIdx;
            jQ(".cc_row").each(function(i, el){
                lastIdx = parseInt(jQ(el).data('idx'));
            });
            let idx = lastIdx + 1,
                params =  {patient_id : patient_detail.settings.patient_id_decoded,},
                row = jQ("<div>").attr({
                    class: 'cc_row row',
                    'data-idx': idx,
                }),
                col1 = jQ("<div>").attr({
                    class: 'cc_col1 small-12 columns',
                    'data-idx': idx,
                }),
                closeBtn = `<span class="patientEmail_removeCc_btn" data-idx="${idx}"><i class="fa fa-times-circle"></i></span>`,
                emailLabel = jQ("<label>").attr({
                    for: `patientEmail_patientEmailCcs_${idx}_email`,
                    class: `hidden-cc-${idx}`,
                    id: `patientEmail_patientEmailCcs_${idx}_patient_email_label`
                }).html('Email'),
                emailTxt = jQ("<input>").attr({
                    type: 'text',
                    name: `patient_email[patientEmailCcs][${idx}][email]`,
                    id: `patientEmail_patientEmailCcs_${idx}_email`,
                    class: `patientEmail_patientEmailCcs_patient_email_label hidden-cc-${idx}`,
                }),
                idTxt = jQ("<input>").attr({
                    type: 'hidden',
                    name: `patient_email[patientEmailCcs][${idx}][id]`,
                    id: `patientEmail_patientEmailCcs_${idx}_id`,
                });
            col1.appendTo(row);
            col1.append(closeBtn);
            emailLabel.appendTo(col1);
            emailTxt.appendTo(col1);
            idTxt.appendTo(col1);
            col1.appendTo(row);
            row.appendTo("#cc_container");

            bindRemoveCc();
        });
    },

    initDataTable: function(dt_id) {

        var callBack4 = function() {
            patient_detail.bindPatientMedicalDiagnosisMedicationForm();
        };

        //Call Back for Notes
        var callBack6 = function() {
            patient_detail.bindPatientNoteForm();
            patient_detail.bindPatientTransferForm();
        };

        if (jQ.fn.DataTable.isDataTable('#'+dt_id)) {
            return;
        }
        switch (dt_id) {
            case 'patient-health-facility-datalist':

                var callBack28 = function() {
                    patient_detail.bindPatientHealthFacilityForm()
                };
                patient_detail.healthFacilityDataList = jQ('#patient-health-facility-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.patient_health_facility_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'order': [[5, 'DESC']],
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 6 },
                        { 'searchable': false, 'targets': 6 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack28();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack28);
                            }
                        }
                    }
                });

                break;
            case 'chart-datalist':

                var callBack1 = function() {
                    patient_detail.bindPatientChartForm();
                    patient_detail.bindPatientTransferForm();
                };
                patient_detail.chartDataList = jQ('#chart-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.chart_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 6 },
                        { 'searchable': false, 'targets': 6 }
                    ],
                    'order': [[3, 'desc']],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack1();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack1);
                            }
                        }
                    }
                });

                break;
            case 'panel-services':
                jQ('#patient-services-tabs').on('change.zf.tabs', function () {
                    const id = jQ(this).find('.tabs-title.is-active').data('dt-id');
                    patient_detail.initDataTable(id);
                });

                const id = jQ('#patient-services-tabs').find('.tabs-title.is-active').data('dt-id');
                patient_detail.initDataTable(id);
                break;
            case 'patient-services-other-datalist':

                var callBack20 = function() {
                    patient_detail.bindPatientServicesOtherForm();
                };
                patient_detail.patientServicesOtherDataList = jQ('#patient-services-other-datalist').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_services_other_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 5},
                        {searchable: false, targets: 5}
                    ],
                    orderClasses: false,
                    order: [[3, 'desc']],
                    drawCallback: callBack20,
                    createdRow: function(row) {
                        jQ(jQ(row).children()[4]).addClass('text-right');
                        jQ(jQ(row).children()[5]).addClass('text-center');
                    },
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack20);
                            }
                        }
                    }
                });

                break;
            case 'patient-services-datalist':

                var callBack19 = function() {
                    patient_detail.bindPatientServicesForm();
                };
                patient_detail.patientServicesDataList = jQ('#patient-services-datalist').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_services_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 5},
                        {searchable: false, targets: 5}
                    ],
                    orderClasses: false,
                    order: [[3, 'desc']],
                    drawCallback: callBack19,
                    createdRow: function(row) {
                        jQ(jQ(row).children()[4]).addClass('text-right');
                        jQ(jQ(row).children()[5]).addClass('text-center');
                    },
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack19);
                            }
                        }
                    }
                });

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

                const id2 = jQ('#patient-medical-tabs').find('.tabs-title.is-active').data('dt-id');
                patient_detail.initDataTable(id2);

                for (let i = 0 ; i < patient_detail.settings.diagnosis_key ; i++){

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

                break;
            case 'patient-medical-diagnosis-datalist' :

                var callBack3 = function() {
                    patient_detail.bindPatientMedicalDiagnosisForm()
                };
                patient_detail.medicalDiagnosisDataList = jQ('#patient-medical-diagnosis-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.medical_diagnosis_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_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-treatment-consideration-datalist' :

                var callBack24 = function() {
                    patient_detail.bindPatientTreatmentConsiderationForm();
                };
                patient_detail.patientTreatmentConsiderationDataList = jQ('#patient-treatment-consideration-datalist').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_treatment_consideration_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 4},
                        {searchable: false, targets: 4}
                    ],
                    orderClasses: false,
                    order: [[3, 'desc']],
                    drawCallback: callBack24,
                    createdRow: function(row) {
                        jQ(jQ(row).children()[3]).addClass('');
                        jQ(jQ(row).children()[4]).addClass('');
                    },
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack24);
                            }
                        }
                    }
                });

                break;
            case 'patient-treatment-plan-datalist' :

                var callBack25 = function() {
                    patient_detail.bindPatientTreatmentPlanForm();
                };
                patient_detail.patientTreatmentPlanDataList = jQ('#patient-treatment-plan-datalist').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_treatment_plan_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 4},
                        {searchable: false, targets: 4}
                    ],
                    orderClasses: false,
                    order: [[3, 'desc']],
                    drawCallback: callBack25,
                    createdRow: function(row) {
                        jQ(jQ(row).children()[3]).addClass('');
                        jQ(jQ(row).children()[4]).addClass('');
                    },
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack25);
                            }
                        }
                    }
                });

                break;
            case 'patient-schedule-datalist':

                var callBack7 = function() {
                    patient_detail.bindPatientAppointmentNoticeFaxForm();
                    patient_detail.bindPatientAppointmentNoticeFaxRowButton();
                };
                patient_detail.scheduleDataList = jQ('#patient-schedule-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.schedule_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 8 },
                        { 'searchable': false, 'targets': 8 }
                    ],
                    'orderClasses': false,
                    order: [[2, 'desc']],
                    drawCallback: callBack7,
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack7);
                            }
                        }
                    }
                });
                var callBackAppointment = function() {
                    global.askContinue();
                };
                jQ('#appointmentNoticeFax-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.appointmentNoticeFax_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 4 },
                        { 'searchable': false, 'targets': 4 }
                    ],
                    'orderClasses': false,
                    order: [[0, 'desc']],
                    drawCallback: callBackAppointment,
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx);
                            }
                        }
                    }
                });
                break;
            case 'panel-affiliation':
                jQ('#patient-affiliation-tabs').on('change.zf.tabs', function () {
                    const id = jQ(this).find('.tabs-title.is-active').data('dt-id');
                    patient_detail.initDataTable(id);
                });

                const id3 = jQ('#patient-affiliation-tabs').find('.tabs-title.is-active').data('dt-id');
                patient_detail.initDataTable(id3);
                break;
            case 'patient-insurance-datalist' :

                var callBack5 = function() {
                    patient_detail.bindPatientInsuranceForm()
                };
                patient_detail.insuranceDataList = jQ('#patient-insurance-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.insurance_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 9 },
                        { 'searchable': false, 'targets': 9 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack5();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack5);
                            }
                        }
                    }
                });

                break;
            case 'patient-referring-health-facility-datalist' :

                var callBack9 = function() {
                    patient_detail.bindPatientReferringHealthFacilityForm()
                };
                patient_detail.referringHealthFacilityDataList = jQ('#patient-referring-health-facility-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.patient_referring_health_facility_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 7 },
                        { 'searchable': false, 'targets': 7 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack9();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack9);
                            }
                        }
                    }
                });

                break;
            case 'patient-referring-provider-datalist' :

                var callBack10 = function() {
                    patient_detail.bindPatientReferringProviderForm();
                };
                patient_detail.referringProviderDataList = jQ('#patient-referring-provider-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.patient_referring_provider_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 7 },
                        { 'searchable': false, 'targets': 7 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack10();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack10);
                            }
                        }
                    }
                });

                break;
            case 'file-datalist' :

                var callBack2 = function() {
                    patient_detail.bindPatientFileForm();
                    patient_detail.bindPatientTransferForm();
                };
                patient_detail.fileDataList = jQ('#file-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.file_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_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, callBack2);
                            }
                        }
                    }
                });

                break;

            case 'clinicmasterFile-datalist' :

                patient_detail.clinicmasterFileDataList = jQ('#clinicmasterFile-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.clinicmasterFile_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'deferRender': true,
                    'orderClasses': false,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 1 },
                        { 'searchable': false, 'targets': 1 }
                    ],
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack2);
                            }
                        }
                    }
                });

                break;

            case 'patient-letter-datalist' :

                var callBack8 = function() {
                    patient_detail.bindPatientLetterForm();
                    patient_detail.bindPatientLetterNoteForm();
                    patient_detail.bindPatientLetterRowButton();
                    patient_detail.bindPatientTransferForm();
                    global.askContinue();
                }, actionCol = jQ('#patient-letter-datalist th').length - 1;
                patient_detail.letterDataList = jQ('#patient-letter-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.patient_letter_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.letter_status = jQ("#letter_status").val();
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'order': [[0,'desc']],
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': actionCol },
                        { 'searchable': false, 'targets': actionCol }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack8();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack8);
                            }
                        }
                    }
                });
                jQ('#letter_status').on('change', function(){
                    patient_detail.letterDataList.draw();
                });

                if(patient_detail.settings.letterId != null || patient_detail.settings.letterId != '') {
                    patient_detail.letterDataList.search(patient_detail.settings.letterId).draw();
                }

                break;
            case 'patient-email-datalist' :

                var callBack26 = function() {
                    patient_detail.bindPatientEmailForm();
                    patient_detail.bindPatientLetterRowButton();
                    global.askContinue();
                }, actionCol2 = jQ('#patient-email-datalist th').length - 1;
                patient_detail.patientEmailDataList = jQ('#patient-email-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.patient_email_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.status = jQ("#email_status").val();
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'order': [[0,'desc']],
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': actionCol2 },
                        { 'searchable': false, 'targets': actionCol2 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack26();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack26);
                            }
                        }
                    }
                });
                jQ('#email_status').on('change', function(){
                    patient_detail.patientEmailDataList.draw();
                });

                break;
            case 'panel-billing':
                jQ('#patient-billing-tabs').on('change.zf.tabs', function () {
                    const id = jQ(this).find('.tabs-title.is-active').data('dt-id');
                    patient_detail.initDataTable(id);
                });

                const id4 = jQ('#patient-billing-tabs').find('.tabs-title.is-active').data('dt-id');
                patient_detail.initDataTable(id4);
                break;
            case 'patientBilling-datalist' :

                var callBack11 = function() {
                    patient_detail.bindPatientBillingForm();
                    patient_detail.bindPatientTransferForm();
                };
                patient_detail.billingDataList = jQ('#patientBilling-datalist').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_billing_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                            d.status = jQ('#billing-status').val();
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 9},
                        {searchable: false, targets: 9}
                    ],
                    orderClasses: false,
                    order: [[0, 'desc']],
                    drawCallback: callBack11,
                    createdRow: function(row, data) {
                        // if(data[8] !== '0.00' && data[2] !== 'Void'){
                        if(parseFloat(data[9]) >= 0 && (data[2] === "Pending Payment" || data[2] === "Pending Billing")){
                            jQ(jQ(row).children()[9]).css('color', 'red');
                        }
                        jQ(jQ(row).children()[6]).addClass('text-right');
                        jQ(jQ(row).children()[7]).addClass('text-right');
                        jQ(jQ(row).children()[8]).addClass('text-right');
                        jQ(jQ(row).children()[9]).addClass('text-center');
                    },
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack11);
                            }
                        }
                    },
                });

                jQ('#billing-status').on('change', function(){
                    patient_detail.billingDataList.draw();
                });

                if(patient_detail.settings.invoiceNo != null || patient_detail.settings.invoiceNo != '') {
                    patient_detail.billingDataList.search(patient_detail.settings.invoiceNo).draw();
                }

                break;
            case 'patient-rental-datalist' :

                var callBack23 = function() {
                    patient_detail.bindPatientRentalForm();
                };
                patient_detail.patientRentalDataList = jQ('#patient-rental-datalist').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_rental_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 6},
                        {searchable: false, targets: 6}
                    ],
                    orderClasses: false,
                    order: [[3, 'desc']],
                    drawCallback: callBack23,
                    createdRow: function(row) {
                        jQ(jQ(row).children()[4]).addClass('');
                        jQ(jQ(row).children()[5]).addClass('');
                    },
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack23);
                            }
                        }
                    }
                });

                break;
            case 'patientPayment-datalist' :

                var callBack12 = function() {
                    patient_detail.bindPatientPaymentForm();
                };
                patient_detail.paymentDataList = jQ('#patientPayment-datalist').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_payment_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                            d.status = jQ('#payment-status').val();
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 6},
                        {searchable: false, targets: 6}
                    ],
                    orderClasses: false,
                    order: [[3, 'desc']],
                    drawCallback: callBack12,
                    createdRow: function(row, data) {
                        if(data[1] == 'Pending'){
                            jQ(jQ(row).children()[1]).css('color', 'red');
                        }
                        if(data[5] == '0.00'){
                            jQ(jQ(row).children()[4]).css('color', 'red');
                        }
                        jQ(jQ(row).children()[5]).addClass('text-right');
                        jQ(jQ(row).children()[6]).addClass('text-center');
                    },
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack12);
                            }
                        }
                    }
                });
                jQ('#payment-status').on('change', function(){
                    patient_detail.paymentDataList.draw();
                });

                if(patient_detail.settings.invoiceNo != null || patient_detail.settings.invoiceNo != '') {
                    patient_detail.paymentDataList.search(patient_detail.settings.invoiceNo).draw();
                }

                break;
            case 'patient_billing_refund-datalist' :

                var callBack21 = function() {
                    patient_detail.bindPatientBillingRefundForm();
                };
                patient_detail.patientBillingRefundDataList = jQ('#patient_billing_refund-datalist').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_billing_refund_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 4},
                        {searchable: false, targets: 4}
                    ],
                    orderClasses: false,
                    order: [[3, 'desc']],
                    drawCallback: callBack21,
                    createdRow: function(row) {
                        jQ(jQ(row).children()[4]).addClass('text-right');
                        jQ(jQ(row).children()[5]).addClass('text-center');
                    },
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack21);
                            }
                        }
                    }
                });

                break;

            case 'patient-red-flag-datalist' :

                var callBack14 = function() {
                    patient_detail.bindPatientRedFlagForm();
                    patient_detail.bindPatientTransferForm();
                };
                patient_detail.patientRedFlagDataList = jQ('#patient-red-flag-datalist').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_red_flag_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 3},
                        {searchable: false, targets: 3}
                    ],
                    orderClasses: false,
                    order: [[2, 'desc']],
                    drawCallback: callBack14,
                    createdRow: function(row) {
                        jQ(jQ(row).children()[4]).addClass('text-right');
                        jQ(jQ(row).children()[5]).addClass('text-center');
                    },
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack14);
                            }
                        }
                    }
                });

                break;

            case 'patient-purchased-items-dt' :

                var callBackPurchasedItems = function() {
                    patient_detail.bindPatientPurchasedItemsForm();
                };
                patient_detail.patientPurchasedItemsDataList = jQ('#patient-purchased-items-dt').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_purchased_items_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 4},
                        {searchable: false, targets: 4}
                    ],
                    orderClasses: false,
                    order: [[3, 'desc']],
                    drawCallback: callBackPurchasedItems,
                    createdRow: function(row) {
                        jQ(jQ(row).children()[4]).addClass('text-center');
                    },
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack14);
                            }
                        }
                    }
                });

                break;

            case 'patient-ticket-datalist' :

                var callBack18 = function() {
                    // patient_detail.bindPatientTicketForm();
                    patient_detail.bindPatientTransferForm();
                };
                patient_detail.ticketDataList = jQ('#patient-ticket-datalist').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_ticket_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 7},
                        {searchable: false, targets: 7}
                    ],
                    orderClasses: false,
                    order: [[2, 'desc']],
                    drawCallback: callBack18,
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack18);
                            }
                        }
                    }
                });

                break;

            case 'patient-reminder-datalist' :

                var callBack22 = function() {
                    patient_detail.bindPatientReminderForm();
                    patient_detail.bindPatientTransferForm();
                };
                patient_detail.patientReminderDataList = jQ('#patient-reminder-datalist').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: patient_detail.settings.patient_reminder_ajaxUrl,
                        data: function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    deferRender: true,
                    columnDefs: [
                        {orderable: false, targets: 5},
                        {searchable: false, targets: 5}
                    ],
                    orderClasses: false,
                    order: [[3, 'desc']],
                    drawCallback: callBack22,
                    createdRow: function(row) {
                        jQ(jQ(row).children()[4]).addClass('');
                        jQ(jQ(row).children()[5]).addClass('');
                    },
                    responsive: {
                        details: {
                            renderer: function(api, rowIdx) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack22);
                            }
                        }
                    }
                });

                break;

            case 'patient-history-datalist' :

                var callBack13 = function() {
                };
                patient_detail.patientHistoryDataList = jQ('#patient-history-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.patient_history_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            // d.status = jQ("#status").val();
                        }
                    },
                    order: [[1, 'DESC']],
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': [0,1,2,3,4] }
                    ],
                    drawCallback: function() {
                        callBack13();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack13);
                            }
                        }
                    }
                });

                break;
            case 'panel-notes':
                jQ('#patient-note-tabs').on('change.zf.tabs', function () {
                    const id = jQ(this).find('.tabs-title.is-active').data('dt-id');
                    patient_detail.initDataTable(id);
                });

                const id5 = jQ('#patient-note-tabs').find('.tabs-title.is-active').data('dt-id');
                patient_detail.initDataTable(id5);
                break;
            case 'patient-note-clinical-datalist' :

                patient_detail.noteClinicalDataList = jQ('#patient-note-clinical-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.note_clinical_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'order': [[0, 'DESC']],
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 3 },
                        { 'searchable': false, 'targets': 3 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack6();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack6);
                            }
                        }
                    }
                });

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

                patient_detail.noteBillingDataList = jQ('#patient-note-billing-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.note_billing_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'order': [[0, 'DESC']],
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 3 },
                        { 'searchable': false, 'targets': 3 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack6();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack6);
                            }
                        }
                    }
                });

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

                patient_detail.noteAppointmentDataList = jQ('#patient-note-appointment-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.note_appointment_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'order': [[0, 'DESC']],
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 3 },
                        { 'searchable': false, 'targets': 3 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack6();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack6);
                            }
                        }
                    }
                });

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

                patient_detail.noteSpecialistDataList = jQ('#patient-note-specialist-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.note_specialist_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'order': [[0, 'DESC']],
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 3 },
                        { 'searchable': false, 'targets': 3 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack6();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack6);
                            }
                        }
                    }
                });

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

                patient_detail.noteLetterDataList = jQ('#patient-note-letter-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.note_letter_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_id;
                        }
                    },
                    'order': [[0, 'DESC']],
                    'deferRender': true,
                    'columnDefs': [
                        { 'orderable': false, 'targets': 3 },
                        { 'searchable': false, 'targets': 3 }
                    ],
                    'orderClasses': false,
                    drawCallback: function() {
                        callBack6();
                    },
                    responsive: {
                        details: {
                            renderer: function( api,rowIdx ) {
                                return global.dataTableResponsiveCallBack(api, rowIdx, callBack6);
                            }
                        }
                    }
                });

                break;
            case 'patient-note-datalist' :
                patient_detail.noteDataList = jQ('#patient-note-datalist').DataTable({
                    'processing': true,
                    'serverSide': true,
                    'ajax': {
                        'url': patient_detail.settings.note_ajaxUrl,
                        'data': function(d) {
                            d.url = global.settings.url;
                            d.patient_id = patient_detail.settings.patient_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;
        }

        return;

        //Affiliation specialist is not used
        var callBack16 = function() {
            patient_detail.bindPatientSpecialistForm();
        };
        patient_detail.specialistDataList = jQ('#patient-specialist-datalist').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: patient_detail.settings.patient_specialist_ajaxUrl,
                data: function(d) {
                    d.url = global.settings.url;
                    d.patient_id = patient_detail.settings.patient_id;
                }
            },
            deferRender: true,
            columnDefs: [
                {orderable: false, targets: 5},
                {searchable: false, targets: 5}
            ],
            orderClasses: false,
            order: [[2, 'desc']],
            drawCallback: callBack16,
            createdRow: function(row) {
                jQ(jQ(row).children()[4]).addClass('text-right');
                jQ(jQ(row).children()[5]).addClass('text-center');
            },
            responsive: {
                details: {
                    renderer: function(api, rowIdx) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBack16);
                    }
                }
            }
        });

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

    bindPatientExportHl7: function() {
        if(jQ('.href-export-to-hl7').length > 0) {

            jQ('.href-export-to-hl7').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: patient_detail.settings.patient_export_hl7_formUrl,
                    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();
                        patient_detail.bindPatientExportHl7FormAction();
                    }
                };

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

    bindPatientExportHl7FormAction: function() {

        jQ('.href-patient-export-hl7-action').unbind('click.patientExportHl7FormAction').bind('click.patientExportHl7FormAction', function () {
            jQ('.href-patient-export-hl7-action').addClass('disabled').removeClass('href-patient-export-hl7-action');
            var type = jQ("#hl7_message_type").val();
            location.href = (patient_detail.settings.patient_export_hl7_formActionUrl + "?type=" + type);
            setTimeout(function(){
                jQ('#modal-small').foundation('close');
                global.flashMessage('success', [type + ' HL7 File is now downloading.']);
            }, 1000)
        });
    },
};