//DoctorPrescription Screen Js//

$(document).ready(function () {

    //if (parseInt($('#hiddenRole_id').val()) == 1) {
    //    PrintDoctor();
    //}
    PrintDoctor();
    loadMedicineType();
    loadwhentoeat();
    //ShowPrescription();
    //loadpharmacyid();
    templatelist();  
    Medicine_Frequency();
    loadmedicineprescription();
});

var medicinetypearray = [];
var whentotakearray = [];
var frequencyarray = [];
var SubmitArr = [];
var IPDoctorArr = [];

function PrintDoctor() {
    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#branch_id').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            $('#ddRefDoctor').empty();
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    var RefDoctor = '';

                    var default_opt = '<option value="0">--Select--</option>';

                    IPDoctorArr = data1;

                    //if (data1.length > 0) {
                    //    for (var i = 0; i < data1.length; i++) {

                    //        if (parseInt($('#hiddenRole_id').val()) == 1) {
                    //            $('#txtDoctorName').prop('readonly', true);
                    //            $('#txtDoctorName').val(data1[i].first_name);
                    //            $('#Hdndoctor_name').val(data1[i].first_name);
                    //        }
                    //    }  
                    //}
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function ShowPrescription() {
    var Prescriptiondata = {

        Dml_Indicator: "PS",
        ip_Indicator: "IP",
        visit_report_id: $("#IPVisitReport_Id").val(),
        is_discharge_medicine: 0
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Prescriptiondata),
        success: function (data) {

            var data2 = JSON.parse(data);
            if (data2.msg == "Success") {
                var data1 = data2.data;

                tr = $('<table id="example1" class="table table-responsive table-bordered table-striped dataTable " />');

                tr.append("<thead><tr><th>Types</th><th>Medicine</th><th>When to take</th><th>Duration</th><th>Doctor Instruction</th><th>Frequency</th><th>Route</th><th>Doctor Name</th><th>Created DateTime</th><th>Action</th></tr></thead><tbody>");

                $.each(data1, function (i, emp) {
                    var PaseStart = "", Delete = "";

                    view = "<a href=# class='label label-success'onclick=loadPrescription('" + emp.medicine_prescription_id + "');>Edit</a>";

                    if (emp.ip_medicine_status == 1) {
                        PaseStart = "<a id='Pause' href=# class='label label-success'onclick=Pause('" + emp.medicine_prescription_id + "');>pause</a>";
                    }
                    else {
                        PaseStart = "<a id='Start' href=# class='label label-success'onclick=Start('" + emp.medicine_prescription_id + "');>Start</a>";
                    }

                    Delete = '<button type="button" class="btn btn-delete btn-xs" data-id="CD_D1" data-toggle="tooltip" data-placement="bottom" title="Delete" data-type="role_rights_delete" data-nav="sp_div" data-name="delete_Prescription" onclick=DeletePrescription(' + emp.medicine_prescription_id + ');><i class="fa fa-trash-o" aria-hidden="true"></i></button>';

                    var generic_name = '';
                    if (emp.generic_name == '' || emp.generic_name == null) {
                        generic_name = '';
                    }
                    else {
                        generic_name = '<span style=font-size:11sssssspx;><i>(' + emp.generic_name + ')</i></span>';
                    }

                    var session = '', morning = '0', afternoon = '0', evening = '0', night = '0';
                    if (emp.morning != '' && emp.morning != null) {

                        morning = emp.morning.split('.');

                        if (morning.length > 1) {
                            if (morning[1] == 5 || morning[1] == 50 || morning[1] == 05) {
                                if (morning[0] == 0) {
                                    morning = '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                                else {
                                    morning = morning[0] + '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                            }
                            else if (morning[1] == 25) {
                                if (morning[0] == 0) {
                                    morning = '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    morning = morning[0] + '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else if (morning[1] == 75) {
                                if (morning[0] == 0) {
                                    morning = '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    morning = morning[0] + '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else {
                                morning = emp.morning;
                            }
                        }
                        else { morning = emp.morning; }
                    }
                    if (emp.afternoon != '' && emp.afternoon != null) {
                        afternoon = emp.afternoon;
                        afternoon = afternoon.split('.');
                        if (afternoon.length > 1) {
                            if (afternoon[1] == 5 || afternoon[1] == 50 || afternoon[1] == 05) {
                                if (afternoon[0] == 0) {
                                    afternoon = '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                                else {
                                    afternoon = afternoon[0] + '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                            }
                            else if (afternoon[1] == 25) {
                                if (afternoon[0] == 0) {
                                    afternoon = '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    afternoon = afternoon[0] + '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else if (afternoon[1] == 75) {
                                if (afternoon[0] == 0) {
                                    afternoon = '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    afternoon = afternoon[0] + '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else {
                                afternoon = emp.afternoon;
                            }
                        }
                        else { afternoon = emp.afternoon; }
                    }
                    if (emp.evening != '' && emp.evening != null) {
                        evening = emp.evening.split('.');
                        if (evening.length > 1) {
                            if (evening[1] == 5 || evening[1] == 50 || evening[1] == 05) {
                                if (evening[0] == 0) {
                                    evening = '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                                else {
                                    evening = evening[0] + '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                            }
                            else if (evening[1] == 25) {
                                if (evening[0] == 0) {
                                    evening = '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    evening = evening[0] + '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else if (evening[1] == 75) {
                                if (evening[0] == 0) {
                                    evening = '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    evening = evening[0] + '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else {
                                evening = emp.evening;
                            }
                        }
                        else { evening = emp.evening; }
                    }
                    if (emp.night != '' && emp.night != null) {
                        night = emp.night.split('.');

                        if (night.length > 1) {
                            if (night[1] == 5 || night[1] == 50 || night[1] == 05) {
                                if (night[0] == 0) {
                                    night = '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                                else {
                                    night = night[0] + '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                            }
                            else if (night[1] == 25) {
                                if (night[0] == 0) {
                                    night = '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    night = night[0] + '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else if (night[1] == 75) {
                                if (night[0] == 0) {
                                    night = '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    night = night[0] + '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else {
                                night = emp.night;
                            }
                        }
                        else { night = emp.night; }
                    }
                    if (emp.evening == '' || emp.evening == null || emp.evening == 0) {
                        session = morning + ' - ' + afternoon + ' - ' + night;
                    }
                    else {
                        session = morning + ' - ' + afternoon + ' - ' + evening + ' - ' + night;
                    }

                    var color = '';
                    if (emp.priority == 1) {
                        color = '<i class=" fa fa-circle" style="color:green"></i>&nbsp;';
                    }
                    else if (emp.priority == 2) {
                        color = '<i class=" fa fa-play" style="color:orange"></i>&nbsp;';
                    }
                    else if (emp.priority == 3) {
                        color = '<i class=" fa fa-square" style="color:#418bfe"></i>&nbsp;';
                    }
                    else {
                        color = '<i class=" fa fa-circle" style="color:#ffffff"></i>&nbsp;';
                    }

                    row_data = "<tr><td>" + emp.medicine_type + "</td><td style='text-transform: capitalize;'>" + color + emp.medicine_name + generic_name + "</td><td>" + emp.when_to_eat_value + "</td><td>" + emp.days_to_take + "</td><td>" + emp.instructions + "</td><td>" + session + "</td><td>" + ((emp.iproute != null && emp.iproute != "") ? emp.iproute : "-") + "</td><td>" + ((emp.ipdoctor_name != null && emp.ipdoctor_name != "") ? emp.ipdoctor_name : "-") + "</td><td>" + emp.created_on + "</td><td>" + view + " " + PaseStart + " " + Delete + "</td></tr>";
                    tr.append(row_data);
                });
                tr.append("</tbody></table>");
                $('#tbl-medicine').html(tr);
            }
            else {
                console.log(data);
            }
        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}

function DeletePrescription(id) {

    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", 'Are You Sure, You Want to Delete?',
          {

              closeButton: true,
              progressBar: true,
              allowHtml: true,
              timeOut: 20000000,

              onShown: function (toast) {
                  $("#confirmationRevertYes").click(function () {

                      var Prescriptiondata = {

                          Dml_Indicator: "IPD",
                          ip_Indicator: "IP",
                          medicine_prescription_id: id,
                          ip_prescription_status: 0
                      }

                      $.ajax({
                          async: true,
                          type: 'POST',
                          url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
                          contentType: 'application/json; charset=UTF-8',
                          data: JSON.stringify(Prescriptiondata),
                          success: function (data) {

                              var data2 = JSON.parse(data);
                              if (data2.msg == "Success") {

                                  toastr.success('Deleted Successfully.');

                                  ShowPrescription();

                              }
                              else {
                                  console.log(data);
                              }
                          },
                          error: function (data) {
                              toastr.warning('some issue');
                          }
                      });
                  });
              }
          })
}

function templatelist() {
    var Template = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'S',
        is_ip: 1
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Medicine_template',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var data2 = JSON.parse(data);
            var tr = '';
            if (jQuery.isEmptyObject((data2.data))) {
                // Type 2- diet, Type 1-lab , Type 3- prescription to make therespective tab active in template page
                tr = tr + '<a href="/Template/Index?Type=3"><div class="pull-left">Click To Add Prescription Template</div><div class="clearfix"></div></a>';
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;

                    if (data.length <= 0) {
                        // Type 2- diet, Type 1-lab , Type 3- prescription to make therespective tab active in template page
                        tr = tr + '<a href="/Template/Index?Type=3"><div class="pull-left">Click To Add Prescription Template</div><div class="clearfix"></div></a>';
                    }
                    else {
                        for (var i = 0; i < data.length; i++) {
                            tr = tr + '<a href="javascript:void(0)" class="Clscopytemplate" onclick=copytemplate(' + data[i].medicine_template_id + ');><div class="pull-left">' + data[i].template_name + '</div><div class="clearfix"></div><br></a>';
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
            $('#templatelist').html(tr);
            
        }
    });
}

function copytemplate(medicineTemplateId) {
    $('.Clscopytemplate').hide();
    $('#loaderimg').show();

    var VisitreportId = {
        medicine_template_id: medicineTemplateId,
        patient_id: $("#IPPatient_Id").val(),
        visit_report_id: $('#IPVisitReport_Id').val(),
        Dml_Indicator: 'PTI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Medicine_template',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {

            var data2 = JSON.parse(data);

            if (jQuery.isEmptyObject((data2.data))) {
                $('#Ptbl-medicine').show();
                $('#Ptbl-medicine').fadeOut(8000);
                $('#Ptbl-medicine').html('No medicine prescribed during previous data found');
                $('#Ptbl-medicine').focus();
                $('#Ptbl-medicine').val('');
                return false;
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    //ShowPrescription();
                    loadmedicineprescription();
                }
                else {
                    console.log(data);
                }
            }
            $('.Clscopytemplate').show();
            $('#loaderimg').hide();
        }
    });
}

function loadMedicineType() {

    var params = {
        Dml_Indicator: '',
        medicine_type_id: 0,
        medicine_type: $('#HiddenDoctorID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/MedicineType',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(params),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var medicine;
                    $('#SelMedicineType').empty();
                    medicinetypearray = data1;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        medicine = medicine + '<option value="' + emp.medicine_type_id + '">' + emp.medicine_type + '</option>';
                    });
                    $('#SelMedicineType').append(default_opt + medicine);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
    //PatientNeuropathyLoad();
}

function loadwhentoeat() {

    var VisitreportId = {
        Dml_Indicator: 'MS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    debugger;
                    var data1 = data2.data;

                    $('#hndwenttoeat').empty();
                    whentotakearray = [];
                    whentotakearray = data1;
                    trs = '';
                    for (var i = 0; i < data1.length; i++) {
                        trs = trs + '<option value="' + data1[i].when_to_eat_id + '">' + data1[i].when_to_eat_value + '</option>';
                    }
                    $('#hndwenttoeat').append(trs);
                }
                else {
                    console.log(data);
                }
            }
        }

    });
}


$('#txtDoctorName').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, branch_id: $('#branch_id').val() },
            success: function (data) {
                debugger;
               // var data2 = JSON.parse(data);
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname };
                }))
            }
        })
    },
    select: function (event, ui) {
        $('#Hdndoctor_name').val(ui.item.value);
    }
});

//$('#ADD_Medicine').on("click", function () {
$(document).on('click', '#ADD_Medicine', function () {
    debugger;

    if ($.trim($('#SelMedicineType :selected').val()) == "" || $('#SelMedicineType :selected').val() == "0") {
        $('#PSelMedicineType').show();
        $('#PSelMedicineType').fadeOut(8000);
        $('#PSelMedicineType').html('Select Types');
        $('#SelMedicineType').focus();
        $('#SelMedicineType :selected').val('0');
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }

    if ($.trim($('#medicine_name').val()) == "") {
        $('#Pmedicine_name').show();
        $('#Pmedicine_name').fadeOut(8000);
        $('#Pmedicine_name').html('Enter Medicine Name');
        $('#medicine_name').focus();
        $('#medicine_name').val('');
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }

    var priority = $("input[name='optradio']:checked").val();
    var mor = $('#mor').val();
    var aft = $('#aft').val();
    var nit = $('#nit').val();
    if ($('#days').val().length == 0 || $('#days').val() == '') {
        $('#Pdays').show();
        $('#Pdays').fadeOut(8000);
        $('#Pdays').html('Enter Duration');
        $('#days').focus();
        return false;
    }
    if (mor > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#mor').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }
    if (aft > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#aft').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }
    if (nit > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#nit').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }

    if ($.trim($('#txtDoctorName').val()) != "") {

        if ($.trim($('#Hdndoctor_name').val()) == "") {
            $('#PtxtDoctorName').show();
            $('#PtxtDoctorName').fadeOut(8000);
            $('#PtxtDoctorName').html('Enter Valid Doctor Name');
            $('#txtDoctorName').focus();
            $('#txtDoctorName').val('');

            return false;
        }
    }

    var Durations = $('#hndduration').val();

    var WhenEat = $('#hndwenttoeat').val();
    var day = $('#days').val();
    if (day == '' || day == null) {
    }
    else {
        var days = 0;
        if (Durations == 1) {
            days = day;
        }
        else if (Durations == 2) {
            days = ((day) * (7));
        }
        else if (Durations == 3) {
            days = ((day) * (30));
        }
        else {

        }
    }
    var days1 = days;




    var medicineType = $('#dosage').val();
    var max_quantity = parseFloat(mor) + parseFloat(aft) + parseFloat(nit);
    max_quantity = parseFloat(max_quantity) * parseFloat($('#days').val());



    var mdPescription = {
        Dml_Indicator: 'IPI',
        ip_Indicator: "IP",
        patient_id: $("#IPPatient_Id").val(),
        visit_report_id: $("#IPVisitReport_Id").val(),
        medicine_type_id: $('#SelMedicineType').val(),
        medicine_name: $('#medicine_name').val(),
        how_to_take: $('#hndwenttoeat').val(),
        morning: mor,
        afternoon: aft,
        evening: $('#eve').val(),
        night: nit,
        days_to_take: days,
        pmedicine_dosage: $('#dosage').val(),
        medicine_dosage: $('#dosage').val(),
        medicine_type: $('#SelUnit').val(),
        doctor_id: $('#doctorId').val(),
        slot_start_time: $('#Hdnappointment_date').val(),
        instructions: $('#prescriptionNotes').val(),
        medicine_unit: $('#SelUnit').val(),
        generic_name: $('#txtGenericName').val(),
        max_quantity: max_quantity,
        pharmacy_id: $('#txtPharmacyID').val(),
        medicine_id: $('#txtMedicineID').val(),
        iproute: $("#ddRoute").val(),
        ipdoctor_name: $("#txtDoctorName").val(),
        medicine_prescription_id: $("#HPrescriptionID").val(),
        is_discharge_medicine: 0,
        priority: priority
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(mdPescription),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {

                if (data1.msg == "Success") {
                    debugger;
                    var data1 = data1.data;
                    if (data1.length > 0) {
                        if ($("#HPrescriptionID").val() == "") {
                            toastr.success('Prescription Added Successfully',
                            {
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });
                        }
                        else {

                            toastr.success('Prescription Updated Successfully',
                            {
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });

                        }



                        ShowPrescription();
                        clearPrescription();
                    }
                    else {
                        toastr.warning('Unable to add the Prescription',
                            {
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });
                    }

                }
                else {
                    console.log(data);
                }

            }
        }
    });
});

function clearPrescription() {

    if (parseInt($('#hiddenRole_id').val()) == 2) {

        $('#txtDoctorName').val('');
        $('#Hdndoctor_name').val('');
    }
    $('#SelMedicineType').val(0),
    $("#medicine_name").val(""),
    $("#hndwenttoeat").val(""),
    $("#days").val(""),
    $("#mor").val(""),
    $('#aft').val(""),
    $('#nit').val("");
    $("#ddRoute").val(""),
    //$("#txtDoctorName").val(""),
    $("#prescriptionNotes").val(""),
    $("#HPrescriptionID").val(""),
    $('#txtGenericName').val('');
    $("#high").prop("checked", false);
    $("#medium").prop("checked", false);
    $("#low").prop("checked", false);

    //duration reset
    $('#duration_days').prop('checked', true);
    $('#duration_week').prop('checked', false);
    $('#duration_month').prop('checked', false);
    $('p.duration_days').addClass('text_before_btn');
    $('p.duration_week').removeClass('text_before_btn');
    $('p.duration_month').removeClass('text_before_btn');
    $('.duration_disp').html('Days');
    $('#hndduration').val(1);
    $('#setDurationUnit').text('Days');
    $("input[name='optradio']").prop('checked', false);
}

function loadPrescription(val) {
    if($("#IPDischarge_Id").val() != "2")
    {
        var Prescriptiondata = {
            medicine_prescription_id: val,
            Dml_Indicator: 'IPID',
            ip_Indicator: "IP",
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Prescriptiondata),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                }
                else {

                    if (data2.msg == "Success") {
                        var data1 = data2.data;

                        $.each(data1, function (i, emp) {
                            $('#SelMedicineType').val(emp.medicine_type_id),
                            $("#medicine_name").val(emp.medicine_name),
                            $("#hndwenttoeat").val(emp.how_to_take),
                            $("#days").val(emp.days_to_take),
                            $("#mor").val(emp.morning),
                            $('#aft').val(emp.afternoon),
                            $('#nit').val(emp.night);
                            $('#eve').val(emp.evening);
                            $("#ddRoute").val(emp.iproute),
                            $("#txtDoctorName").val(emp.ipdoctor_name),
                            $('#Hdndoctor_name').val(emp.ipdoctor_name),
                            $("#prescriptionNotes").val(emp.instructions),
                            $("#HPrescriptionID").val(emp.medicine_prescription_id)
                            $('#txtGenericName').val(emp.generic_name);
                            $("#high").prop("checked", false);
                            $("#medium").prop("checked", false);
                            $("#low").prop("checked", false);

                            $('#days').val(emp.days_to_take);
                            $('#duration_days').prop('checked', true);
                            $('#duration_week').prop('checked', false);
                            $('#duration_month').prop('checked', false);
                            $('p.duration_days').addClass('text_before_btn');
                            $('p.duration_week').removeClass('text_before_btn');
                            $('p.duration_month').removeClass('text_before_btn');
                            $('.duration_disp').html('Days');
                            $('#hndduration').val(1);
                            $('#setDurationUnit').text('Days');

                            if (emp.priority == 3) {
                                $("#high").prop("checked", true);
                            }
                            else if (emp.priority == 2) {
                                $("#medium").prop("checked", true);
                            }
                            else if (emp.priority == 1) {
                                $("#low").prop("checked", true);
                            }
                            else { }

                            if (emp.how_to_take == 9 || emp.how_to_take == 10) {
                                $('#eveningSession').show();
                                $('.alltime').removeClass('col-lg-3');
                                $('.alltime').addClass('col-lg-4');
                                $('.alltimeinner').removeClass('col-md-4');
                                $('.alltimeinner').addClass('col-md-3');
                                $('.whentoeatcls').removeClass('col-lg-2');
                                $('.whentoeatcls').addClass('col-lg-1');
                            }
                            else {
                                $('#eveningSession').hide();
                                //$('#eve').val(0);
                            }
                        });
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }
    
}

function Pause(val) {

    if ($("#IPDischarge_Id").val() != "2")
    {
        var Prescriptiondata = {
            medicine_prescription_id: val,
            Dml_Indicator: 'IPPS',
            ip_Indicator: "IP",
            ip_medicine_status: "0"
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Prescriptiondata),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {

                }
                else {

                    if (data2.msg == "Success") {
                        var data1 = data2.data;

                        toastr.success('Medicine Paused');
                        //ShowPrescription();
                        loadmedicineprescription();
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }
}

function Start(val) {

    if ($("#IPDischarge_Id").val() != "2")
    {
        var Prescriptiondata = {
            medicine_prescription_id: val,
            Dml_Indicator: 'IPPS',
            ip_Indicator: "IP",
            ip_medicine_status: "1"
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Prescriptiondata),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {

                }
                else {

                    if (data2.msg == "Success") {
                        var data1 = data2.data;
                        toastr.success('Medicine Started');
                        //ShowPrescription();
                        loadmedicineprescription();
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }
    
}

function dosage() {
    var medicine_name = $('#medicine_name').val();

    if (medicine_name.length > 0) {
        var medicine = {
            medicine_name: medicine_name,
            doctor_id: $('#HiddenDoctorID').val(),
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PatientDashboard/select_Medicine',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(medicine),
            success: function (data) {
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data;

                    if (data1.Table1.length > 0) {
                        if (data1.Table1[0].generic_name == '' || data1.Table1[0].generic_name == null) {
                            //$('#SelMedicineType').val(data1.Table[0].medicine_type_id);
                            $('#txtGenericName').val(data1.Table[0].generic_name);
                            $('#lblGenericName').html('Select Generic');
                        }
                        else {
                            //$('#SelMedicineType').val(data1.Table1[0].medicine_type_id);
                            $('#txtGenericName').val(data1.Table1[0].generic_name);
                            //$('#lblGenericName').html(data1.Table1[0].generic_name);
                        }
                        $('#hndwenttoeat').val(data1.Table1[0].how_to_take);
                        //  $('#days').val(data1.Table1[0].days_to_take);
                        $('#mor').val(data1.Table1[0].morning);
                        $('#aft').val(data1.Table1[0].afternoon);
                        //$('#priority').val(data1.Table1[0].priority);
                        if (data1.Table1[0].priority == 3) {
                            $("#high").prop("checked", true);
                        }
                        else if (data1.Table1[0].priority == 2) {
                            $("#medium").prop("checked", true);
                        }
                        else if (data1.Table1[0].priority == 1) {
                            $("#low").prop("checked", true);
                        }
                        else { }
                        if (data1.Table1[0].how_to_take == 9 || data1.Table1[0].how_to_take == 10) {
                            $('#eveningSession').show();
                            $('.alltime').removeClass('col-lg-3');
                            $('.alltime').addClass('col-lg-4');
                            $('.alltimeinner').removeClass('col-md-4');
                            $('.alltimeinner').addClass('col-md-3');
                            $('.whentoeatcls').removeClass('col-lg-2');
                            $('.whentoeatcls').addClass('col-lg-1');
                        }
                        else {
                            $('#eveningSession').hide();
                            $('.alltime').addClass('col-lg-3');
                            $('.alltime').removeClass('col-lg-4');
                            $('.alltimeinner').addClass('col-md-4');
                            $('.alltimeinner').removeClass('col-md-3');
                            $('.whentoeatcls').removeClass('col-lg-1');
                            $('.whentoeatcls').addClass('col-lg-2');
                            $('#eve').val(0);
                        }
                        $('#nit').val(data1.Table1[0].night);
                        $('#prescriptionNotes').val(data1.Table1[0].instructions);
                    }
                    else if (data1.Table.length > 0) {
                        // $('#SelMedicineType').val(data1.Table[0].medicine_type_id);
                        $('#txtGenericName').val(data1.Table[0].generic_name);
                    }
                    else {
                        $('#txtGenericName').val('');
                        //$('#txtGenericName').prop('readonly', false);
                    }

                }
                else {
                    console.log(data);
                }
            }
        });
    }
}

$('#SelMedicineType').change(function () {

    if ($('#medicine_name').val() != null && $('#medicine_name').val() != "" && $('#txtMedicineID').val() != null && $('#txtMedicineID').val() != "") {
        $('#txtMedicineID').val('');
        $('#medicine_name').val('');
        $('#days').val('');
        $('#dosage').val('');
        $('input:checkbox').prop('checked', false);
        $('#mor').val(0);
        $('#aft').val(0);
        $('#eve').val(0);
        $('#nit').val(0);
        $("#ddRoute").val("");
        $('#prescriptionNotes').val('');
        $('#txtGenericName').val('');
        //$('#txtGenericName').prop('readonly', true);
        $('#lblGenericName').html('Select Generic');
        $('#txtGenericName').show();
        //when_to eat reset
        $('#before_food').prop('checked', true);
        $('#with_food').prop('checked', false);
        $('#after_food').prop('checked', false);
        $('.when_to_eat_disp').text('Before Food');
        $('p.before_food').addClass('text_before_btn');
        $('p.with_food').removeClass('text_before_btn');
        $('p.after_food').removeClass('text_before_btn');
        $('#hndwenttoeat').val(0);
        //duration reset
        $('#duration_days').prop('checked', true);
        $('#duration_week').prop('checked', false);
        $('#duration_month').prop('checked', false);
        $('p.duration_days').addClass('text_before_btn');
        $('p.duration_week').removeClass('text_before_btn');
        $('p.duration_month').removeClass('text_before_btn');
        $('.duration_disp').html('Days');
        $('#hndduration').val(1);
        $('#prescriptionNotesToggle').hide();
        $("input[name='optradio']").prop('checked', false);
    }

})

function Daily() {
    $('#days').val('9999');
}


$('.radio_wrapper_2').click(function () {
    debugger;
    var value = $('input[name=duration_switch]:checked').val();
    if (value == 1) {
        $('.duration_disp').text('Days');
        $('p.duration_days').addClass('text_before_btn');
        $('p.duration_week').removeClass('text_before_btn');
        $('p.duration_month').removeClass('text_before_btn');
        $('#hndduration').val(1);
        $("#hndduration").change();
    } else if (value == 2) {
        $('.duration_disp').text('Week');
        $('p.duration_days').removeClass('text_before_btn');
        $('p.duration_week').addClass('text_before_btn');
        $('p.duration_month').removeClass('text_before_btn');
        $('#hndduration').val(2);
        $("#hndduration").change();
    } else if (value == 3) {
        $('.duration_disp').text('Month');
        $('p.duration_days').removeClass('text_before_btn');
        $('p.duration_week').removeClass('text_before_btn');
        $('p.duration_month').addClass('text_before_btn');
        $('#hndduration').val(3);
        $("#hndduration").change();
    }
});

$("#hndduration").change(function () {
    debugger;
    var dur = $(this).val();
    var durTxt;
    if (dur == 1) {
        durTxt = "Days";
    } else if (dur == 2) {
        durTxt = "Week";
    } else if (dur == 3) {
        durTxt = "Month";
    }
    $('#setDurationUnit').text(durTxt);
    $('#setDurationUnit').show();
    $('#DurationUnitToggle').hide();
});


//function dosage() {
//    var medicine_name = $('#medicine_name').val();
//    if ($('#doctorId').val() != 'USD00035') {
//        if (medicine_name.length > 0) {
//            var medicine = {
//                medicine_name: medicine_name,
//                doctor_id: $('#doctorId').val(),
//            }
//            $.ajax({
//                async: true,
//                type: 'POST',
//                url: '/PatientDashboard/select_Medicine',
//                contentType: 'application/json; charset=UTF-8',
//                data: JSON.stringify(medicine),
//                success: function (data) {

//                    var data2 = JSON.parse(data);
//                    if (data2.msg == "Success") {
//                        var data = data2.data;

//                        if (data.length > 2) {
//                            var data1 = JSON.parse(data);
//                            if (data1.Table1.length > 0) {
//                                if (data1.Table1[0].generic_name == '' || data1.Table1[0].generic_name == null) {
//                                    //$('#SelMedicineType').val(data1.Table[0].medicine_type_id);
//                                    $('#txtGenericName').val(data1.Table[0].generic_name);
//                                    $('#lblGenericName').html('Add Generic');
//                                }
//                                else {
//                                    //$('#SelMedicineType').val(data1.Table1[0].medicine_type_id);
//                                    $('#txtGenericName').val(data1.Table1[0].generic_name);
//                                    //$('#lblGenericName').html(data1.Table1[0].generic_name);
//                                }
//                                $('#hndwenttoeat').val(data1.Table1[0].how_to_take);
//                                //  $('#days').val(data1.Table1[0].days_to_take);
//                                $('#mor').val(data1.Table1[0].morning);
//                                $('#aft').val(data1.Table1[0].afternoon);
//                                //$('#priority').val(data1.Table1[0].priority);
//                                if (data1.Table1[0].priority == 3) {
//                                    $("#high").prop("checked", true);
//                                }
//                                else if (data1.Table1[0].priority == 2) {
//                                    $("#medium").prop("checked", true);
//                                }
//                                else if (data1.Table1[0].priority == 1) {
//                                    $("#low").prop("checked", true);
//                                }
//                                else { }
//                                if (data1.Table1[0].how_to_take == 9 || data1.Table1[0].how_to_take == 10) {
//                                    $('#eveningSession').show();
//                                    $('.alltime').removeClass('col-lg-3');
//                                    $('.alltime').addClass('col-lg-4');
//                                    $('.alltimeinner').removeClass('col-md-4');
//                                    $('.alltimeinner').addClass('col-md-3');
//                                    $('.whentoeatcls').removeClass('col-lg-2');
//                                    $('.whentoeatcls').addClass('col-lg-1');
//                                }
//                                else {
//                                    $('#eveningSession').hide();
//                                    $('.alltime').addClass('col-lg-3');
//                                    $('.alltime').removeClass('col-lg-4');
//                                    $('.alltimeinner').addClass('col-md-4');
//                                    $('.alltimeinner').removeClass('col-md-3');
//                                    $('.whentoeatcls').removeClass('col-lg-1');
//                                    $('.whentoeatcls').addClass('col-lg-2');
//                                    $('#eve').val(0);
//                                }
//                                $('#nit').val(data1.Table1[0].night);
//                                $('#prescriptionNotes').val(data1.Table1[0].instructions);
//                            }
//                            else if (data1.Table.length > 0) {
//                                //$('#SelMedicineType').val(data1.Table[0].medicine_type_id);
//                                $('#txtGenericName').val(data1.Table[0].generic_name);
//                            }
//                            else {
//                                $('#txtGenericName').val('');
//                                $('#txtGenericName').prop('readonly', false);
//                            }
//                        }
//                        else {
//                            // $("#dosage").attr("readonly", false);
//                        }
//                    }
//                    else {
//                        console.log(data);
//                    }
//                }
//            });
//        }
//    }
//}

function medicine() {
    if ($('#medicine').val('').length == 0) {
        $('#dosage').val('');
    }

}

function prescriptionNotes_change() {

    var mdescription = {
        Dml_Indicator: 'I',
        doctor_id: $('#doctorId').val(),
        notes: $('#prescriptionNotes').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/prescription_notes_ins',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(mdescription),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

            }

        }
    });
}

function loadpharmacyid() {
    var screen = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Dashboard_count',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(screen),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {
                if (data2.msg == "Success") {
                    debugger;
                    var data = data2.data;

                    if (data.Table9.length > 0) {
                        var pharmacyID = data.Table9[0].pharmacy_id;
                        $('#txtPharmacyID').val(pharmacyID);
                        $('#phy_data_flag').val(data.Table9[0].data_flag);

                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

$('#hndwenttoeat').change(function () {
    var hndwenttoeat = $('#hndwenttoeat').val();
    if (hndwenttoeat == 9 || hndwenttoeat == 10) {
        $('#eveningSession').show();
        $('.alltime').removeClass('col-lg-3');
        $('.alltime').addClass('col-lg-4');
        $('.alltimeinner').removeClass('col-md-4');
        $('.alltimeinner').addClass('col-md-3');
        $('.whentoeatcls').removeClass('col-lg-2');
        $('.whentoeatcls').addClass('col-lg-1');
    }
    else {
        $('#eveningSession').hide();
        //$('.alltime').addClass('col-lg-3');
        //$('.alltime').removeClass('col-lg-4');
        //$('.alltimeinner').addClass('col-md-4');
        //$('.alltimeinner').removeClass('col-md-3');
        //$('.whentoeatcls').removeClass('col-lg-1');
        //$('.whentoeatcls').addClass('col-lg-2');
        $('#eve').val(0);
    }
    if ($('#hndwenttoeat').val() == 4) {
        $('#mor').val(1);
        $('#aft').val(0);
        $('#eve').val(0);
        $('#nit').val(0);
    }
    else if ($('#hndwenttoeat').val() == 5) {
        $('#mor').val(1);
        $('#aft').val(1);
        $('#eve').val(0);
        $('#nit').val(1);
    }
    else if ($('#hndwenttoeat').val() == 6) {
        $('#mor').val(1);
        $('#aft').val(1);
        $('#eve').val(0);
        $('#nit').val(1);
    }
    else if ($('#hndwenttoeat').val() == 7) {
        $('#mor').val(1);
        $('#aft').val(0);
        $('#eve').val(0);
        $('#nit').val(1);
    }
    else if ($('#hndwenttoeat').val() == 8) {
        $('#mor').val(1);
        $('#aft').val(0);
        $('#eve').val(0);
        $('#nit').val(1);
    }
    else if ($('#hndwenttoeat').val() == 9) {
        $('#mor').val(1);
        $('#aft').val(1);
        $('#eve').val(1);
        $('#nit').val(1);
    }
    else if ($('#hndwenttoeat').val() == 10) {
        $('#mor').val(1);
        $('#aft').val(1);
        $('#eve').val(1);
        $('#nit').val(1);
    }
});

$('#medicine_name').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/CaseStudy/AutoCompletelist?dataflags=" + $('#phy_data_flag').val() + "&MedicineName=" + $('#medicine_name').val() + "&PharmacyID=" + $('#txtPharmacyID').val()+"&typeid=" + $('#SelMedicineType').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term },
            success: function (data) {
                //$('#txtMedicineID').val('');
                debugger;
                console.log(data);
                response($.map(data, function (item) {
                    return { label: item.medicine_status + "   ", value: item.medicine_name, medicine_type_id: item.medicine_type_id, id: item.medicine_id };
                    // return { label: item.medicine_name + "     Stock: " + item.medicine_status + "    MRP:  " + item.last_updated_on, value: item.medicine_name, medicine_type_id: item.medicine_type_id, id: item.medicine_id };
                }))
            }
        })
    },
    select: function (event, ui) {
        $('#txtMedicineID').val(ui.item.id);
        $('#SelMedicineType').val(ui.item.medicine_type_id);
    }
});

$('#txtGenericName').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/CaseStudy/AutoCompletelist_genericName?generic_name=" + $('#txtGenericName').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term },
            success: function (data) {
                response($.map(data, function (item) {
                    return { label: item.generic_name, value: item.generic_name, id: item.generic_id };
                }));
            }
        })
    }
});

$('#btnTemplate').click(function () {
    if ($.trim($('#templateName').val()) == "") {
        $('#PtemplateName').show();
        $('#PtemplateName').fadeOut(8000);
        $('#PtemplateName').html('Enter The Patient Name');
        $('#templateName').focus();
        $('#templateName').val('');
        return false;
    }
    $("#myTemplateTitle").modal("hide");
    $('#loaderimg').show();
    var Template = {
        template_name: $('#templateName').val(),
        visit_report_id: $('#IPVisitReport_Id').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'IPI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Medicine_template',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#loaderimg').hide();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    if (data1.length > 0) {
                        toastr.success("Template Saved Successfully");
                        templatelist();
                    }
                    else {
                        toastr.warning("Unable to Save the template, Please try again");
                    }
                }
                else {
                    console.log(data);
                }
                
            }
        }
    });
});

// New Prescription Start //

// Medicine Name Auto complete
$(document).on("focus", ".medicine-autocomplete", function () {
    debugger;
    var inputElement = $(this);

    inputElement.autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/CaseStudy/AutoCompletelist?dataflags=" + $('#phy_data_flag').val() + "&MedicineName=" + inputElement.val() + "&PharmacyID=" + $('#txtPharmacyID').val() + "&typeid=" + 0 + "&BranchId=" + $("#branch_id").val() + "&is_pharmacy=" + $('#His_pharmacy').val(),
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.medicine_status + "   ",
                            value: item.medicine_name,
                            medicine_type_id: item.medicine_type_id,
                            id: item.medicine_id
                        };
                    }))
                }
            })
        },
        select: function (event, ui) {
            var newRow = inputElement.closest("tr").clone();
            var newRow1 = inputElement.closest("tr");
            newRow.find("input").not("#priority").val("");
            var maxVal = Math.max.apply(null, $('.maxlenvalue').map(function () {
                return parseInt($(this).attr('maxlenvalue')) || 0;
            }).get());

            maxVal = maxVal + 1;
            newRow.find(".maxlenvalue").attr('maxlenvalue', maxVal);
            newRow.find("#priority").prop("checked", false);
            newRow.find("#priority").attr('name', 'optradio' + maxVal);

            var inputElement1 = $(event.target)
            var nextInput = newRow1.find("input[type='text']").eq(inputElement1.index() + 2);
            nextInput.focus();

            dosage1(ui.item.value, newRow1);
            if (newRow1.is(":last-child")) {

                newRow.find('.deleteicon-btn').hide();
                $("#tbl-medicine1").append(newRow);
                updateSerialNumbers();
                $('#tblmedicine tbody').sortable({
                    handle: '.draggable-handle',
                    helper: 'clone',
                    opacity: 1.5,
                    cursor: 'move',
                    update: function (event, ui) {
                        // Update serial numbers when a row is moved
                        updateSerialNumbers();
                    },
                });
            }
            newRow1.find('.deleteicon-btn').show();
        }
    });

});

function dosage1(selectedMedicine, row) {
    debugger;
    // 'row' is the row where the medicine was selected
    $('#txtNoDurationMedicine').val('');
    var medicine_name = selectedMedicine; // Use the selected medicine name
    if ($('#doctorId').val() != 'USD00035') {
        if (medicine_name.length > 0) {
            var medicine = {
                medicine_name: medicine_name,
                doctor_id: $('#doctorId').val(),
                medicine_type_id: $('#SelMedicineType').val()
            };
            $.ajax({
                async: true,
                type: 'POST',
                url: '/PatientDashboard/select_Medicine',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(medicine),
                success: function (data) {
                    debugger;
                    var data1 = JSON.parse(data);
                    if (data1.msg == "Success") {
                        data1 = data1.data;
                        if (data1.Table.length > 0) {
                            row.find('#txttdMedicine_id').val(data1.Table[0].medicine_id);
                            row.find('#txttdno_duration').val(data1.Table[0].no_duration);
                            row.find('#txttdmedicine_type_id').val(data1.Table[0].medicine_type_id);
                            //row.find('#txttdmedicine_type').val(data1.Table[0].medicine_type_id);
                            row.find('#txttdmedicine_type').val(data1.Table[0].medicine_type);

                        }
                        if (data1.Table1.length > 0) {
                            // Assign values to the remaining fields in the same row
                            row.find('#txtGenericName').val(data1.Table1[0].generic_name);

                            row.find('#txttdhndwenttoeat').val(data1.Table1[0].when_to_eat_value);
                            row.find('#Hidwhen_to_eat_id').val(data1.Table1[0].how_to_take);

                            //row.find('#txttdmedicinefrequency').val(data1.Table1[0].medicine_frequency);
                            row.find('#Hidmedicine_frequencyId').val(data1.Table1[0].medicine_frequency);
                            row.find('#txttdmedicinefrequency').val(data1.Table1[0].frequency_name);

                            row.find('#txttddosage').val(data1.Table1[0].medicine_dosage);
                            row.find('#txttddurationinput').val(data1.Table1[0].duration);
                            row.find('#txttdprescriptionNotes').val(data1.Table1[0].instructions);

                        }
                        if (data1.Table1.length > 0) {
                            if (data1.Table1[0].no_duration == "1") {
                                row.find('#days').val("");
                            } else {
                                row.find('#days').val(data1.Table1[0].days_to_take);
                            }
                        }
                    } else {
                        console.log(data);
                    }
                }
            });
        }
    }
}


$('#MBtn_Save').click(function () {
    debugger;
    saveprescription(1)
});

$('#btn_NewTemplate').click(function () {
    debugger;
    saveprescription(2);
})

function saveprescription(val) {
    debugger;
    formChanged = false;
    var dmlindicator = "";
    if (val == 1) {
        dmlindicator = 'MPIUX';
    }
    else {
        dmlindicator = 'MPIUXT';
    }

    var tableData = [];
    var tot_rowM = $('#tblmedicine >tbody >tr').length;
    if (tot_rowM > 0) {
        $('#loaderimg').show();
        $("#tblmedicine tbody tr").each(function () {
            var row = $(this);
            if (row.find("#txtmedicineName").val() !== '') {
                debugger;
                var ADT = row.find("#medicine_date").val();
                if (ADT == "") {
                    ADT = "";
                }
                else {
                    var a = ADT.split('/');
                    ADT = a[2] + '-' + a[1] + '-' + a[0];
                }

                var time = row.find("#medicine_time").val();
                var ATM = "";
                if (time == "") {
                    ATM = "";
                }
                else {
                    var ATM = moment(time, 'hh:mm A').format('HH:mm');
                }

                var Take_DateTime="";

                if (ADT == "" && ATM == "") {
                    Take_DateTime = "";
                }
                else {
                    Take_DateTime = ADT + " " + ATM;
                }


                var Startdate = row.find("#Start_date").val();
                if (Startdate == "") {
                    Startdate = "";
                }
                else {
                    var S = Startdate.split('/');
                    Startdate = S[2] + '-' + S[1] + '-' + S[0];
                }

                var Enddate = row.find("#End_date").val();
                if (Enddate == "") {
                    Enddate = "";
                }
                else {
                    var E = Enddate.split('/');
                    Enddate = E[2] + '-' + E[1] + '-' + E[0];
                }

                var mor = 0;
                var aft = 0;
                var nit = 0;
                var eve = 0;
                var max_quantity = 0;
                var daysInUnit = 0;
                var dosageValue = row.find("#txttddosage").val();
                dosageValue = dosageValue.replace(/\s*-\s*/g, "-");
                row.find("#txttddosage").val(dosageValue);
                if (typeof dosageValue === "string" && ((/^\s*\d+(?:\s*-\s*\d+)+\s*$/.test(dosageValue)) || (/^\s*\d.+(?:\s*-\s*\d.+)+\s*$/.test(dosageValue)))) {  ///^\d+(?:\s*-\s*\d*(?:\s*-\s*\d*)?)?$/.test(dosageValue)) {
                    // Split the value into parts
                    var parts = dosageValue.split('-');
                    if (parts.length == 3) {
                        mor = parseFloat($.trim(parts[0]));
                        aft = parseFloat($.trim(parts[1])) || 0;
                        nit = parseFloat($.trim(parts[2])) || 0;
                    }
                    else if (parts.length == 4) {
                        mor = parseFloat($.trim(parts[0]));
                        aft = parseFloat($.trim(parts[1])) || 0;
                        nit = parseFloat($.trim(parts[3])) || 0;
                        eve = parseFloat($.trim(parts[2])) || 0;
                    }
                }
                if (row.find("#txttdno_duration").val() == 0) {
                    var text = row.find("#txttddurationinput").val();

                    var match = text.match(/^(\d+) (Days|Weeks|Months|Years)$/i);

                    if (match) {
                        var number = parseInt(match[1]);
                        var unit = match[2].toLowerCase();


                        switch (unit) {
                            case "days":
                                daysInUnit = number;
                                break;
                            case "weeks":
                                daysInUnit = number * 7;
                                break;
                            case "months":
                                daysInUnit = number * 30;
                                break;
                            case "years":
                                daysInUnit = number * 365;
                                break;
                            default:
                                daysInUnit = 0;
                        }



                        var max_quantity = parseFloat(mor) + parseFloat(aft) + parseFloat(nit);
                        max_quantity = parseFloat(max_quantity) * parseFloat(number);
                    }
                }
                else {
                    max_quantity = 1;
                    daysInUnit = 1
                }
                var mdescription = {
                    Dml_Indicator: dmlindicator,
                    patient_id: $('#IPPatient_Id').val(),
                    templatename: $('#templateName').val(),
                    visit_report_id: $('#IPVisitReport_Id').val(),
                    //medicine_type_id: parseInt(row.find("#txttdmedicine_type").val()),
                    medicine_type_id: parseInt(row.find("#txttdmedicine_type_id").val()),
                    medicine_name: row.find("#txtmedicineName").val(),
                    medicine_type_name: row.find("#txttdmedicine_type").val(),
                    is_pharmacy: $('#His_pharmacy').val(),
                    //how_to_take: parseInt(row.find("#txttdhndwenttoeat").val()),
                    how_to_take: parseInt(row.find("#Hidwhen_to_eat_id").val()),
                    morning: mor,
                    afternoon: aft,
                    evening: eve,
                    night: nit,
                    days_to_take: daysInUnit,
                    pmedicine_dosage: (row.find("#txttddosage").val() == '' ? "" : row.find("#txttddosage").val()),
                    medicine_dosage: (row.find("#txttddosage").val() == '' ? "" : row.find("#txttddosage").val()),
                    medicine_type: parseInt(row.find("#txttdmedicine_type_id").val()),
                    doctor_id: $('#doctorId').val(),
                    slot_start_time: $('#Hdnappointment_date').val(),
                    instructions: row.find("#txttdprescriptionNotes").val(),
                    medicine_unit: parseInt(row.find("#txttdmedicine_type").val()),
                    generic_name: row.find("#txtGenericName").val(),
                    max_quantity: max_quantity,
                    priority: row.find("#priority:checked").val(),
                    display_order: row.find("#txttdserialnumber").text(),
                    pharmacy_id: $('#txtPharmacyID').val(),
                    medicine_id: parseInt(row.find("#txttdMedicine_id").val()),
                    // medicine_frequency: parseInt(row.find("#txttdmedicinefrequency").val()),
                    medicine_frequency: parseInt(row.find("#Hidmedicine_frequencyId").val()),
                    medicine_prescription_id: parseInt(row.find("#txttdmedicine_prescription_id").val()),
                    duration: row.find("#txttddurationinput").val(),
                    patient_take_datetime: Take_DateTime,
                    patient_take_dosage: row.find("#medicine_PatientTake").val(),
                    is_discharge_medicine: "0",
                    ipdoctor_name: row.find("#txtIPDoctorName").val(),
                    start_date: Startdate,
                    end_date: Enddate
                }
                tableData.push(mdescription);
            }
        });
        if (tableData.length > 0) {
            $.ajax({
                async: true,
                type: 'POST',
                url: '/PatientDashboard/Medicine_Prescription_Ins_Upd_XML',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(tableData),
                success: function (data) {
                    var data1 = JSON.parse(data);
                    if (data1.msg == "Success") {
                        $('#loaderimg').hide();
                        var data1 = data1.data;

                        if (val == 1) {
                            toastr.success('Saved Successfully');
                            // bindingprescriptiontable(data1.Table)
                            loadmedicineprescription();
                        }
                        else {

                            toastr.success('Template Saved Successfully',
                                {
                                    closeButton: false,
                                    progressBar: true,
                                    allowHtml: true,
                                    timeOut: 0,
                                })
                            setTimeout(function () {
                                templatelist();
                            }, 2000);
                            $('#myTemplateTitle').modal("toggle");
                            loadmedicineprescription();
                        }

                    }
                }
            });
        }
        else {
            $('#loaderimg').hide();
        }
    }

}

function loadmedicineprescription() {
    debugger;

    var VisitreportId = {
        //visit_report_id: $('#IPVisitReport_Id').val(),
        //Dml_Indicator: 'S'

        Dml_Indicator: "PS",
        ip_Indicator: "IP",
        visit_report_id: $("#IPVisitReport_Id").val(),
        is_discharge_medicine: 0,
        is_pharmacy: $("#His_pharmacy").val(),
        BranchId: $("#branch_id").val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    // Handle the case where no data is returned, if needed
                }
                else {
                    if (data1.length > 0) {
                        // Clear the existing table rows
                        bindingprescriptiontable(data1);
                    }
                    else {
                        $('.medicine_date').datepicker({
                            autoclose: true,
                            todayHighlight: true,
                            format: "dd/mm/yyyy",
                            startDate: "today"
                            //endDate: tom,
                        });

                        $('.SE_medicine_date').datepicker({
                            autoclose: true,
                            todayHighlight: true,
                            format: "dd/mm/yyyy",
                            //startDate: "today", use other hospital
                            //startDate: "",
                            //endDate: tom,
                        });
                    }
                }
            }
            else {

                console.error("AJAX request failed.");
            }
        },
        error: function (error) {

            console.error("AJAX error:", error);
        }
    });
}
function bindingprescriptiontable(data1) {
    debugger;
    // Assuming you have a JSON response called data1
    // $('#tblmedicine tbody').empty();
    if ($('#tblmedicine tbody tr:last #txtmedicineName').val() == '') {
        $('#tblmedicine tbody tr:last').remove();
    }


    if ($('#tblmedicine tbody tr').length > 0) {
        //$('#tblmedicine tbody').empty();
        $('#tblmedicine tbody tr').each(function (i, el) {
            var medicineprescriptionid = $(this).find('#txttdmedicine_prescription_id').val();
            if (medicineprescriptionid != "" && medicineprescriptionid != null) {
                $(this).remove();
            }
        })
    }



    var medval = '';

    var default_opt = '<option value="0">--Select--</option>';
    var medicine = "";
    $('#dd_tblMedicine').empty();

    $.each(data1, function (i, emp) {

        $('#tblmedicine tbody').empty();

        var j = parseInt(i) + 1
        var checked1 = '', checked2 = '', checked3 = '';
        if (emp.priority == 3) {
            checked1 = 'checked'
        }
        else if (emp.priority == 2) {
            checked2 = 'checked'
        }
        else if (emp.priority == 1) {
            checked3 = 'checked'
        }

        var PaseStart = "";

        if (emp.ip_medicine_status == 1) {
            PaseStart = "<a id='Pause' href=# class='label label-success'onclick=Pause('" + emp.medicine_prescription_id + "');>pause</a>";
        }
        else {
            PaseStart = "<a id='Start' href=# class='label label-success'onclick=Start('" + emp.medicine_prescription_id + "');>Start</a>";
        }

        // Construct the table row based on your data
        var row = '<tr id="' + emp.medicine_prescription_id + '">' +
            '<td class="draggable-handle tblserialnumber" style="cursor:move !important" id="txttdserialnumber">' + j + '</td>' +

            '<td class="">' +
            //'<div class="dropdown-wrapper">' +
            //'<select class="form-control SelMedicineType" tabindex="44" name="SelMedicineType" id="txttdmedicine_type">' +
            //'<option value="' + emp.medicine_type_id + '">' + emp.medicine_type + '</option>' +
            //'</select>' +
            //'</div>' +
            '<input class="SelMedicineTypeA form-control" type="text" name="SelMedicineType" id="txttdmedicine_type" value="' + emp.medicine_type + '"/>' +
            '</td>' +
            '<td>' +
            '<input class="medicine-autocomplete form-control" type="text" value="' + emp.medicine_name + '"  id="txtmedicineName" />' +
             '<div style="margin-bottom:25px" class="maxlenvalue" maxlenvalue=' + j + '><label class="radbtn crbp" id="highhead"><input type="radio"  name="optradio' + j + '" value="3" id="priority"  ' + checked1 + '><span class="checkmark rbrblue"></span></label>' +
             '<label class="radbtn crbp" id="mediumhead"><input type="radio"  name="optradio' + j + '" value="2" id="priority"  ' + checked2 + '><span class="checkmark rbrred"></span></label>' +
             '<label class="radbtn crbp" id="lowhead"><input type="radio"  name="optradio' + j + '" value="1"  id="priority" ' + checked3 + '><span class="checkmark rbrgreen"></span></label></div>' +
            '</td>' +
            '<td>' +
            '<input class="form-control txtGenericName" type="text" value="' + emp.generic_name + '"  id="txtGenericName" />' +
            '</td>' +
            '<td>' +
            '<input class="dosage-autocomplete form-control" name="num_hyphen"  type="text" value="' + emp.medicine_dosage + '" id="txttddosage" />' +
            '</td>' +
            '<td class="header-cell when-to-take-header">' +
            //'<div class="dropdown-wrapper">' +
            //'<select class="form-control hndwenttoeat"  name="when_to_eat" id="txttdhndwenttoeat">' +
            //'<option value="' + emp.how_to_take + '">' + emp.when_to_eat_value + '</option>' +
            //'</select>' +
            //'</div>' +
            '<input class="hndwenttoeatA form-control" type="text" id="txttdhndwenttoeat" value="' + emp.when_to_eat_value + '"/>' +
            '</td>' +
            '<td>' +
            //'<select class="form-control medicinefrequency"  name="medicinefrequency" id="txttdmedicinefrequency">' +
            //'<option value="' + emp.medicine_frequency + '">' + emp.frequency_name + '</option>' +
            //'</select>' +
            '<input class="medicinefrequencyA form-control" type="text" name="medicinefrequency" id="txttdmedicinefrequency" value="' + emp.frequency_name + '"/>' +
            '</td>' +
            '<td>' +
            '<input class="durationinput form-control" type="text" value="' + emp.duration + '" id="txttddurationinput" />' +
            '</td>' +
            '<td>' +
            '<input type="text" class="form-control prescriptionNotes" value="' + emp.instructions + '" id="txttdprescriptionNotes" />' +
            '</td>' +
            '<td>' +
            '<input class="IPDoctorNameA form-control" type="text" name="IPDoctorName" id="txtIPDoctorName" value="' + emp.ipdoctor_name + '"/>' +
            '</td>' +
            '<td class="hidden"><input type="text" class="form-control txttdmedicine_type_id" value="' + emp.medicine_type_id + '" id="txttdmedicine_type_id" /></td>' +
            '<td class="hidden"><input type="text" class="form-control txttdMedicine_id" value="' + emp.medicine_id + '" id="txttdMedicine_id" /></td>' +
            '<td class="hidden"><input type="text" class="form-control txttdno_duration" value="' + emp.no_duration + '" id="txttdno_duration" /></td>' +
            '<td class="hidden"><input type="text" class="form-control txttdmedicine_prescription_id" value="' + emp.medicine_prescription_id + '" id="txttdmedicine_prescription_id" /></td>' +

            '<td class="hidden"><input type="text" class="form-control Hidwhen_to_eat_id" value="' + emp.how_to_take + '" id="Hidwhen_to_eat_id" /></td>' +
            '<td class="hidden"><input type="text" class="form-control Hidmedicine_frequencyId" value="' + emp.medicine_frequency + '" id="Hidmedicine_frequencyId" /></td>' +
            '<td><div class="input-group date"><div class="input-group-addon"><i class="fa fa-calendar"></i></div><input type="text" class="form-control pull-right SE_medicine_date" id="Start_date" autocomplete="off" value="' + emp.start_date + '"></div></td>' +
            '<td><div class="input-group date"><div class="input-group-addon"><i class="fa fa-calendar"></i></div><input type="text" class="form-control pull-right SE_medicine_date" id="End_date" autocomplete="off" value="' + emp.end_date + '"></div></td>' +
            '<td><div class="input-group date"><div class="input-group-addon"><i class="fa fa-calendar"></i></div><input type="text" class="form-control pull-right medicine_date" id="medicine_date" autocomplete="off" value="' + emp.patient_take_date + '"></div><div class="input-group"><input type="text" class="form-control timepicker2 medicine_time MedicineTime_' + j + '" id="medicine_time" value="' + emp.patient_take_time + '" onclick=GetTime("MedicineTime_' + j + '","' + emp.patient_take_time + '");><div class="input-group-addon"><i class="fa fa-clock-o"></i></div></div></td>' +
            '<td><input type="text" class="form-control medicine_PatientTake" id="medicine_PatientTake" value="' + emp.patient_take_dosage + '" /></td>' +

            '<td><button class="btn deleteicon-btn btn-sm" title="Delete Medicine" onclick="deleteMedicine(this,\'' + emp.medicine_prescription_id + '\')"><i class="fa fa-trash" aria-hidden="true"></i></button>' + PaseStart + '</td>' +
            '</tr>';

        medval += row;


        medicine = medicine + '<option value="' + emp.medicine_prescription_id + '">' + emp.medicine_name + '</option>';

    });
    // Append the constructed rows to the table
    $('#tblmedicine tbody').append(medval);
    $('#dd_tblMedicine').append(default_opt + medicine);
    addNewRow();
    $('.medicine_date').datepicker({
        autoclose: true,
        todayHighlight: true,
        format: "dd/mm/yyyy",
        startDate: "today"
        //startDate: "",
        //endDate: tom,
    });

    $('.SE_medicine_date').datepicker({
        autoclose: true,
        todayHighlight: true,
        format: "dd/mm/yyyy",
        //startDate: "today", use other hospital
        //startDate: "",
        //endDate: tom,
    });
}

function GetTime(id,value) {
    debugger;
    var options2 = {
        title: 'Time',
        twentyFour: true
    };

    $('.' + id).wickedpicker(options2);
    //$('.' + id).val(value);
}

function addNewRow() {
    debugger
    // Get the current number of rows in the table
    var rowCount = $('#tblmedicine tbody tr').length + 1;
    var maxVal = Math.max.apply(null, $('.maxlenvalue').map(function () {
        return parseInt($(this).attr('maxlenvalue')) || 0;
    }).get());
    maxVal = maxVal + 1;
    var newRow = '<tr>' +
        '<td class="draggable-handle tblserialnumber" style="cursor:move !important" id="txttdserialnumber">' + rowCount + '</td>' + // Add serial number
        '<td class="header-cell when-to-take-header">' +
        //'<div class="dropdown-wrapper">' +
        //'<select class="form-control SelMedicineType" tabindex="44" name="SelMedicineType" id="txttdmedicine_type">' +
        //'</select>' +
        //'</div>' +
        '<input class="SelMedicineTypeA form-control" type="text" name="SelMedicineType" id="txttdmedicine_type" />' +
        '</td>' +
        '<td><input class="medicine-autocomplete form-control" type="text" id="txtmedicineName" />' +
         '<div style="margin-bottom:25px" class="maxlenvalue" maxlenvalue=' + maxVal + '><label class="radbtn crbp" id="highhead"><input type="radio" class="maxlenvalue" name="optradio' + maxVal + '" id="priority" value="3"><span class="checkmark rbrblue"></span></label>' +
             '<label class="radbtn crbp" id="mediumhead"><input type="radio"  name="optradio' + maxVal + '" id="priority" value="2"><span class="checkmark rbrred"></span></label>' +
             '<label class="radbtn crbp" id="lowhead"><input type="radio"  name="optradio' + maxVal + '" id="priority" value="1"><span class="checkmark rbrgreen"></span></label></div>' +
        '</td>' +
        '<td><input class="form-control txtGenericName" type="text" id="txtGenericName" /></td>' +
        '<td>' +
        '<input class="dosage-autocomplete form-control" type="text" name="num_hyphen" id="txttddosage" />' +
        '</td>' +
        '<td class="header-cell when-to-take-header">' +
        //'<div class="dropdown-wrapper">' +
        //'<select class="form-control hndwenttoeat" tabindex="44" name="when_to_eat" id="txttdhndwenttoeat">' +

        //'<option value=""></option>' +
        //'</select>' +
        //'</div>' +
        '<input class="hndwenttoeatA form-control" type="text" name="when_to_eat" id="txttdhndwenttoeat" value=""/>' +
        '</td>' +
        '<td>' +
        //'<select class="form-control medicinefrequency" tabindex="44" name="medicinefrequency" id="txttdmedicinefrequency">' +
        //'<option value=""></option>' +
        //'</select>' +
        '<input class="medicinefrequencyA form-control" type="text" name="medicinefrequency" id="txttdmedicinefrequency" value=""/>' +
        '</td>' +
        '<td>' +
        '<input class="durationinput form-control" type="text" id="txttddurationinput" />' +
        '</td>' +
        '<td>' +
        '<input type="text" class="form-control prescriptionNotes" id="txttdprescriptionNotes" />' +
        '</td>' +
        '<td>' +
            '<input class="IPDoctorNameA form-control" type="text" name="IPDoctorName" id="txtIPDoctorName" />' +
            '</td>' +
        '<td class="hidden"><input type="text" class="form-control txttdmedicine_type_id" id="txttdmedicine_type_id" /></td>' +
        '<td class="hidden"><input type="text" class="form-control txttdMedicine_id" id="txttdMedicine_id" /></td>' +
        '<td class="hidden"><input type="text" class="form-control txttdno_duration" id="txttdno_duration" /></td>' +
        '<td class="hidden"><input type="text" class="form-control txttdmedicine_prescription_id" id="txttdmedicine_prescription_id" /></td>' +

        '<td class="hidden"><input type="text" class="form-control Hidwhen_to_eat_id" id="Hidwhen_to_eat_id" /></td>' +
        '<td class="hidden"><input type="text" class="form-control Hidmedicine_frequencyId" id="Hidmedicine_frequencyId" /></td>' +
         '<td><div class="input-group date"><div class="input-group-addon"><i class="fa fa-calendar"></i></div><input type="text" class="form-control pull-right SE_medicine_date" id="Start_date" autocomplete="off"></div></td>' +
         '<td><div class="input-group date"><div class="input-group-addon"><i class="fa fa-calendar"></i></div><input type="text" class="form-control pull-right SE_medicine_date" id="End_date" autocomplete="off"></div></td>' +
        '<td><div class="input-group date"><div class="input-group-addon"><i class="fa fa-calendar"></i></div><input type="text" class="form-control pull-right medicine_date" id="medicine_date" autocomplete="off"></div><div class="input-group"><input type="text" class="form-control timepicker2 medicine_time MedicineTime_' + rowCount + '" id="medicine_time" onclick=GetTime("MedicineTime_' + rowCount + '","' + 0 + '");><div class="input-group-addon"><i class="fa fa-clock-o"></i></div></div></td>' +
        '<td><input type="text" class="form-control medicine_PatientTake" id="medicine_PatientTake" /></td>'+


        '<td><button class="btn deleteicon-btn btn-sm" title="Delete Medicine" onclick="deleteMedicine(this,0)"><i class="fa fa-trash" aria-hidden="true"></i></button></td></td>' +
        '</tr>';

    $('#tblmedicine tbody').append(newRow);

    // Enable row sorting with jQuery UI Sortable
    $('#tblmedicine tbody').sortable({
        handle: '.draggable-handle',
        helper: 'clone',
        opacity: 1.5,
        cursor: 'move',
        update: function (event, ui) {
            updateSerialNumbers(); // Update serial numbers when a row is moved
        },
    });
    
}
//function updateSerialNumbers() {
//    $('.tblserialnumber').each(function (index) {
//        $(this).text(index + 1);
//    });
//}

function updateSerialNumbers() {
    $("#tbl-medicine1 tr").each(function (index, row) {
        $(row).find("td:first").text(index + 1); // Update serial number
    });
    PatientTakeDateTime();
}

function PatientTakeDateTime() {
    $('.medicine_date').datepicker({
        autoclose: true,
        todayHighlight: true,
        format: "dd/mm/yyyy",
        startDate: "today" 
        //endDate: tom,
    });

    $('.SE_medicine_date').datepicker({
        autoclose: true,
        todayHighlight: true,
        format: "dd/mm/yyyy",
        //startDate: "today", use other hospital
        //startDate: "",
        //endDate: tom,
    });

}

function deleteMedicine(e, id) {
    debugger;
    var rowCount = $("#tblmedicine tbody tr").length;

    if (rowCount === 1) {

        toastr.warning("Cannot delete the last row.");
    }
    else {
        if (id == 0) {
            var rowToDelete = $(e).closest("tr");
            rowToDelete.remove();
            toastr.success("Medicine deleted");
            // Optionally, update the serial numbers for the remaining rows
            updateSerialNumbers();
        }
        else {

            var medicineId = id;
            var mdescription = {
                //Dml_Indicator: 'D',
                //medicine_prescription_id: medicineId,
                //visit_report_id: $('#IPVisitReport_Id').val(),

                Dml_Indicator: "IPD",
                ip_Indicator: "IP",
                medicine_prescription_id: medicineId,
                ip_prescription_status: 0,
                visit_report_id: $('#IPVisitReport_Id').val()
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(mdescription),
                success: function (data) {
                    var data1 = JSON.parse(data);
                    if (data1.msg == "Success") {
                        var data1 = data1.data;
                        var medval = '';


                        var rowToDelete = $(e).closest("tr");
                        rowToDelete.remove();
                        updateSerialNumbers();
                        toastr.success("Medicine deleted");

                        $('#dd_tblMedicine').remove(medicineId);

                    }
                    else {
                        console.log(data);
                    }
                }
            });
        }
    }
}

// when to take auto complete
$(document).on("focus", ".hndwenttoeatA1", function () {
    debugger;

    $(this).autocomplete({
        source: whentotakearray.map(item => item.when_to_eat_value), // Use the 'medicine_type' property for suggestions
        minLength: 0,
        select: function (event, ui) {

            WhentoTakeId = whentotakearray.find(item => item.when_to_eat_value === ui.item.value).when_to_eat_id;
            when_to_eat_value = whentotakearray.find(item => item.when_to_eat_value === ui.item.value).when_to_eat_value;

            $('.Hidwhen_to_eat_id').val(WhentoTakeId)
            $('.hndwenttoeatA').val(when_to_eat_value)
        }
    });
    if ($(this).val() === '') {
        $(this).autocomplete("search", "");
    }
});

$(document).on("focus", ".hndwenttoeatA", function () {
    debugger;
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");

    $(this).autocomplete({
        source: whentotakearray.map(item => item.when_to_eat_value), // Use the 'medicine_type' property for suggestions
        minLength: 0,
        select: function (event, ui) {
            debugger;
            WhentoTakeId = whentotakearray.find(item => item.when_to_eat_value === ui.item.value).when_to_eat_id;
            when_to_eat_value = whentotakearray.find(item => item.when_to_eat_value === ui.item.value).when_to_eat_value;

            newRow1.find('#Hidwhen_to_eat_id').val(WhentoTakeId)
        }
    });
    if ($(this).val() === '') {
        $(this).autocomplete("search", "");
    }

});

$(document).on("change", ".hndwenttoeatA", function () {
    debugger;
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");
    if (newRow1.find('#txttdhndwenttoeat').val() == "") {
        newRow1.find('#Hidwhen_to_eat_id').val(0);
    }
});

// Medicine frequency auto complete
$(document).on("focus", ".medicinefrequencyA1", function () {
    debugger;
    console.log(frequencyarray)

    $(this).autocomplete({
        source: frequencyarray.map(item => item.frequency_name), // Use the 'medicine_type' property for suggestions
        minLength: 0,
        select: function (event, ui) {

            MedicineFrequencyId = frequencyarray.find(item => item.frequency_name === ui.item.value).frequency_master_id;
            MedicineFrequencyName = frequencyarray.find(item => item.frequency_name === ui.item.value).frequency_name;


            $('.Hidmedicine_frequencyId').val(MedicineFrequencyId)

            $('.medicinefrequencyA').val(MedicineFrequencyName)
        }
    });
    if ($(this).val() === '') {
        $(this).autocomplete("search", "");
    }
});

$(document).on("focus", ".medicinefrequencyA", function () {
    debugger;
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");
    $(this).autocomplete({
        source: frequencyarray.map(item => item.frequency_name), // Use the 'medicine_type' property for suggestions
        minLength: 0,
        select: function (event, ui) {

            MedicineFrequencyId = frequencyarray.find(item => item.frequency_name === ui.item.value).frequency_master_id;
            MedicineFrequencyName = frequencyarray.find(item => item.frequency_name === ui.item.value).frequency_name;

            newRow1.find('#Hidmedicine_frequencyId').val(MedicineFrequencyId)
        }
    });
    if ($(this).val() === '') {
        $(this).autocomplete("search", "");
    }
});

$(document).on("change", ".medicinefrequencyA", function () {
    debugger;
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");
    if (newRow1.find('#txttdmedicinefrequency').val() == "") {
        newRow1.find('#Hidmedicine_frequencyId').val(0);
    }


});

//Doctor Name autocomplete

$(document).on("focus", ".IPDoctorNameA", function () {
    debugger;
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");
    $(this).autocomplete({
        source: IPDoctorArr.map(item => item.first_name), // Use the 'medicine_type' property for suggestions
        minLength: 0,
        select: function (event, ui) {

            Doctor_Name = IPDoctorArr.find(item => item.first_name === ui.item.value).first_name;

            newRow1.find('#txtIPDoctorName').val(Doctor_Name)
        }
    });
    if ($(this).val() === '') {
        $(this).autocomplete("search", "");
    }
});

$(document).on("change", ".IPDoctorNameA", function () {
    debugger;
    var inputElement = $(this);
    var newRow1 = inputElement.closest("tr");
    //if (newRow1.find('#txtIPDoctorName').val() == "") {
    //    newRow1.find('#txtIPDoctorName').val("");
    //}


});


//    // Use event delegation for dosage autocomplete
$(document).on("focusout", ".dosage-autocomplete", function () {
    debugger;
    var dosageInput = $(this);
    var dosageValue = $(this).val();

    // Check if the entered value is a non-empty string
    if (typeof dosageValue === "string" && /^\d+(?:\s*-\s*\d*(?:\s*-\s*\d*)?)?$/.test(dosageValue)) {
        // Split the value into parts
        var parts = dosageValue.split("-");
        var X = parts[0];
        var Y = parts[1] || "0";
        var Z = parts[2] || "0";

        // Update the dosage field with the formatted value
        var formattedDosage = X + " - " + Y + " - " + Z;
        dosageInput.val(formattedDosage);
    }
});


$(document).on("focus", ".dosage-autocomplete", function () {
    debugger;
    var inputElement = $(this);

    inputElement.autocomplete({
        source: function (request, response) {
            debugger;

            $.ajax({
                async: true,
                url: "/CaseStudy/Medicine_Dosage?prescription_notes=" + inputElement.val(),
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.notes, value: item.notes };
                    }))

                }
            })
        },
    });

});

$(document).on("focus", ".prescriptionNotes", function () {
    debugger;
    var inputElement = $(this);

    inputElement.autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/CaseStudy/prescription_notes?prescription_notes=" + inputElement.val(),
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.notes, value: item.notes };
                    }))

                }
            })
        },
    });
});


//Function to handle appending a new row on Enter key press
function handleEnterKey1(event) {
    debugger;
    if (event.keyCode === 13) { // Check if Enter key is pressed
        var inputElement = $(event.target);
        var currentRow = inputElement.closest("tr");

        currentRow.find('.deleteicon-btn').show();
        // If there's a next input in the same row, focus on it

        if (inputElement.val() != "") {

            // Clone the current row and append it
            if (currentRow.is(":last-child")) {
                var newRow = currentRow.clone();

                newRow.find("input").val(""); // Clear input values in the new row

                newRow.find('.deleteicon-btn').hide();
                $("#tbl-medicine1").append(newRow);
                updateSerialNumbers();
            }

            var lastRow = $("#tbl-medicine1 tr:last");
            var thirdColumn = lastRow.find("td:eq(2)");
            var inputInSecondColumn = thirdColumn.find("input[type='text']");
            inputInSecondColumn.focus();
        }

    }
}


$(document).on("focus", ".txtGenericName", function () {
    var inputElement = $(this);

    inputElement.autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/CaseStudy/AutoCompletelist_genericName?generic_name=" + inputElement.val(),
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    debugger;
                    response($.map(data, function (item) {
                        return { label: item.generic_name, value: item.generic_name, id: item.generic_id };
                    }));
                }
            })
        }
    });
});


$(document).on("click", ".add-row", function () {
    //var newRow = $(this).closest("tr").clone();
    //newRow.find("input").val(""); // Clear input values in the new row
    //$("#tbl-medicine1").append(newRow);
    addNewRow();
});
$(document).on("click", ".delete-row", function () {
    // Delete the clicked row
    $(this).closest("tr").remove();
});
// Event handler for When to take header click
$(".whentotakeheader").click(function (event) {
    debugger;
    event.stopPropagation(); // Prevent event propagation to the document
    $('#hndwenttoeatheader').show();
    $('#hndwenttoeatheader').focus();
});

$(".notesh").click(function (event) {
    event.stopPropagation(); // Prevent event propagation to the document
    $('#prescriptionNotesheader').show();
    $('#prescriptionNotesheader').focus();
});

$(".durationh").click(function (event) {
    event.stopPropagation(); // Prevent event propagation to the document
    $('#durationinputheader').show();
    $('#durationinputheader').focus();
});

$(".freaquencyh").click(function (event) {
    event.stopPropagation(); // Prevent event propagation to the document
    $('#medicinefrequencyheader').show();
    $('#medicinefrequencyheader').focus();
});

$(".dosageautocompleteh").click(function (event) {
    event.stopPropagation(); // Prevent event propagation to the document
    $('#dosageautocompleteheader').show();
    $('#dosageautocompleteheader').focus();
});

// Clicking anywhere in the document except inside the table header will hide the elements
$(document).click(function () {
    $('#hndwenttoeatheader, #prescriptionNotesheader, #durationinputheader, #medicinefrequencyheader, #dosageautocompleteheader').hide();
});
$('#hndwenttoeatheader').change(function () {
    debugger;
    var item = $(this);
    $('.hndwenttoeat').val(item.val());

})
$('#hndwenttoeatheader').change(function () {
    debugger;

    var item = $(this);
    $('.hndwenttoeat').val(item.val());

});

$('#prescriptionNotesheader').change(function () {
    var item = $(this);
    $('.prescriptionNotes').val(item.val());
});
$('#durationinputheader').change(function () {
    var item = $(this);
    $('.durationinput').val(item.val());
});
$('#medicinefrequencyheader').change(function () {
    debugger;
    var item = $(this);
    $('.medicinefrequency').val(item.val());
});
$('#dosageautocompleteheader').change(function () {
    var item = $(this);
    var dosageValue = $(this).val();

    // Check if the entered value is a non-empty string
    if (typeof dosageValue === "string" && /^\d+(?:\s*-\s*\d*(?:\s*-\s*\d*)?)?$/.test(dosageValue)) {
        // Split the value into parts
        var parts = dosageValue.split("-");
        var X = parts[0];
        var Y = parts[1] || "0";
        var Z = parts[2] || "0";
        // Update the dosage field with the formatted value
        var formattedDosage = X + " - " + Y + " - " + Z;
        $('.dosage-autocomplete').val(formattedDosage);
    }
    else {
        $('.dosage-autocomplete').val(item.val());
    }

});

$('table').on('keyup', 'input[name="num_hyphen"]', function (e) {
    debugger
    var value = this.value;
    var id = this.id;
    var preg_check = /[^0-9-.]/g;
    if (preg_check.test(value)) {
        var parentRow = $(this).closest('tr');
        $(this).val(value.replace(/[^0-9-.]/g, ''));
    }
});
$('table').on('keyup', 'input[name="num_only"]', function (e) {
    debugger
    var value = this.value;
    var id = this.id;
    var preg_check = /[^0-9]/ig;
    if (preg_check.test(value)) {
        var parentRow = $(this).closest('tr');
        $(this).val(value.replace(/[^0-9-]/g, ''));
    }
});

function Medicine_Frequency() {

    var PatientData = {
        Dml_Indicator: 'IPFR'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/CaseStudy',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            var data = JSON.parse(data);

            var data = data.data;
            if (jQuery.isEmptyObject((data))) {

            }
            else {
                console.log(data);
                
                if (data.Table.length > 0) {
                    $('#medicinefrequency').empty();
                    $('#medicinefrequency_edit').empty();
                    trs = '';
                    var defaultoption = '<option value="0">--select--</option>';
                    frequencyarray = data.Table;
                    //loadfrequencytype(frequencyarray);
                    for (var i = 0; i < data.Table.length; i++) {
                        trs = trs + '<option value="' + data.Table[i].frequency_master_id + '">' + data.Table[i].frequency_name + '</option>';
                    }
                    $('#medicinefrequency').append(defaultoption + trs);
                    // $('.medicinefrequency').append(defaultoption + trs);
                    $('#medicinefrequency_edit').append(defaultoption + trs);
                }
            } 
        }

    });    
}

$('#dd_tblMedicine').change(function () {
    
    if (parseInt($('#dd_tblMedicine').val()) == 0) {
        $('#Single_medicine_tbl tbody').empty();
    }
    else {
        Singlemedicineprescription();
    }

})

function Singlemedicineprescription() {
    debugger;

    var VisitreportId = {

        Dml_Indicator: "SMP",
        visit_report_id: $("#IPVisitReport_Id").val(),
        is_discharge_medicine: 0,
        is_pharmacy: $("#His_pharmacy").val(),
        medicine_prescription_id: $('#dd_tblMedicine').val(),
        BranchId: $("#branch_id").val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {
            var data1 = JSON.parse(data);

            $('#Single_medicine_tbl tbody').empty();
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    // Handle the case where no data is returned, if needed
                }
                else {
                    if (data1.length > 0) {

                        $('#Single_medicine_tbl').dataTable().fnClearTable();
                        $('#Single_medicine_tbl').dataTable().fnDraw();
                        $('#Single_medicine_tbl').dataTable().fnDestroy();
                        var medval = "";
                        $.each(data1, function (i, emp) {

                            var j = parseInt(i) + 1
                            var checked1 = '', checked2 = '', checked3 = '';
                            if (emp.priority == 3) {
                                checked1 = 'checked'
                            }
                            else if (emp.priority == 2) {
                                checked2 = 'checked'
                            }
                            else if (emp.priority == 1) {
                                checked3 = 'checked'
                            }

                            var PaseStart = "";

                            if (emp.ip_medicine_status == 1) {
                                PaseStart = "Start Medicine";
                            }
                            else {
                                PaseStart = "Stop Medicine";
                            }

                            // Construct the table row based on your data
                            var row = '<tr><td>' + j + '</td><td>' + emp.medicine_type +'</td><td>' + emp.medicine_name +'</td><td>' + emp.generic_name +'</td><td>' + emp.medicine_dosage +'</td><td>' + emp.when_to_eat_value +'</td><td>' + emp.frequency_name +'</td><td>' + emp.duration +'</td><td>' + emp.instructions +'</td>' +
                                '<td>' + emp.ipdoctor_name +'</td><td>' + emp.start_date + '</td><td>' + emp.end_date + '</td><td>' + emp.patient_take_date +" "+ emp.patient_take_time + '</td><td>' + emp.patient_take_dosage + '</td><td>' + emp.medicine_start_date + '</td><td>' + emp.medicine_stop_date + '</td></tr>';

                            medval += row;

                        });

                        $('#Single_medicine_tblbody').html(medval);
                        //datatable('Single_medicine_tbl', 'SMedicine', 'Legal');

                        $('#Single_medicine_tbl').dataTable();
                    }
                    
                }
            }
            else {

                console.error("AJAX request failed.");
            }
        },
        error: function (error) {

            console.error("AJAX error:", error);
        }
    });
}


// New Prescription End //