
var storeitemslistarray = [];

$(document).ready(function () {
    debugger;
    check_previlige_tabs(44);
    loadWardName();
    LoadOperationTheatre();
    loadTherapist();
    LoadBranch();
    LoadRoomstype();
});
$(document).ready(function () {
    $('.input-group.date').datepicker({
        format: "dd/mm/yyyy",
        autoclose: true,
        todayHighlight: true,
        startDate: new Date()
    });
});

$("#stssubmit").click(function () {
    stssubmit();
});

$("#OTCsubmit").off("click").on("click", function () {
    debugger;
    OTCsubmit();
});

var selectedRowId;

function setSelectedRowId(id) {
    selectedRowId = id;
}

function stssubmit() {
    var selectedStatus = $("#ddstatus").val();

    if (!selectedStatus || selectedStatus === "0") {
        console.error("Please select a valid status");
        return;
    }

    var scheduleStatusValue;

    if (selectedStatus === "2") {
        scheduleStatusValue = 2; // OT BedTransfer
    } else if (selectedStatus === "3") {
        scheduleStatusValue = 3; // PreOT List
    } else if (selectedStatus === "4") {
        scheduleStatusValue = 4; // Post OT List
    } else {
        console.error("Invalid status selected");
        return;
    }
    debugger;
    var OTSstatus = {
        P_Dml_Indicator: "OTSII",
        id: selectedRowId,
        schedule_status: scheduleStatusValue
    };
    debugger;
    $.ajax({
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTSstatus),
        success: function (data) {
            toastr.success('Updated successfully');
            $('#addstatuspopup').modal('hide');
            LoadOperationTheatre();
        },
        error: function (xhr, status, error) {
            console.error(xhr.responseText);
            toastr.error('Data not added. Please try again.');
        }
    });
}


$('#addstatuspopup').on('hidden.bs.modal', function () {

    $('#ddstatus').val("0");

});

$(document).on('click', '#addStatus', function () {
    console.log("Dropdown toggle clicked");
    fetchOTStatus();
});

function fetchOTStatus() {
    console.log("fetchOTStaus");
    console.log(selectedRowId);
    var OTSstatus1 = {
        P_Dml_Indicator: "OTSIU",
        id: selectedRowId,
    };

    $.ajax({
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTSstatus1),
        success: function (data) {
            console.log("gvsdvfgfhds");
            console.log(data);


            var responseJson = JSON.parse(data);
            var scheduleStatus = responseJson.data.Table[0].schedule_status;
            console.log(scheduleStatus);
            if (scheduleStatus == 3) {
                $('#ddstatus').val(scheduleStatus);
            } else if (scheduleStatus == 2) {
                $('#ddstatus').val(2);
            } else {
                $('#ddstatus').val(0);
            }

        },
        error: function (xhr, status, error) {
            console.error(error);
        }
    });

}


function check_previlige_tabs(formid) {
    debugger;
    var RightData = {
        Stringtype: formid,
        Dml_Indicator: "CTABR"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/UserRight/User_rights_privileges',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RightData),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    var j = 0, k = 0, m = 0;

                    $.each(data1.Table, function (i, emp1) {
                        $("[data-id=" + emp1.tab_id + "]").removeClass('hidden');
                    })

                    $.each(data1.Table1, function (i, emp) {
                        if (emp.status == 0) {
                            $("[data-id=" + emp.role_rights_view + "]").addClass('hidden');
                        }
                        else if (emp.status == 1) {
                            if (j == 0 && emp.tab_id == 'HS_V1') {

                                $('#' + emp.tab_name).click();
                                m = m + 1;
                            }
                            if (k == 0 && emp.tab_id == 'HM_V1') {
                                if (m == 0) {
                                    $('#' + emp.tab_name).click();

                                    k = +1;
                                }
                            }

                            j = j + 1;
                        }
                    });
                }
            }
        }
    });
}

function OTsubmit() {
    debugger;

    if ($('#dd_Branch').val() == '0') {
        $("#Pdd_Branch").show();
        $("#Pdd_Branch").html("Select Branch").fadeOut(8000);
        $('#Pdd_Branch').focus();

        return false;
    }

    var surgeryname = $("#surgeryname").val().toString().trim();
    if (surgeryname == "") {
        $("#Psurgeryname").show();
        $("#Psurgeryname").html("Please Select Surgery name").fadeOut(8000);
        $('#Psurgeryname').focus();

        return false;
    }

    //if (surgeryname != "") {

    //    if ($("#hdsur_id").val() == "") {
    //        $("#Psurgeryname").show();
    //        $("#Psurgeryname").html("Select correct Surgery name").fadeOut(8000);
    //        $('#Psurgeryname').focus();

    //        return false;
    //    }
    //}

    var SelDoctor = $("#SelDoctor").val().toString().trim();
    if (SelDoctor == "") {
        $("#PSelDoctor").show();
        $("#PSelDoctor").html("Please Select Surgeon name").fadeOut(8000);
        $('#PSelDoctor').focus();

        return false;
    }

    //if (SelDoctor != "") {
    //    if ($("#Hdndoctor_id").val() == "") {
    //        $("#PSelDoctor").show();
    //        $("#PSelDoctor").html("Select correct Surgeon name").fadeOut(8000);
    //        $('#PSelDoctor').focus();

    //        return false;
    //    }
    //}

    if ($("#txt_AssSurgeonName").val().toString().trim() == "") {
        $("#Ptxt_AssSurgeonName").show();
        $("#Ptxt_AssSurgeonName").html("Select Assistant Surgeon Name").fadeOut(8000);
        $('#Ptxt_AssSurgeonName').focus();

        return false;
    }

    //if ($("#txt_AssSurgeonName").val().trim() != "") {
    //    if ($("#HdnAss_surgeonid").val() == "") {
    //        $("#Ptxt_AssSurgeonName").show();
    //        $("#Ptxt_AssSurgeonName").html("Select correct Assistant Surgeon Name").fadeOut(8000);
    //        $('#Ptxt_AssSurgeonName').focus();

    //        return false;
    //    }
    //}

    if ($("#txt_AnaesthesianName").val().toString().trim() == "") {
        $("#Ptxt_AnaesthesianName").show();
        $("#Ptxt_AnaesthesianName").html("Select Anaesthesian Name").fadeOut(8000);
        $('#Ptxt_AnaesthesianName').focus();

        return false;
    }

    //if ($("#txt_AnaesthesianName").val().trim() != "") {

    //    if ($("#HdnAnaesthesian_id").val() == "") {
    //        $("#Ptxt_AnaesthesianName").show();
    //        $("#Ptxt_AnaesthesianName").html("Select correct Anaesthesian Name").fadeOut(8000);
    //        $('#Ptxt_AnaesthesianName').focus();

    //        return false;
    //    }
    //}

    var PaitentSearch = $("#PaitentSearch").val().trim();
    if (PaitentSearch === '') {
        $("#Ppatient").show();
        $("#Ppatient").html("Please Enter the Patient").fadeOut(8000);
        $('#Ppatient').focus();

        return false;
    }

    if ($('#OTroom').val() == "") {
        $("#POTroom").show();
        $("#POTroom").html("Select Theatre").fadeOut(8000);
        $('#POTroom').focus();

        return false;
    }

    var expdate = $("#expdate").val().trim();
    if (expdate === '') {
        $("#Pexpdate").show();
        $("#Pexpdate").html("Please Enter Date").fadeOut(8000);
        $('#Pexpdate').focus();

        return false;
    }

    if ($('#exptime').val() == "") {
        $("#Pexptime").show();
        $("#Pexptime").html("Select Expected From Time").fadeOut(8000);
        $('#Pexptime').focus();

        return false;
    }

    if ($('#txt_ExpToTime').val() == "") {
        $("#Ptxt_ExpToTime").show();
        $("#Ptxt_ExpToTime").html("Select Expected To Time").fadeOut(8000);
        $('#Ptxt_ExpToTime').focus();

        return false;
    }
    var FromTime = $("#exptime").val();
    var Exp_FromTime = moment(FromTime, 'hh:mm A');
    var FromMinutes = Exp_FromTime.hours() * 60 + Exp_FromTime.minutes();

    var ToTime = $("#txt_ExpToTime").val();
    var Exp_ToTime = moment(ToTime, 'hh:mm A');
    var ToMinutes = Exp_ToTime.hours() * 60 + Exp_ToTime.minutes()

    if (FromMinutes >= ToMinutes) {
        $("#Pexptime").show();
        $("#Pexptime").html("Expected To Time should be greater than Expected From Time").fadeOut(8000);
        $('#exptime').focus();
        return false;
    }

    var Expected_date = "";
    if ($("#expdate").val() != '') {
        var date1 = $("#expdate").val().split('/');
        Expected_date = date1[2] + '-' + date1[1] + '-' + date1[0];
    }

    var FromTime = $("#exptime").val();
    var Exp_FromTime = moment(FromTime, 'hh:mm A').format('HH:mm');

    var ToTime = $("#txt_ExpToTime").val();
    var Exp_ToTime = moment(ToTime, 'hh:mm A').format('HH:mm');


    var id = $("#hdnEditId").val();
    debugger;
    var OTdata = {
        P_Dml_Indicator: "OTIN",
        id: id,
        Surgery_Name: surgeryname,
        Surgeon_Name: SelDoctor,
        //CSSD_Kit: $('#cssdkit').val(),
        Patient_Name: $('#hdpat_id').val(),
        Room_no: $('#hdroom_id').val(),
        Date: Expected_date,
        fromTime: Exp_FromTime,
        toTime: Exp_ToTime,
        Schedule_Type: 1,
        branch_id: $('#dd_Branch').val(),
        assistant_surgeon: $("#txt_AssSurgeonName").val().toString(),
        anaesthesian: $("#txt_AnaesthesianName").val().toString(),
        visit_reportid: $('#HdnVisitId').val(),
        diagnosis: $('#diagnosis').val()

    };

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

            if (data1.Table[0].Message == "Surgeon_Exists") {
                toastr.warning('The Surgeon already Booked at the same time.');
            }
            else if (data1.Table[0].Message == "Ass_Surgeon_Exists") {
                toastr.warning('The Assistant Surgeon already Booked at the same time.');
            }
            else if (data1.Table[0].Message == "anaesthesian_Exists") {
                toastr.warning('The Anaesthesian already Booked at the same time.');
            }
            else if (data1.Table[0].Message == "Room_Exists") {
                toastr.warning('The Room already Booked at the same time.');
            }
            else if (data1.Table[0].Message == "Success") {

                Clear_OTFields();

                //Added By Tharuni for Request Submit
                let equipdetlen = $('#equipmentdetails_table>tbody>tr').length;
                let ReqArr = new Array();
                for (let i = 0; i < equipdetlen; i++) {
                    let obj = {};
                    obj.ServiceId = $('#eqp_tdEntityName_' + i).attr('data-id');
                    obj.VisitReportId = $('#HdnVisitId').val();
                    obj.Quantity = $('#eqp_tdSMCode_' + i).html();
                    obj.PatientId = $('#HdnPatientId').val();
                    obj.UserCreatedBy = $('#hiddenUser_id').val();
                    obj.SurgeryId = data1.Table[0].SurgeryId;
                    obj.Request_type = 1;
                    obj.DmlIndicator = 'CR';
                    obj.request_details_id = $('#EquipmentDetails_id_' + i).val();
                    obj.request_id = $('#HdnRequest_id').val();
                    ReqArr.push(obj);
                }
                let blooddetailslen = $('#blooddetails_table>tbody>tr').length;
                for (let i = 0; i < blooddetailslen; i++) {
                    let obj = {};
                    obj.ServiceId = $('#tdSM_' + i).attr('data-id');
                    obj.VisitReportId = $('#HdnVisitId').val();
                    //obj.Quantity = $('#tdSM_' + i).html();
                    obj.Quantity = $('#td_1' + i + ' td:eq(2)').text();
                    obj.Remarks = $('#tdbb_' + i).html();
                    obj.PatientId = $('#HdnPatientId').val();
                    obj.UserCreatedBy = $('#hiddenUser_id').val();
                    obj.SurgeryId = data1.Table[0].SurgeryId;
                    obj.Request_type = 2;
                    obj.DmlIndicator = 'CR';
                    obj.request_details_id = $('#BloodDetails_id_' + i).val();
                    obj.request_id = $('#HdnRequest_id').val();
                    ReqArr.push(obj);
                }
                $.ajax({
                    async: true,
                    type: 'POST',
                    url: '/Calender/CreateOTService',
                    contentType: 'application/json; charset=UTF-8',
                    data: JSON.stringify(ReqArr),
                    success: function (data) {
                        $('#equipmentdetails_table tbody').empty()
                        $('#blooddetails_table tbody').empty()
                        LoadOperationTheatre();
                        if (id) {

                            toastr.success('Updated successfully');

                            var currentPage = window.location.pathname;
                            var element = currentPage === '/calender/Index' ? 'col-md-6 col-sm-6 col-xs-12' : 'col-md-3 col-sm-3 col-xs-12';
                            $('.columnclass').attr('class', element);
                            if (currentPage === '/calender/Index') {

                            } else {
                                window.location.reload();
                            }
                        } else {

                            toastr.success('Added successfully');
                            var currentPage = window.location.pathname;
                            var element = currentPage === '/calender/Index' ? 'col-md-6 col-sm-6 col-xs-12' : 'col-md-3 col-sm-3 col-xs-12';
                            $('.columnclass').attr('class', element);
                            if (currentPage === '/calender/Index') {

                            } else {
                                window.location.reload();
                            }
                        }
                        $("#hdnEditId").val(null);
                        $('#otcreationpop').modal('hide');
                    }
                })

            }
        },
        error: function (xhr, status, error) {
            console.error(xhr.responseText);
            toastr.error('Data not added. Please try again.');
        }
    });
}



$('#btnMCDSubmit').click(function () {
    debugger;
    var fromDate = $("#dis_from").val();
    var toDate = $("#dis_to").val();

    var newfromdate = "";
    var newtodate = "";

    if (fromDate.trim() === "") {
        newfromdate = "";
    } else {
        var fromDatesplit = fromDate.split('/');
        newfromdate = fromDatesplit[2] + '-' + fromDatesplit[1] + '-' + fromDatesplit[0];
    }

    if (toDate.trim() === "") {
        newtodate = "";
    } else {
        var toDatesplit = toDate.split('/');
        newtodate = toDatesplit[2] + '-' + toDatesplit[1] + '-' + toDatesplit[0];
    }

    var surgeonName = $('#Hdndoctor_id').val();
    var surgeryName = $("#hdsur_id").val();
    var wardId = $("#ddTblSelectType").val();

    var surgeonNameValue = $("#docname_1").val();
    if (surgeonNameValue == "") {
        surgeonName = "";
    }

    var surgeryNameValue = $("#SurgeryName_1").val();
    if (surgeryNameValue == "") {
        surgeryName = "";
    }
    ddTblSelectType
    var wardTypeValue = $("#ddTblSelectType").val();
    if (wardTypeValue == "") {
        wardId = "";
    }

    LoadOperationTheatre(newfromdate, newtodate, surgeonName, surgeryName, wardId);
});

function LoadOperationTheatre(fromDate, toDate, surgeonName, surgeryName, wardId) {
    debugger;
    var Tem = {
        P_Dml_Indicator: "OTS",
        Date: fromDate,
        todate: toDate,
        Surgeon_Name: surgeonName,
        Surgery_Name: surgeryName,
        ward_id: wardId,
        Schedule_Type: 1
    };

    $.ajax({
        type: "POST",
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(Tem),
        success: function (data) {
            var OTlistpopup = JSON.parse(data);
            $('#labsetuptable_body').empty();
            $('#lab_table_list').dataTable().fnClearTable();
            $('#lab_table_list').dataTable().fnDraw();
            $('#lab_table_list').dataTable().fnDestroy();
            if (OTlistpopup && OTlistpopup.data && OTlistpopup.data.Table) {
                OTlistpopup = OTlistpopup.data.Table;
                var Hidenclasss = '';
                for (var i = 0; i < OTlistpopup.length; i++) {

                    if (OTlistpopup[i].ip_visit_report_status == 2) {
                        Hidenclasss = "hide";
                    } else {
                        Hidenclasss = "";
                    }

                    var row = "<tr id='row_" + (i + 1) + "'>" +
                        "<td>" + (i + 1) + "</td>" +
                        "<td>" + OTlistpopup[i].Surgery_Name + "</td>" +
                        "<td>" + OTlistpopup[i].Surgeon + "</td>" +
                        "<td>" + OTlistpopup[i].Patientid + "</td>" +
                        "<td>" + OTlistpopup[i].Room_name + "</td>" +
                        "<td>" + OTlistpopup[i].fromDate + "</td>" +
                        "<td>" + OTlistpopup[i].fromTime + "</td>" +
                        "<td style='display:none;' id='Rks_" + (i + 1) + "'>" + OTlistpopup[i].status + "</td>" +
                        "<td style='display:none;' id='Rs_" + (i + 1) + "'>" + OTlistpopup[i].schedule_status + "</td>" +
                        "<td class='tbl-action'>" +
                        "<a class='btn btn-sm btn-primary btn-edit " + Hidenclasss + "' data-id='" + OTlistpopup[i].id + "' title='Edit' onclick='OTEdit(" + OTlistpopup[i].id + ")' data-toggle='modal' data-target='#otcreationpop'><i class='fa fa-pencil fa-xs'></i></a>&nbsp;" +
                        "<button class='btn btn-sm btn-danger btn-delete " + Hidenclasss + "' data-id='" + OTlistpopup[i].id + "' title='Delete' onclick='OTDelete(" + OTlistpopup[i].id + ", \"" + OTlistpopup[i].schedule_status + "\")'><i class='fas fa-trash-alt fa-xs'></i></button>" +
                        "<div class='dropdown " + Hidenclasss + "'>" +
                        "<a href='#' class='dropdown-toggle btn btn-info-dots btn-xs ' data-toggle='dropdown' aria-expanded='false' id='other_info_" + OTlistpopup[i].id + "'><span class='fa fa-ellipsis-h' data-toggle='tooltip' data-placement='bottom' title='Other Options' style='color:black;' aria-hidden='true'></span><span class='sr-only'>Options</span></a>" +
                        "<div class='dropdown-menu' aria-labelledby='other_info_" + OTlistpopup[i].id + "'>" +
                        "<a data-toggle='modal' data-target='#addstatuspopup'  id='addStatus' onclick='setSelectedRowId(" + OTlistpopup[i].id + ")'>Add Status</a>" +
                        "</div>" +
                        "</div>" +
                        "</td>"
                    "</tr>";

                    $("#labsetuptable_body").append(row);
                }
                datatable('lab_table_list', 'Lab_setup', 'Legal');
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}




$('#otcreationpop').on('hidden.bs.modal', function () {

    $('#surgeryname').val("").trigger('change');
    $('#SelDoctor').val("").change();
    $('#cssdkit').val("");
    $('#PaitentSearch').val("");
    $('#OTroom').val("");
    $("#expdate").val("");
    $("#todate1").val("");
    $('#exptime').val("");
    $('#diagnosis').val("");
    $("#hdnEditId").val(null);
    $('#txt_AssSurgeonName').val("").change();
    $('#txt_AnaesthesianName').val("").change();
    $('#txt_ExpToTime').val("");
    $("#dd_Branch").val(0);
    $('#equipmentdetails_table tbody').empty();
    $('#blooddetails_table tbody').empty();
    $("#OTsubmit").text("Submit");
    $('#PaitentSearch').prop('disabled', false);

    // Reset the values inside the card
    $('.pat-stripe-user-name').html('');
    $('.pat_contact').html('');
    $('.pat_id').html('');
    $('.billing_class').html('');
    $('#Hpatientid').val('');
    $('#entity').hide();
    $('#div_tpa').hide();
    $('#tpa_insurance').html('');
    $('.age').html('');
    $('.height').html('');
    $('.weight').html('');
    $('#hdn_visit_doctorid').val('');
    $('#hdn_visit_doctorname').val('');
    $('.DOA').html('');
    $('.entity').html('');
    $('.visit').html('');
    $('.visit_date').html('');
    $('#Hvisitid').val('');
    $('#Vvisit_reportid').val('');
    $('.pat_address').html('');
    $('.doc_name').html('');
    $('.ward_id').html('');
    $('#Hwardid').val('');
    $('.bed_id').html('');
    $('#Hbedid').val('');
    $('.visit_type').html('');
    $('#OperationName').html('');
    $('#Hbilling_class').val('');
    $('#VBranch_id').val('');
    $('.IPpatblood,#IPpatblood').html('');
    $('#firstvisit,.firstvisit').html('');
    $('#app_no').hide();
    $('#app_yes').hide();
    $('#visit_name').html('IP Admission No : ');
    $("#CardPatientImage").attr("src", "/Content/img/profile_icon.png");

});



function OTEdit(Id) {
    debugger;
    var val = {
        P_Dml_Indicator: "OTE",
        id: Id,
        Schedule_Type: 1
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(val),
        success: function (data) {
            var OTlist = JSON.parse(data);
            var otc = OTlist.data.Table1;
            $('#equipmentdetails_table tbody').empty();
            $('#blooddetails_table tbody').empty();
            if (otc.length > 0) {

                for (var i = 0; i < otc.length; i++) {
                    var row = "<tr class='tr_input number' data-id='" + i + "' id='eqp_td_" + i + "'>" +
                        "<td>" + (i + 1) + "</td><input type='hidden' id='EquipmentDetails_id_" + i + "' value='" + otc[i].request_details_id + "'>" +
                        "<td id='eqp_tdEntityName_" + i + "' data-id=" + otc[i].master_service_id + ">" + otc[i].equipment + "</td>" +
                        "<td id='eqp_tdSMCode_" + i + "'>" + otc[i].quantity + "</td>" +
                        "<td><button class='btn-xs btn btn-delete btn-delete-equipment-row' data-id=" + i + " onclick='EquipmentDelete(\"" + i + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td>" +
                        "</tr>";
                    $("#equipmentdetails_table").append(row);
                }
            }



            var otdc = OTlist.data.Table2;

            if (otdc.length > 0) {

                for (var i = 0; i < otdc.length; i++) {
                    var row = "<tr class='tr_input number' data-id='" + i + "' id='td_1" + i + "'>" +
                        "<td>" + (i + 1) + "</td><input type='hidden' id='BloodDetails_id_" + i + "' value='" + otdc[i].request_details_id + "'>" +
                        "<td id='tdSM_" + i + "' data-id=" + otdc[i].master_service_id + ">" + otdc[i].blood_component + "</td>" +
                        "<td id='tdEntity_" + i + "'>" + otdc[i].quantity + "</td>" +
                        "<td id='tdbb_" + i + "'>" + otdc[i].remarks + "</td>" +
                        "<td><button class='btn-xs btn btn-delete btn-delete-blood-row' data-id=" + i + " onclick='BloodDelete(\"" + i + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td>" +
                        "</tr>";
                    $("#blooddetails_table").append(row);
                }
            }


            var valFromServer = JSON.parse(data).data.Table[0];
            $('#HdnRequest_id').val(valFromServer.request_id);
            $("#surgeryname").val(valFromServer.Surgery);
            //$("#SelDoctor").val(valFromServer.Surgeon);
            $("#cssdkit").val(valFromServer.CSSD_Kit);
            $("#PaitentSearch").val(valFromServer.Patientid);
            /*  $("#OTroom").val(valFromServer.Room_name);*/
            $("#expdate").val(valFromServer.fromDate);
            $("#todate1").val(valFromServer.toDate);
            $('#exptime').val(valFromServer.fromTime);
            $('#txt_ExpToTime').val(valFromServer.toTime);
            //$("#txt_AssSurgeonName").val(valFromServer.assistant_surgeon_);
            //$("#txt_AnaesthesianName").val(valFromServer.anaesthesian_);
            $("#dd_Branch").val(valFromServer.branch_id);
            var roomNameFromServer = valFromServer.Room_name;
            $('#OTroom option').filter(function () {
                return $(this).text() === roomNameFromServer;
            }).prop('selected', true);

            $("#hdnEditId").val(Id);
            //$("#Hdndoctor_id").val(valFromServer.Surgeon_Name);
            $("#hdpat_id").val(valFromServer.Patient_Name);
            $("#hdroom_id").val(valFromServer.Room_no);
            //$("#HdnAss_surgeonid").val(valFromServer.assistant_surgeon);
            //$("#HdnAnaesthesian_id").val(valFromServer.anaesthesian);
            $("#hdsur_id").val(valFromServer.Surgery_Name);
            $("#diagnosis").val(valFromServer.diagnosis);

            var selectElement = $('#surgeryname');
            var SurgeryNames = valFromServer.Surgery.split(',');
            var SurgeryIds = valFromServer.Surgery_Name.split(',').map(function (item) {
                return item.trim().split(':')[0];
            });
            SurgeryNames.forEach(function (name, index) {
                var id = SurgeryIds[index];
                var option = $('<option>').text(name.trim()).val(id);
                option.prop('selected', true);
                selectElement.append(option);
            });

            $("#OTsubmit").text("Update");
            Load_OTSurgery(valFromServer.visit_reportid);
            Load_SurgeonDoctor(valFromServer.Surgeon_Name);
            Load_AssSurgeonDoctor(valFromServer.assistant_surgeon);
            Load_Anaesthesian(valFromServer.anaesthesian);
            PatientSearch(valFromServer.Patient_Name, "2", valFromServer.branch_id, valFromServer.visit_report_id);

        }
    });
}

function OTDelete(id, schedule_status) {
    debugger;
    if (schedule_status == 2) {
        toastr.warning('Added pre OT,So Unable to delete');
    } else if (schedule_status == 3) {
        toastr.warning('Added post OT,So Unable to delete');
    } else {
        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 want to delete?', {
            closeButton: true,
            progressBar: true,
            allowHtml: true,
            timeOut: 20000000,

            onShown: function (toast) {
                $("#confirmationRevertYes").click(function () {
                    var OTdel = {
                        P_Dml_Indicator: "OTD",
                        id: id
                    };

                    $.ajax({
                        type: "POST",
                        url: '/Calender/OTList',
                        data: OTdel,
                        success: function (response) {
                            console.log(response);
                            toastr.success('Deleted successfully');
                            LoadOperationTheatre();
                        },
                        error: function (error) {
                            console.log(error);
                        }
                    });
                });

                $("#confirmationRevertNo").click(function () {
                    // Handle No button click if needed
                });
            }
        });
    }
}


function OTCsubmit() {
    debugger;
    var selectedBranch = $("#ot_Branch").val();
    if (selectedBranch === '0') {
        $("#Pot_Branch").show().html("Please Select Branch").fadeOut(8000);
        $('#Pot_Branch').focus();
        return false;
    }

    var txt_service_name = $("#txt_service_name").val().trim();
    if (txt_service_name === '') {
        $("#Pservicename").show().html("Please Enter Service Name").fadeOut(8000);
        $('#Pservicename').focus();
        return false;
    }

    var ScheduleType = $('#HdnTabId').val();

    if (ScheduleType == 4) {
        var txt_Technician = $("#txt_Technician").val().trim();
        if (txt_Technician == '') {
            $("#Ptxt_Technician").show().html("Please Select Technician Name").fadeOut(8000);
            $('#Ptxt_Technician').focus();
            return false;
        }
        var Technicianid = $("#Hdn_user_id").val().trim();
        if (Technicianid == '' || Technicianid == '0') {
            $("#Ptxt_Technician").show().html("Please Select Technician Name").fadeOut(8000);
            $('#Ptxt_Technician').focus();
            return false;
        }
    }
    else {
        var txt_DMO = $("#txt_DMO").val().trim();
        if (txt_DMO === '') {
            $("#Pdmo").show().html("Please Enter DMO Name").fadeOut(8000);
            $('#Pdmo').focus();
            return false;
        }

        var docname = $("#docname").val().trim();
        if (docname === '') {
            $("#Pdocname").show().html("Please Enter Doctor Name").fadeOut(8000);
            $('#Pdocname').focus();

        }

        var selectedTherapists = $("#personname").val();
        if (selectedTherapists === null || selectedTherapists.length === 0) {
            $("#Ppersonname").show().html("Please Select Therapist Name").fadeOut(8000);
            $('#Ppersonname').focus();

        }
    }

    var txtPaitentSearch_bill = $("#txtPaitentSearch_bill").val().trim();
    if (txtPaitentSearch_bill === '') {
        $("#Ppatname").show().html("Please Enter Patient Name").fadeOut(8000);
        $('#Ppatname').focus();
        return false;
    }

    var date = $("#date").val().trim();
    if (date === '') {
        $("#Pdate").show().html("Please Enter Date").fadeOut(8000);
        $('#Pdate').focus();
        return false;
    }

    var to_date = $("#to_date").val().trim();
    if (to_date === '') {
        $("#Ptodate").show().html("Please Enter To Date").fadeOut(8000);
        $('#Ptodate').focus();
        return false;

    }

    var selectedDate = null;
    if ($("#date").val() != '') {
        var dateParts = $("#date").val().split('/');
        selectedDate = dateParts[2] + '-' + dateParts[1] + '-' + dateParts[0];
    }

    var toSelectedDate = null;
    if ($("#to_date").val() != '') {
        var toDateParts = $("#to_date").val().split('/');
        toSelectedDate = toDateParts[2] + '-' + toDateParts[1] + '-' + toDateParts[0];
    }

    //var time = $("#time").val();
    //var convertedTime = moment(time, 'hh:mm A').format('HH:mm');

    //var To_time = $("#endtime").val();
    //var convertedendTime = moment(To_time, 'hh:mm A').format('HH:mm');
    //var id = $("#hdnEditId").val();

    if ($('#time').val() == "") {
        $("#Ptime").show();
        $("#Ptime").html("Select Start Time").fadeOut(8000);
        $('#Ptime').focus();

        return false;
    }

    if ($('#endtime').val() == "") {
        $("#Pendtime").show();
        $("#Pendtime").html("Select End Time").fadeOut(8000);
        $('#Pendtime').focus();

        return false;
    }
    if ($('#hdnslotid').val() == "" || $('#hdnslotid').val() == null) {
        toastr.warning("Slot not available")
        return false;
    }
    var FromTime = $("#time").val();
    var Exp_FromTime = moment(FromTime, 'hh:mm A');
    var ins_FromTime = moment(FromTime, 'hh:mm A').format('HH:mm');
    var FromMinutes = Exp_FromTime.hours() * 60 + Exp_FromTime.minutes();

    var ToTime = $("#endtime").val();
    var Exp_ToTime = moment(ToTime, 'hh:mm A');
    var ins_ToTime = moment(ToTime, 'hh:mm A').format('HH:mm');
    var ToMinutes = Exp_ToTime.hours() * 60 + Exp_ToTime.minutes()
    var id = $("#hdnEditId").val();

    if (FromMinutes >= ToMinutes) {
        $("#Pendtime").show();
        $("#Pendtime").html("End Time should be greater than Start Time").fadeOut(8000);
        $('#time').focus();
        return false;
    }

    //added by nandhini for inventory trigger on save therapy
    if (ScheduleType == 3) {
        var totalitemsrow = $('#tbl_consumables>tbody>tr').length;
        if (totalitemsrow <= 0) {
            toastr.warning("Kindly add service items");
            return false;
        }
    }

    var Consunables_data = [];
    var tot_len = $('#tbl_consumables>tbody>tr').length;
    for (var i = 1; i <= tot_len; i++) {
        var con_lab = {};
        con_lab.hospitalId = $('#HospitalIdInt').val(),
            con_lab.itemName = $('#con_name_' + i).html(),
            con_lab.itemId = $('#item_id_' + i).html(),
            con_lab.qty = $('#con_quan_' + i).html(),
            con_lab.createdBy = $('#hiddenUser_id' + i).html()
        Consunables_data.push(con_lab);

    }



    // Function to send AJAX request for each date in the range
    /* function sendRequestForDate(date) {*/
    var OTBdata = {
        P_Dml_Indicator: id ? "OTU" : "OTI",
        id: id,
        Service_Name: $('#hdserve_id').val(),
        Patient_Name: $('#hdpat_id').val(),
        DMO: $('#Hdn_user_id').val(),
        Person_Name: $('#Hdata_id').val().toString(),//$('#Hdn_user_id1').val().toString(),
        Doctor_Name: $('#Hdndoctor_id').val(),
        Room_no: $('#hdroom_id').val(),
        fromDate: selectedDate,
        fromTime: ins_FromTime,
        toTime: ins_ToTime,
        toDate: toSelectedDate,
        Remarks: $('#remarks').val(),
        serviceid: $('#hdserveid').val(),
        branch_id: $('#ot_Branch').val(),
        //Schedule_Type: ($('#modalHeading').text() === 'Book a Day Care Schedule') ? 2 : 3
        Schedule_Type: ScheduleType,
        itemlist: Consunables_data,
        schedule_request_id: $('#hdnScheduleRequestId').val(),
        store_id: $('#store_name').val(),
        store_branch_id: $('#store_name :selected').attr('data-id'),
        store_branchmap_id: $('#store_name :selected').attr('data-mapid'),
        HospitalIdInt: $('#HospitalIdInt').val(),
        patientid_Int: $('#HdnPatientId').val(),
        doctor_appointment_slot_id: $('#hdnslotid').val()
    };
    if (to_date == null && to_date == undefined && to_date == '') {
        OTBdata.To_date = to_date;
    }
    debugger;
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTBdata),
        success: function (data) {

            debugger;
            var data1 = JSON.parse(data);
            debugger;
            if (data1.data.Table[0].msg == "Already have appointment") {
                toastr.warning("Already have appointment for this patient on this time ");
            }
            else if (data1.data.Table[0].ErrorMsg == "Room Exist" || data1.msg === "Room exist") {
                toastr.warning("Room exists");
            }
            else if (data1.data.Table[0].ErrorMsg == "Already scheduled") {
                toastr.warning("Time Slot Exist");
            }

            else if (data1.data.Table[0].msg == "DATE ALREADY EXISTS") {
                var dates = data1.data.Table[0].existingdate;
                toastr.warning("TIME ALREADY EXISTS ON " + dates);
            }
            else if (data1.data.Table[0].msg == "Validation Failed") {
                toastr.warning("Slot Exist");
            }
            else if (data1.data.Table[0].msg == "Insert successfully") {
                toastr.success("Successfully Created");
                location.reload();

                $("#hdnEditId").val(null);
                $('#bookingpop').modal('hide');
                $('#txt_service_name').val("");
                $('#txtPaitentSearch_bill').val("");
                $('#txt_DMO').val("");
                $('#docname').val("");
                $('#personname').val("").change();
                $('#room').val("");
                $('#date').val("");
                $('#time').val("");
                $('#endtime').val("");
                $('#remarks').val("");
                $('#tblPatientAppiontment').empty();
                $('#store_name').attr('disabled', false);
            }
            else if (data1.data.Table[0].msg == "Update Successful") {
                toastr.success("Updated Successfully");

                $("#hdnEditId").val(null);
                $('#bookingpop').modal('hide');
                $('#txt_service_name').val("");
                $('#txtPaitentSearch_bill').val("");
                $('#txt_DMO').val("");
                $('#docname').val("");
                $('#personname').val("").change();
                $('#room').val("");
                $('#date').val("");
                $('#time').val("");
                $('#endtime').val("");
                $('#remarks').val("");
                $('#tblPatientAppiontment').empty();

            }
            if (OTBdata.Schedule_Type === 2) {
                LoadDayCare();
            } else if (OTBdata.Schedule_Type === 3) {
                LoadMassage();
            }

            /*   $('#bookingpop').modal('hide');*/

        },
        error: function (xhr, status, error) {
            console.error(xhr.responseText);
            toastr.error('Data not added. Please try again.');
        }
    });
}




// Iterate over the date range and send requests for each date
//    var currentDate = moment(selectedDate);
//    var endDate = moment(toSelectedDate);
//    while (currentDate <= endDate) {
//        sendRequestForDate(currentDate.format('YYYY-MM-DD'));
//        currentDate.add(1, 'days');
//    }
//}

$('#btnDCSubmit').click(function () {
    debugger;
    var fromDate = $("#dis_from_1").val();
    var toDate = $("#dis_to_1").val();

    var newfromdate = "";
    var newtodate = "";

    if (fromDate.trim() === "") {
        newfromdate = "";
    } else {
        var fromDatesplit = fromDate.split('/');
        newfromdate = fromDatesplit[2] + '-' + fromDatesplit[1] + '-' + fromDatesplit[0];
    }

    if (toDate.trim() === "") {
        newtodate = "";
    } else {
        var toDatesplit = toDate.split('/');
        newtodate = toDatesplit[2] + '-' + toDatesplit[1] + '-' + toDatesplit[0];
    }

    var patientName = $("#hdpat_id").val();
    var serviceName = $("#hdserve_id").val();
    var patientNameValue1 = $("#daycarepat").val();
    if (patientNameValue1 == "") {
        patientName = "";
    }

    var serviceNameValue1 = $("#DcareService").val();
    if (serviceNameValue1 == "") {
        serviceName = "";
    }

    LoadDayCare(newfromdate, newtodate, patientName, serviceName);
});

function LoadDayCare(fromDate, toDate, patientName, serviceName) {
    debugger;
    var DCPopup = {
        P_Dml_Indicator: "SDC",
        fromDate: fromDate,
        toDate: toDate,
        Patient_name: patientName,
        Service_Name: serviceName,
        Schedule_Type: 2
    };

    $.ajax({
        type: "POST",
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(DCPopup),
        success: function (data) {
            var DClistpopup = JSON.parse(data);
            $('#dclistbody').empty();
            $('#dclist').dataTable().fnClearTable();
            $('#dclist').dataTable().fnDraw();
            $('#dclist').dataTable().fnDestroy();
            if (DClistpopup && DClistpopup.data && DClistpopup.data.Table) {
                DClistpopup = DClistpopup.data.Table;
                for (var i = 0; i < DClistpopup.length; i++) {
                    var row = "<tr id='row_" + (i + 1) + "'>" +
                        "<td>" + (i + 1) + "</td>" +
                        "<td style='display:none;' id='DCid_" + (i + 1) + "'>" + DClistpopup[i].id + "</td>" +
                        "<td data-id=" + DClistpopup[i].Service_Name + " id=service_name_" + (i + 1) + ">" + DClistpopup[i].Service + "</td>" +
                        "<td data-id=" + DClistpopup[i].Doctor_Name + " id=Doctor_Name_" + (i + 1) + ">" + DClistpopup[i].Doctor + "</td>" +
                        "<td data-id=" + DClistpopup[i].DMO + " id=dmo" + (i + 1) + ">" + DClistpopup[i].dmo_name + "</td>" +
                        "<td data-id=" + DClistpopup[i].Patient_Name + " id=Patient_Name_" + (i + 1) + ">" + DClistpopup[i].Patient + "</td>" +
                        "<td data-id=" + DClistpopup[i].Room_no + " id=Room_no_" + (i + 1) + ">" + DClistpopup[i].Room_name + "</td>" +
                        "<td id='Date_" + (i + 1) + "'>" + DClistpopup[i].fromDate + "</td>" +
                        //"<td id='to_Date" + (i + 1) + "'>" + DClistpopup[i].To_Date + "</td>" +
                        "<td id='Time_" + (i + 1) + "'>" + DClistpopup[i].fromTime + "</td>" +
                        "<td id='to_Time_" + (i + 1) + "'>" + DClistpopup[i].toTime + "</td>" +
                        "<td style='display:none;' id='Remarks_" + (i + 1) + "'>" + DClistpopup[i].Remarks + "</td>" +
                        "<td class='tbl-action'>" +
                        "<button class='btn btn-sm btn-primary btn-edit' data-id='" + DClistpopup[i].id + "' title='Edit' data-heading='daycare' onclick='DCEdit(" + DClistpopup[i].id + ")'data-toggle='modal' data-target='#bookingpop'><i class='fa fa-pencil fa-xs'></i></button>&nbsp;" +
                        "<button class='btn btn-sm btn-danger btn-delete' data-id='" + DClistpopup[i].id + "' title='Delete' onclick='DCDelete(" + DClistpopup[i].id + ")'><i class='fas fa-trash-alt fa-xs'></i></button>" +
                        "</td>" +
                        "</tr>";

                    $("#dclistbody").append(row);
                }
                datatable('dclist', 'DCCare', 'Legal');
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function DCEdit(Id) {
    debugger;
    var valdc = {
        P_Dml_Indicator: "OTDC",
        id: Id,
        Schedule_Type: 2
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(valdc),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var valdc = data1.data.Table[0];
            $("#txt_service_name").val(valdc.Service);
            $("#docname").val(valdc.Doctor);
            /*$("#txtPaitentSearch_bill").val(valdc.Patient);*/
            //$("#txtPaitentSearch_bill").val(valdc.Patient).attr('readonly', true);
            $("#txtPaitentSearch_bill").val(valdc.Patient).prop('disabled', true);
            $("#room").val(valdc.Room_name);
            $("#date").val(valdc.fromDate);
            $("#to_date").val(valdc.toDate);
            $('#time').val(valdc.fromTime);
            $('#endtime').val(valdc.toTime);
            $('#txt_DMO').val(valdc.dmo_name);
            $("#ot_Branch").val(valdc.branch_id);
            $('#remarks').val(valdc.Remarks);

            $(".to_dateCls").hide();
            $("#hdnEditId").val(Id);

            $("#hdroom_id").val(valdc.Room_no);
            $("#hdserve_id").val(valdc.Service_Name);
            $("#hdpat_id").val(valdc.Patient_Name);
            $("#Hdndoctor_id").val(valdc.Doctor_Name);
            $("#Hdn_user_id").val(valdc.DMO);

            $("#OTCsubmit").text("Update");

        }
    });
}


function DCDelete(id) {
    debugger;

    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 want to delete?', {
        closeButton: true,
        progressBar: true,
        allowHtml: true,
        timeOut: 20000000,

        onShown: function (toast) {
            $("#confirmationRevertYes").click(function () {
                var Dcdel = {
                    P_Dml_Indicator: "OTD",
                    id: id
                };

                $.ajax({
                    type: "POST",
                    url: '/Calender/OTList',
                    data: Dcdel,
                    success: function (response) {
                        console.log(response);

                        LoadDayCare();
                        toastr.success('Deleted successfully');
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });

            $("#confirmationRevertNo").click(function () {
                // Handle No button click if needed
            });
        }
    });
}




$('#btnMGSubmit').click(function () {
    debugger;
    var fromDate = $("#dis_from_2").val();
    var toDate = $("#dis_to_2").val();

    var newfromdate = "";
    var newtodate = "";

    if (fromDate.trim() === "") {
        newfromdate = "";
    } else {
        var fromDatesplit = fromDate.split('/');
        newfromdate = fromDatesplit[2] + '-' + fromDatesplit[1] + '-' + fromDatesplit[0];
    }

    if (toDate.trim() === "") {
        newtodate = "";
    } else {
        var toDatesplit = toDate.split('/');
        newtodate = toDatesplit[2] + '-' + toDatesplit[1] + '-' + toDatesplit[0];
    }

    var patientName = $("#hdpat_id").val();
    var serviceName = $("#hdserve_id").val();
    var patientNameValue = $("#massagepatlist").val();
    if (patientNameValue == "") {
        patientName = "";
    }

    var serviceNameValue = $("#MService").val();
    if (serviceNameValue == "") {
        serviceName = "";
    }

    LoadMassage(newfromdate, newtodate, patientName, serviceName);
});

function LoadMassage(fromDate, toDate, patientName, serviceName) {
    var MPopup = {
        P_Dml_Indicator: "SDM",
        fromDate: fromDate,
        toDate: toDate,
        Patient_name: patientName,
        Service_Name: serviceName,
        Schedule_Type: 3
    };

    $.ajax({
        type: "POST",
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(MPopup),
        success: function (data) {
            var Mlistpopup = JSON.parse(data).data.Table;

            $('#labbody').empty();
            $('#masage_table').dataTable().fnClearTable();
            $('#masage_table').dataTable().fnDraw();
            $('#masage_table').dataTable().fnDestroy();

            if (Mlistpopup && Mlistpopup.length > 0) {
                for (var i = 0; i < Mlistpopup.length; i++) {
                    /*  var status = Mlistpopup[i].schedule_status == 5 ? "Completed" : "Pending";*/
                    var status = (Mlistpopup[i].is_day_complete == 1) ? "Completed" :
                        (Mlistpopup[i].schedule_status == 5 ? "Completed" : "Pending");


                    var raiseBillOption = Mlistpopup[i].schedule_status == 5 ||  Mlistpopup[i] bill_no !=null
                        ? "" : "<li><a href='javascript:void(0);' onclick='quickbill(\"" + Mlistpopup[i].visit_report_id + "\", \"" + Mlistpopup[i].patientid + "\", \"" + Mlistpopup[i].branch_id + "\", \"" + Mlistpopup[i].DMO + "\")' title='Raise Bill' class='hm-dt-action edit'>Raise Bill</a></li>"
                        ;

                    var row = "<tr id='row_" + (i + 1) + "'>" +
                        "<td>" + (i + 1) + "</td>" +
                        "<td style='display:none;' id='Mid_" + (i + 1) + "'>" + Mlistpopup[i].id + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Service_Name + " id=MService_name_" + (i + 1) + ">" + Mlistpopup[i].Service_n + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Person_Name + " id=MPerson_Name_" + (i + 1) + ">" + Mlistpopup[i].Multi_Person_Name + "</td>" +
                        "<td data-id=" + Mlistpopup[i].DMO + " id=dmo" + (i + 1) + ">" + Mlistpopup[i].dmo_name + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Patient_Name + " id=MPatientName_" + (i + 1) + ">" + Mlistpopup[i].Patient_n + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Room_no + " id=Roomno_" + (i + 1) + ">" + Mlistpopup[i].Room_n + "</td>" +
                        "<td id='MDate_" + (i + 1) + "'>" + Mlistpopup[i].fromDate + "</td>" +
                        "<td id='MTime_" + (i + 1) + "'>" + Mlistpopup[i].fromTime + "</td>" +
                        "<td id='MendTime_" + (i + 1) + "'>" + Mlistpopup[i].toTime + "</td>" +
                        "<td id='MStatus_" + (i + 1) + "'>" + status + "</td>" +
                        "<td class='tbl-action'>" +
                        "<div class='dropdown'>" +
                        "<i class='fa fa-ellipsis-h dropdown-toggle pull-right' data-toggle='dropdown' aria-expanded='true'></i>" +
                        "<ul class='dropdown-menu info-dropdown-new'>" +
                        "<div class='disp_if'>" +
                        "<button class='btn btn-sm btn-primary btn-edit' data-id='" + Mlistpopup[i].id + "' title='Edit' data-heading='physio' onclick='MEditphysio(" + Mlistpopup[i].id + ")' data-toggle='modal' data-target='#bookingpop'><i class='fa fa-pencil fa-xs'></i></button>&nbsp;" + "<button class='btn btn-sm btn-secondary btn-therapist'onclick='Loadtherapistpopup(" + Mlistpopup[i].id + ")' data-id='" + Mlistpopup[i].id + "' title='Edit Therapist' data-toggle='modal' data-id='" + Mlistpopup[i].id + "' data-target='#therapistpopup'><i class='fas fa-pen-alt'></i></button>&nbsp;" +
                        "<button class='btn btn-sm btn-danger btn-delete' data-id='" + Mlistpopup[i].id + "' title='Delete' onclick='MDelete(" + Mlistpopup[i].id + ")'><i class='fas fa-trash-alt fa-xs'></i></button>&nbsp;" +
                        "</div>" +
                        raiseBillOption +
                        "</ul>" +
                        "</div>" +
                        "</td>" +
                        "</tr>";

                    $("#labbody").append(row);
                }
                datatable('masage_table', 'Lab_set', 'Legal');
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}


function quickbill(visit_report_id, patient_id, branch_id, dmo) {
    debugger;

    window.location.href = '/BillingMaster/index?FPId=' + patient_id + '&FBId=' + branch_id + '&FDMO=' + dmo;


}

//function quickbill(visit_report_id, patient_id, branch_id, dmo) {
//    debugger;

//    if (visit_report_id != null && visit_report_id != "null" && visit_report_id != "") {
//        window.location.href = '/BillingMaster/index?FPId=' + patient_id + '&FBId=' + branch_id + '&FDMO=' + dmo;
//        //window.location.href = '/BillingMaster/index?visit_report_id=' + visit_report_id + '&patientid=' + patient_id + '&branch_id=' + branch_id + '&dmo=' + dmo + '&type=1&doctorid=';
//    }
//    else {
//        //creata healthcare visit 
//        var VisitreportId = {
//            P_Dml_Indicator: "HVC",
//            branch_id: branch_id,
//            Patient_Name: patient_id
//        };
//        $.ajax({
//            async: true,
//            type: 'POST',
//            url: '/Calender/OTCreation',
//            contentType: 'application/json; charset=UTF-8',
//            data: JSON.stringify(VisitreportId),
//            success: function (data) {
//                debugger;
//                var data = JSON.parse(data);
//                if (data.msg == "Success") {
//                    var data = data.data;
//                    if (jQuery.isEmptyObject((data))) {

//                    }
//                    else {

//                        if (data.Table.length > 0) {
//                            var VisitReportID = (data.Table[0].visit_report_id);
//                            window.location.href = '/BillingMaster/index?FPId=' + patient_id + '&FBId=' + branch_id + '&FDMO=' + dmo;

//                            //window.location.href = '/BillingMaster/index?visit_report_id=' + VisitReportID + '&patientid=' + patient_id + '&branch_id=' + branch_id + '&dmo=' + dmo + '&type=2&doctorid=';
//                        }
//                    }
//                }
//            }
//        });

//    }

//}
function Loadphysio(fromDate, toDate, patientName, serviceName) {
    var MPopup = {
        P_Dml_Indicator: "SDM",
        fromDate: fromDate,
        toDate: toDate,
        Patient_name: patientName,
        Service_Name: serviceName,
        Schedule_Type: 7
    };

    $.ajax({
        type: "POST",
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(MPopup),
        success: function (data) {
            var Mlistpopup = JSON.parse(data).data.Table;

            $('#physiobody').empty();
            $('#physio_table').dataTable().fnClearTable();
            $('#physio_table').dataTable().fnDraw();
            $('#physio_table').dataTable().fnDestroy();

            if (Mlistpopup && Mlistpopup.length > 0) {
                for (var i = 0; i < Mlistpopup.length; i++) {
                    var status = Mlistpopup[i].schedule_status == 5 ? "Completed" : "Pending";

                    var raiseBillOption = Mlistpopup[i].schedule_status == 5
                        ? "" : "<li><a href='javascript:void(0);' onclick='quickbill(\"" + Mlistpopup[i].visit_report_id + "\", \"" + Mlistpopup[i].patientid + "\", \"" + Mlistpopup[i].branch_id + "\", \"" + Mlistpopup[i].DMO + "\")' title='Raise Bill' class='hm-dt-action edit'>Raise Bill</a></li>";

                    var row = "<tr id='row_" + (i + 1) + "'>" +
                        "<td>" + (i + 1) + "</td>" +
                        "<td style='display:none;' id='Mid_" + (i + 1) + "'>" + Mlistpopup[i].id + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Service_Name + " id=MService_name_" + (i + 1) + ">" + Mlistpopup[i].Service_n + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Person_Name + " id=MPerson_Name_" + (i + 1) + ">" + Mlistpopup[i].Multi_Person_Name + "</td>" +
                        "<td data-id=" + Mlistpopup[i].DMO + " id=dmo" + (i + 1) + ">" + Mlistpopup[i].dmo_name + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Patient_Name + " id=MPatientName_" + (i + 1) + ">" + Mlistpopup[i].Patient_n + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Room_no + " id=Roomno_" + (i + 1) + ">" + Mlistpopup[i].Room_n + "</td>" +
                        "<td id='MDate_" + (i + 1) + "'>" + Mlistpopup[i].fromDate + "</td>" +
                        "<td id='MTime_" + (i + 1) + "'>" + Mlistpopup[i].fromTime + "</td>" +
                        "<td id='MendTime_" + (i + 1) + "'>" + Mlistpopup[i].toTime + "</td>" +
                        "<td id='MStatus_" + (i + 1) + "'>" + status + "</td>" +
                        "<td class='tbl-action'>" +
                        "<div class='dropdown'>" +
                        "<i class='fa fa-ellipsis-h dropdown-toggle pull-right' data-toggle='dropdown' aria-expanded='true'></i>" +
                        "<ul class='dropdown-menu info-dropdown-new'>" +
                        "<div class='disp_if'>" +
                        "<button class='btn btn-sm btn-primary btn-edit' data-id='" + Mlistpopup[i].id + "' title='Edit' data-heading='physio' onclick='MEditphysio(" + Mlistpopup[i].id + ")' data-toggle='modal' data-target='#bookingpop'><i class='fa fa-pencil fa-xs'></i></button>&nbsp;" + "<button class='btn btn-sm btn-secondary btn-therapist'onclick='Loadtherapistpopup(" + Mlistpopup[i].id + ")' data-id='" + Mlistpopup[i].id + "' title='Edit Therapist' data-toggle='modal' data-id='" + Mlistpopup[i].id +"' data-target='#therapistpopup'><i class='fas fa-pen-alt'></i></button>&nbsp;"+
                        "<button class='btn btn-sm btn-danger btn-delete' data-id='" + Mlistpopup[i].id + "' title='Delete' onclick='MDelete(" + Mlistpopup[i].id + ")'><i class='fas fa-trash-alt fa-xs'></i></button>&nbsp;" +
                        "</div>" +
                        raiseBillOption +
                        "</ul>" +
                        "</div>" +
                        "</td>" +
                        "</tr>";

                    $("#physiobody").append(row);
                }
                datatable('physio_table', 'physio_set', 'Legal');
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}
function Loadyoga(fromDate, toDate, patientName, serviceName) {
    var MPopup = {
        P_Dml_Indicator: "SDM",
        fromDate: fromDate,
        toDate: toDate,
        Patient_name: patientName,
        Service_Name: serviceName,
        Schedule_Type: 8
    };

    $.ajax({
        type: "POST",
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(MPopup),
        success: function (data) {
            var Mlistpopup = JSON.parse(data).data.Table;

            $('#yogabody').empty();
            $('#yoga_table').dataTable().fnClearTable();
            $('#yoga_table').dataTable().fnDraw();
            $('#yoga_table').dataTable().fnDestroy();

            if (Mlistpopup && Mlistpopup.length > 0) {
                for (var i = 0; i < Mlistpopup.length; i++) {
                    var status = Mlistpopup[i].schedule_status == 5 ? "Completed" : "Pending";

                    var raiseBillOption = Mlistpopup[i].schedule_status == 5
                        ? "" : "<li><a href='javascript:void(0);' onclick='quickbill(\"" + Mlistpopup[i].visit_report_id + "\", \"" + Mlistpopup[i].patientid + "\", \"" + Mlistpopup[i].branch_id + "\", \"" + Mlistpopup[i].DMO + "\")' title='Raise Bill' class='hm-dt-action edit'>Raise Bill</a></li>";

                    var row = "<tr id='row_" + (i + 1) + "'>" +
                        "<td>" + (i + 1) + "</td>" +
                        "<td style='display:none;' id='Mid_" + (i + 1) + "'>" + Mlistpopup[i].id + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Service_Name + " id=MService_name_" + (i + 1) + ">" + Mlistpopup[i].Service_n + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Person_Name + " id=MPerson_Name_" + (i + 1) + ">" + Mlistpopup[i].Multi_Person_Name + "</td>" +
                        "<td data-id=" + Mlistpopup[i].DMO + " id=dmo" + (i + 1) + ">" + Mlistpopup[i].dmo_name + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Patient_Name + " id=MPatientName_" + (i + 1) + ">" + Mlistpopup[i].Patient_n + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Room_no + " id=Roomno_" + (i + 1) + ">" + Mlistpopup[i].Room_n + "</td>" +
                        "<td id='MDate_" + (i + 1) + "'>" + Mlistpopup[i].fromDate + "</td>" +
                        "<td id='MTime_" + (i + 1) + "'>" + Mlistpopup[i].fromTime + "</td>" +
                        "<td id='MendTime_" + (i + 1) + "'>" + Mlistpopup[i].toTime + "</td>" +
                        "<td id='MStatus_" + (i + 1) + "'>" + status + "</td>" +
                        "<td class='tbl-action'>" +
                        "<div class='dropdown'>" +
                        "<i class='fa fa-ellipsis-h dropdown-toggle pull-right' data-toggle='dropdown' aria-expanded='true'></i>" +
                        "<ul class='dropdown-menu info-dropdown-new'>" +
                        "<div class='disp_if'>" +
                        "<button class='btn btn-sm btn-primary btn-edit' data-id='" + Mlistpopup[i].id + "' title='Edit' data-heading='physio' onclick='MEditphysio(" + Mlistpopup[i].id + ")' data-toggle='modal' data-target='#bookingpop'><i class='fa fa-pencil fa-xs'></i></button>&nbsp;" + "<button class='btn btn-sm btn-secondary btn-therapist'onclick='Loadtherapistpopup(" + Mlistpopup[i].id + ")' data-id='" + Mlistpopup[i].id + "' title='Edit Therapist' data-toggle='modal' data-id='" + Mlistpopup[i].id + "' data-target='#therapistpopup'><i class='fas fa-pen-alt'></i></button>&nbsp;" +
                        "<button class='btn btn-sm btn-danger btn-delete' data-id='" + Mlistpopup[i].id + "' title='Delete' onclick='MDelete(" + Mlistpopup[i].id + ")'><i class='fas fa-trash-alt fa-xs'></i></button>&nbsp;" +
                        "</div>" +
                        raiseBillOption +
                        "</ul>" +
                        "</div>" +
                        "</td>" +
                        "</tr>";

                    $("#yogabody").append(row);
                }
                datatable('yoga_table', 'yoga_set', 'Legal');
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function MDelete(id) {
    debugger;

    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 want to delete?', {
        closeButton: true,
        progressBar: true,
        allowHtml: true,
        timeOut: 20000000,

        onShown: function (toast) {
            $("#confirmationRevertYes").click(function () {
                var Mdel = {
                    P_Dml_Indicator: "OTD",
                    id: id
                };

                $.ajax({
                    type: "POST",
                    url: '/Calender/OTList',
                    data: Mdel,
                    success: function (response) {
                        console.log(response);

                        LoadMassage();
                        Loadphysio();
                        Loadyoga();
                        toastr.success('Delete successfully');
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });

            $("#confirmationRevertNo").click(function () {
                // Handle No button click if needed
            });
        }
    });
}

function MEdit(Id) {
    debugger;
    var MPopup = {
        P_Dml_Indicator: "OTLM",
        id: Id,
        Schedule_Type: 3
    };

    $.ajax({
        type: "POST",
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(MPopup),
        success: function (data) {
            var data1 = JSON.parse(data);
            var MPopup = data1.data.Table[0];
            debugger;

            $("#txt_service_name").val(MPopup.Service_n);
            $('#personname').val(MPopup.Multi_Person_Name);
            /* $("#txtPaitentSearch_bill").val(MPopup.Patient_n).attr('readonly', true);*/
            $("#txtPaitentSearch_bill").val(MPopup.Patient_n).prop('disabled', true);
            $("#room").val(MPopup.Room_n);
            $("#date").val(MPopup.fromDate);
            $("#to_date").val(MPopup.toDate);
            $('#time').val(MPopup.fromTime);
            $('#endtime').val(MPopup.toTime);
            $('#txt_DMO').val(MPopup.dmo_name);
            $('#remarks').val(MPopup.Remarks);
            //$("#to_date").closest('.form-group').hide();
            $(".to_dateCls").hide();
            $("#ot_Branch").val(MPopup.branch_id);
            $("#hdnEditId").val(Id);
            $("#hdroom_id").val(MPopup.Room_no);
            $("#hdserve_id").val(MPopup.Service_Name);
            $("#hdpat_id").val(MPopup.Patient_Name);
            $("#Hdndoctor_id").val(MPopup.Person_Name);
            $("#Hdn_user_id").val(MPopup.DMO);
            var selectElement = $('#personname');

            var therapistNames = MPopup.Multi_Person_Name.split(',');
            var therapistIds = MPopup.Person_Name.split(',').map(function (item) {
                return item.trim().split(':')[0];
            });
            $('#personname').empty();
            therapistNames.forEach(function (name, index) {
                var id = therapistIds[index];
                var option = $('<option>').text(name.trim()).val(id);
                option.prop('selected', true);
                selectElement.append(option);
            });


            $("#OTCsubmit").text("Update");


        }

    });
}
function MEditphysio(Id) {
    debugger;
    var MPopup = {
        P_Dml_Indicator: "OTLM",
        id: Id,
        Schedule_Type: 7
    };

    $.ajax({
        type: "POST",
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(MPopup),
        success: function (data) {
            var data1 = JSON.parse(data);
            var MPopup = data1.data.Table[0];
            debugger;

            $("#txt_service_name").val(MPopup.Service_n);
            $('#personname').val(MPopup.Multi_Person_Name);
            /* $("#txtPaitentSearch_bill").val(MPopup.Patient_n).attr('readonly', true);*/
            $("#txtPaitentSearch_bill").val(MPopup.Patient_n).prop('disabled', true);
            $("#room").val(MPopup.Room_n);
            $("#date").val(MPopup.fromDate);
            $("#to_date").val(MPopup.toDate);
            $('#time').val(MPopup.fromTime);
            $('#endtime').val(MPopup.toTime);
            $('#txt_DMO').val(MPopup.dmo_name);
            $('#remarks').val(MPopup.Remarks);
            //$("#to_date").closest('.form-group').hide();
            $(".to_dateCls").hide();
            $("#ot_Branch").val(MPopup.branch_id);
            $("#hdnEditId").val(Id);
            $("#hdroom_id").val(MPopup.Room_no);
            $("#hdserve_id").val(MPopup.Service_Name);
            $("#hdpat_id").val(MPopup.Patient_Name);
            $("#Hdndoctor_id").val(MPopup.Person_Name);
            $("#Hdn_user_id").val(MPopup.DMO);
            var selectElement = $('#personname');

            var therapistNames = MPopup.Multi_Person_Name.split(',');
            var therapistIds = MPopup.Person_Name.split(',').map(function (item) {
                return item.trim().split(':')[0];
            });
            $('#personname').empty();
            therapistNames.forEach(function (name, index) {
                var id = therapistIds[index];
                var option = $('<option>').text(name.trim()).val(id);
                option.prop('selected', true);
                selectElement.append(option);
            });


            $("#OTCsubmit").text("Update");


        }

    });
}
function MEdityoga(Id) {
    debugger;
    var MPopup = {
        P_Dml_Indicator: "OTLM",
        id: Id,
        Schedule_Type: 8
    };

    $.ajax({
        type: "POST",
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(MPopup),
        success: function (data) {
            var data1 = JSON.parse(data);
            var MPopup = data1.data.Table[0];
            debugger;

            $("#txt_service_name").val(MPopup.Service_n);
            $('#personname').val(MPopup.Multi_Person_Name);
            /* $("#txtPaitentSearch_bill").val(MPopup.Patient_n).attr('readonly', true);*/
            $("#txtPaitentSearch_bill").val(MPopup.Patient_n).prop('disabled', true);
            $("#room").val(MPopup.Room_n);
            $("#date").val(MPopup.fromDate);
            $("#to_date").val(MPopup.toDate);
            $('#time').val(MPopup.fromTime);
            $('#endtime').val(MPopup.toTime);
            $('#txt_DMO').val(MPopup.dmo_name);
            $('#remarks').val(MPopup.Remarks);
            //$("#to_date").closest('.form-group').hide();
            $(".to_dateCls").hide();
            $("#ot_Branch").val(MPopup.branch_id);
            $("#hdnEditId").val(Id);
            $("#hdroom_id").val(MPopup.Room_no);
            $("#hdserve_id").val(MPopup.Service_Name);
            $("#hdpat_id").val(MPopup.Patient_Name);
            $("#Hdndoctor_id").val(MPopup.Person_Name);
            $("#Hdn_user_id").val(MPopup.DMO);
            var selectElement = $('#personname');

            var therapistNames = MPopup.Multi_Person_Name.split(',');
            var therapistIds = MPopup.Person_Name.split(',').map(function (item) {
                return item.trim().split(':')[0];
            });
            $('#personname').empty();
            therapistNames.forEach(function (name, index) {
                var id = therapistIds[index];
                var option = $('<option>').text(name.trim()).val(id);
                option.prop('selected', true);
                selectElement.append(option);
            });


            $("#OTCsubmit").text("Update");


        }

    });
}


$('#docname').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HDL", branch_id: $('#ot_Branch').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, id: item.doctorid };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#Hdndoctor_id').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

$('#bookingpop').on('hidden.bs.modal', function () {
    $('#txt_service_name').val("");
    $('#ot_Branch').val(0);
    $('#docname').val("");
    $('#personname').val(null).trigger('change');
    $('#txtPaitentSearch_bill').val("");
    $('#Hdn_user_id').val("");
    $('#txt_DMO').val("");
    $('#room').val("");
    $('#date').val("");
    $('#to_date').val("");
    $('#time').val("");
    $('#endtime').val("");
    $('#remarks').val("");
    $("#hdnEditId").val(null);
    $("#txt_Technician").val("");
    $("#OTCsubmit").text("Submit");
    $(".to_dateCls").show();
    $('#txtPaitentSearch_bill').prop('disabled', false);
    $('.modal-body').scrollTop(0);
});


$('#txt_service_name').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/ServiceNameAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTSN", branch_id: $('#ot_Branch').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data)
                response($.map(data2.data.Table, function (item) {
                    return { label: item.service_name, value: item.service_name, id: item.service_code, serviceid: item.master_service_id, department_id: item.department_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdserve_id').val(ui.item.id);
        $('#hdserveid').val(ui.item.serviceid);
        //loadTherapist(ui.item.serviceid);
        loadservicetime(ui.item.serviceid);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

function loadservicetime(serviceid) {
    var Therapist = {
        P_Dml_Indicator: 'ST',
        id: serviceid,
        branch_id: $('#ot_Branch').val()
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Therapist),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var tableData = data1.data.Table;
                if (jQuery.isEmptyObject(tableData)) {
                    // Handle case when data is empty
                    console.log("No data available");
                } else {
                    // Assuming you want the first item from the array
                    $('#hdnsertime').val(tableData[0].per_patient_time);
                }
            } else {
                console.log(data1);
            }
        }
    });
}



//function initializeAutocomplete(inputFieldId, autocompleteUrl) {
//    $('#' + inputFieldId).autocomplete({
//        source: function (request, response) {
//            $.ajax({
//                async: true,
//                url: autocompleteUrl,
//                type: "POST",
//                dataType: "json",
//                data: {
//                    Prefix: request.term,
//                    P_Dml_Indicator: "OTSN",
//                    branch_id: $('#HospitalBranchID').val()
//                },
//                success: function (data) {
//                    var parsedData = JSON.parse(data);
//                    response($.map(parsedData.data.Table, function (item) {
//                        return {
//                            label: item.service_name,
//                            value: item.service_name,
//                            id: item.service_code,
//                            serviceid: item.master_service_id,
//                            department_id: item.department_id
//                        };
//                    }));
//                }
//            });
//        },
//        minLength: 1,
//        select: function (event, ui) {
//            $('#hdserve_id').val(ui.item.id);
//            $('#hdserveid').val(ui.item.serviceid);
//        },
//        html: true,
//        open: function (event, ui) {
//            $(".ui-autocomplete").css("z-index", 1000);
//        }
//    });
//}


//initializeAutocomplete('txt_service_name', '/Calender/ServiceNameAutoCompletelist');





$('#SelDoctor').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HDL", branch_id: $('#HospitalBranchID').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, id: item.doctorid };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#Hdndoctor_id').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

//$('#personname').autocomplete({
//    source: function (request, response) {
//        $.ajax({
//            async: true,
//            url: "/Ipmanagement/DoctorNameAutoCompletelist",
//            type: "POST",
//            dataType: "json",
//            data: { Prefix: request.term, Dml_Indicator: "HUSEL", branch_id: $('#HospitalBranchID').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, id: item.doctorid };
//                }))
//            }
//        })
//    },
//    minLength: 1,
//    select: function (event, ui) {
//        $('#Hdndoctor_id').val(ui.item.id);
//    },
//    html: true,
//    open: function (event, ui) {
//        $(".ui-autocomplete").css("z-index", 1000);

//    }
//});

$('#room').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/RoomAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTR", branch_id: $('#ot_Branch').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data)
                response($.map(data2.data.Table, function (item) {
                    return { label: item.ward_name, value: item.ward_name, id: item.roomid };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdroom_id').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

$('#surgeryname').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/SurgeryAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTSUR", branch_id: $('#HospitalBranchID').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data)
                response($.map(data2.data.Table, function (item) {
                    return { label: item.ip_operation_name, value: item.ip_operation_name, id: item.ip_operation_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdsur_id').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

$('#txtPaitentSearch_bill').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/PatientAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTP", branch_id: $('#ot_Branch').val(), Patient_Name: $('#txtPaitentSearch_bill').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data);
                response($.map(data2.data.Table, function (item) {
                    return { label: item.first_name + '/' + item.patient_id + '/' + item.phone_number, value: item.first_name, id: item.patient_id };
                }));
            }
        });
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdpat_id').val(ui.item.id);
        $('#HdnVisitId').val(ui.item.VisitReportId);
        $('#HdnPatientId').val(ui.item.patientid);
        $(this).prop('disabled', true);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
    }
});



//$('#OTroom').autocomplete({
//    source: function (request, response) {
//        $.ajax({
//            async: true,
//            url: '/Calender/RoomAutoCompletelist',
//            type: "POST",
//            dataType: "json",
//            data: { Prefix: request.term, P_Dml_Indicator: "OTWR", branch_id: $('#dd_Branch').val() },
//            success: function (data) {
//                debugger;
//                var data2 = JSON.parse(data)
//                response($.map(data2.data.Table, function (item) {
//                    return { label: item.ward_name, value: item.ward_name, id: item.Room_No };
//                }))
//            }
//        })
//    },
//    minLength: 1,
//    select: function (event, ui) {
//        $('#hdroom_id').val(ui.item.id);
//    },
//    html: true,
//    open: function (event, ui) {
//        $(".ui-autocomplete").css("z-index", 1000);

//    }
//});
function initializeOTRoomDropdown() {
    $.ajax({
        async: true,
        url: '/Calender/RoomAutoCompletelist',
        type: "POST",
        dataType: "json",
        data: { P_Dml_Indicator: "OTWR", branch_id: $('#dd_Branch').val() },
        success: function (data) {
            var data2 = JSON.parse(data);
            var dropdown = $('#OTroom');
            dropdown.empty();
            dropdown.append('<option value="">--Select Theatre--</option>');
            $.each(data2.data.Table, function (index, item) {
                dropdown.append($('<option></option>').attr('value', item.Room_No).text(item.ward_name));
            });


            var roomNameFromServer = data2.data.Table[0].Room_name;


            dropdown.val(roomNameFromServer);
        }
    });

    $('#OTroom').change(function () {
        var selectedOption = $(this).find('option:selected');
        $('#hdroom_id').val(selectedOption.val());
    });
}

initializeOTRoomDropdown();

debugger;
$('#PaitentSearch').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/PatAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTPID", branch_id: $('#dd_Branch').val(), Patient_Name: $('#PaitentSearch').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data);
                response($.map(data2.data.Table, function (item) {
                    return { label: item.first_name + '/' + item.patient_id + '/' + item.phone_number, value: item.first_name, id: item.patient_id, patientid: item.patientid, VisitReportId: item.visit_reportid, VisitReport_Id: item.visit_report_id };
                }));
            }
        });
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdpat_id').val(ui.item.id);
        $('#HdnVisitId').val(ui.item.VisitReportId);
        $('#HdnPatientId').val(ui.item.patientid);
        PatientSearch(ui.item.id, "2", $('#dd_Branch').val(), ui.item.VisitReport_Id);
        Load_OTSurgery(ui.item.VisitReportId);
        $(this).prop('disabled', true);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
    }
});
/*ForFilter*/
//function initializeAutocomplete(id) {
//    $('#' + id).autocomplete({
//        source: function (request, response) {
//            $.ajax({
//                async: true,
//                url: '/Calender/PatientAutoCompletelist',
//                type: "POST",
//                dataType: "json",
//                data: { Prefix: request.term, P_Dml_Indicator: "OTP", branch_id: $('#HospitalBranchID').val() },
//                success: function (data) {
//                    debugger;
//                    var data2 = JSON.parse(data);

//                    var filteredData = data2.data.Table.filter(function (item) {
//                        return item.name !== null;
//                    });
//                    response($.map(filteredData, function (item) {
//                        return { label: item.name, value: item.name, id: item.patient_id };
//                    }));
//                }
//            });
//        },
//        minLength: 1,
//        select: function (event, ui) {
//            $('#hdpat_id').val(ui.item.id);
//        },
//        html: true,
//        open: function (event, ui) {
//            $(".ui-autocomplete").css("z-index", 1000);
//        }
//    });
//}

//// Call function for multiple IDs
//$(document).ready(function () {
//    var ids = ['daycarepat', 'massagepatlist']; 
//    ids.forEach(function (id) {
//        initializeAutocomplete(id);
//    });
//});


//For Filter
$('#daycarepat').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/PatientAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTP", branch_id: $('#HospitalBranchID').val(), Patient_Name: $('#daycarepat').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data);
                response($.map(data2.data.Table, function (item) {
                    return { label: item.first_name + '/' + item.patient_id + '/' + item.phone_number, value: item.first_name, id: item.patient_id };
                }));
            }
        });
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdpat_id').val(ui.item.id);
        $('#HdnVisitId').val(ui.item.VisitReportId);
        $('#HdnPatientId').val(ui.item.patientid);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
    }
});

$('#massagepatlist').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/PatientAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTP", branch_id: $('#HospitalBranchID').val(), Patient_Name: $('#massagepatlist').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data);
                response($.map(data2.data.Table, function (item) {
                    return { label: item.first_name + '/' + item.patient_id + '/' + item.phone_number, value: item.first_name, id: item.patient_id };
                }));
            }
        });
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdpat_id').val(ui.item.id);
        $('#HdnVisitId').val(ui.item.VisitReportId);
        $('#HdnPatientId').val(ui.item.patientid);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
    }
});

$('#selectservice').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/ServiceNameAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTSN", branch_id: $('#HospitalBranchID').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data)
                response($.map(data2.data.Table, function (item) {
                    return { label: item.service_name, value: item.service_name, id: item.service_code };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdserve_id').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

function initializeAutocomplete1(id) {
    $('#' + id).autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: '/Calender/ServiceNameAutoCompletelist',
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term, P_Dml_Indicator: "OTSN", branch_id: $('#HospitalBranchID').val() },
                success: function (data) {
                    debugger;
                    var data2 = JSON.parse(data)
                    response($.map(data2.data.Table, function (item) {
                        return { label: item.service_name, value: item.service_name, id: item.service_code };
                    }))
                }
            })
        },
        minLength: 1,
        select: function (event, ui) {
            $('#hdserve_id').val(ui.item.id);
        },
        html: true,
        open: function (event, ui) {
            $(".ui-autocomplete").css("z-index", 1000);

        }
    });
}

// Call the function for multiple IDs
$(document).ready(function () {
    var ids = ['DcareService', 'MService', 'TechnicianService']; // Add more IDs as needed
    ids.forEach(function (id) {
        initializeAutocomplete1(id);
    });
});


$('#docname_1').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HDL", branch_id: $('#HospitalBranchID').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, id: item.doctorid };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#Hdndoctor_id').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});
$('#SurgeryName_1').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/SurgeryAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTSUR", branch_id: $('#HospitalBranchID').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data)
                response($.map(data2.data.Table, function (item) {
                    return { label: item.ip_operation_name, value: item.ip_operation_name, id: item.ip_operation_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdsur_id').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

function loadWardName() {
    debugger;
    var ward = {
        P_Dml_Indicator: 'WRD'
    }
    debugger;
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(ward),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data.Table;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    $('#ddTblSelectType').empty();
                    $('#nurses_ward').empty();
                    $('#wards_ward').empty();

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

                    for (var i = 0; i < data1.length; i++) {
                        trs = trs + '<option value="' + data1[i].wardid + '">' + data1[i].ward_name + '</option>';
                    }
                    $('#ddTblSelectType').append(defaultoption + trs);
                    $('#nurses_ward').append(defaultoption + trs);
                    $('#wards_ward').append(defaultoption + trs);

                    $('#Hdnward_id').val(data1[i].wardid);
                }

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

    });
}

//Filter Clear
$('#btnOTclear').click(function () {
    $('#docname_1').val('');
    $('#Hdndoctor_id').val('');
    $('#dis_from').val('');
    $('#dis_to').val('');
    $('#ddTblSelectType').val(0);
    $('#SurgeryName_1').val('');
    $('#hdsur_id').val('');
    $('#Hdndoctor_id').val('');
    LoadOperationTheatre();

})

$('#btnDCclear').click(function () {

    $('#dis_from_1').val('');
    $('#dis_to_1').val('');
    $('#daycarepat').val('');
    $('#DcareService').val('');
    $('#hdpat_id').val('');
    $('#hdserve_id').val('');
    LoadDayCare();

})
$('#btnMclear').click(function () {

    $('#dis_from_2').val('');
    $('#dis_to_2').val('');
    $('#massagepatlist').val('');
    $('#MService').val('');
    $('#hdpat_id').val('');
    $('#hdserve_id').val('');
    LoadMassage();

})
$('#btnhcclear').click(function () {

    $('#dis_from_3').val('');
    $('#dis_to_3').val('');
    LoadDiffDate();

})



//Schedule Booking Details
function Schedule_BookingDetails(id) {
    debugger;
    $("#bookingheading").text('Booking Detail');
    $('#reschedule').show();
    $('#HdnSchedule_id').val(id);

    var OTdata = {
        P_Dml_Indicator: "SOTBD",
        id: id
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTdata),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            data1 = data1.data;
            $('#Sche_Patient_id').html('');
            $('#Sche_Patient_name').html('');
            $('#Schedule_Service').html('');

            $('#PDoctorName').html('');
            $('#PRoom_Name').html('');
            $('#PDate').html('');
            if (data1.Table.length > 0) {
                $('#US_BranchName').html(data1.Table[0].branch_name);
                $('#Sche_Patient_id').html('Patient Id : ' + data1.Table[0].patient_id);
                $('#Sche_Patient_name').html('Patient Name : ' + data1.Table[0].patient_name);
                $('#Schedule_Service').html('Service Name : ' + data1.Table[0].Service);
                $('#PDoctorName').html(data1.Table[0].Schedule_DoctorName);
                $('#PRoom_Name').html(data1.Table[0].Room_name);
                $('#PDate').html(data1.Table[0].ScheduleDate + ' ' + data1.Table[0].ScheduleTime);
                $('#US_Starttime').html('Start Time : ' + data1.Table[0].fromTime);
                $('#US_Endtime').html('End Time : ' + data1.Table[0].toTime);

                if (data1.Table[0].Schedule_Type == 1) {
                    $('#US_DMOName').hide();
                    $('#PRoom_Name').show();
                }
                else if (data1.Table[0].Schedule_Type == 4) {
                    $('#US_DMOName').show();
                    $('#PRoom_Name').hide();
                    $('#US_DMOName').html('Technician : ' + data1.Table[0].dmo_name);
                }
                else {
                    $('#US_DMOName').show();
                    $('#PRoom_Name').show();
                    $('#US_DMOName').html('DMO : ' + data1.Table[0].dmo_name);
                }


            }

        }
    });
}

//Cancell Schedule Booking Details
function Cancell_ScheduleBooking() {
    debugger;
    var OTdata = {
        P_Dml_Indicator: "CSBRU",
        id: $('#HdnSchedule_id').val(),
        Remarks: $('#txt_SchRemarks').val()
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTdata),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            data1 = data1.data;
            if (data1.Table.length > 0) {

                toastr.success("Booking Cancel Successfully");
                $('#HdnSchedule_id').val('');
                $('#txt_SchRemarks').val('');
                $("#eventreschedulepopup").modal('hide');

                /*calendarJs();*/
            }

        }
    });
}

$('#btnhcSubmit').click(function () {
    debugger;
    var fromDate = $("#dis_from_3").val();
    var toDate = $("#dis_to_3").val();

    var newfromdate = "";
    var newtodate = "";

    if (fromDate.trim() === "") {
        newfromdate = "";
    } else {
        var fromDatesplit = fromDate.split('/');
        newfromdate = fromDatesplit[2] + '-' + fromDatesplit[1] + '-' + fromDatesplit[0];
    }

    if (toDate.trim() === "") {
        newtodate = "";
    } else {
        var toDatesplit = toDate.split('/');
        newtodate = toDatesplit[2] + '-' + toDatesplit[1] + '-' + toDatesplit[0];
    }

    LoadDiffDate(newfromdate, newtodate);
});

function LoadDiffDate(fromDate, toDate) {
    debugger;
    var REM = {
        P_Dml_Indicator: "OPPS",
        fromDate: fromDate,
        toDate: toDate,
        Schedule_Type: 1
    };
    debugger;
    $.ajax({
        type: "POST",
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(REM),
        success: function (data) {
            var OTlist = JSON.parse(data);
            $('#hrsdifftbl_body').empty();
            $('#hrsdifftbl').dataTable().fnClearTable();
            $('#hrsdifftbl').dataTable().fnDraw();
            $('#hrsdifftbl').dataTable().fnDestroy();
            if (OTlist && OTlist.data && OTlist.data.Table) {
                OTlist = OTlist.data.Table;
                for (var i = 0; i < OTlist.length; i++) {
                    var row = "<tr id='row_" + (i + 1) + "'>" +
                        "<td>" + (i + 1) + "</td>" +
                        "<td style='display:none;' id='OTid_" + (i + 1) + "'>" + OTlist[i].id + "</td>" +
                        "<td id='Surgery_Name_" + (i + 1) + "'>" + OTlist[i].Surgery_Name + "</td>" +
                        "<td data-id=" + OTlist[i].Surgeon_Name + " id=Surgeon_Name__" + (i + 1) + ">" + OTlist[i].Surgeon + "</td>" +
                        //"<td id='CSSD__Kit_" + (i + 1) + "'>" + OTlist[i].CSSD_Kit + "</td>" +
                        "<td data--id=" + OTlist[i].Patient_Name + " id=Patient__" + (i + 1) + ">" + OTlist[i].Patientid + "</td>" +
                        "<td data--id=" + OTlist[i].Room_no + " id=Room_no__" + (i + 1) + ">" + OTlist[i].Room_name + "</td>" +
                        "<td id='Expected_Date__" + (i + 1) + "'>" + OTlist[i].fromDate + "</td>" +
                        /*"<td id='To__Date" + (i + 1) + "'>" + OTlist[i].To_Date + "</td>" +*/
                        "<td id='Expected_Time__" + (i + 1) + "'>" + OTlist[i].fromTime + "</td>" +
                        "<td id='ot_schedule_date__" + (i + 1) + "'>" + OTlist[i].ot_schedule_date + "</td>" +
                        "<td id='pre_otchecklist_date_" + (i + 1) + "'>" + OTlist[i].pre_otchecklist_date + "</td>" +
                        "<td id='post_otchecklist_date_" + (i + 1) + "'>" + OTlist[i].post_otchecklist_date + "</td>" +
                        "<td id='schedule_status_" + (i + 1) + "'>" + OTlist[i].schedule_status + "</td>" +
                        "<td id='Diffdate_" + (i + 1) + "'>" + OTlist[i].Diffdate + "</td>" +
                        /*"<td class='tbl-action'>" +*/
                        "</td>" +
                        "</tr>";

                    $("#hrsdifftbl_body").append(row);
                }
                datatable('hrsdifftbl', 'Lab__setup', 'Legal');
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

//Equipmet autocomplete-Added by Tharuni
$('#equipment').autocomplete({

    source: function (request, response) {
        debugger;
        $.ajax({
            async: true,
            url: '/Calender/AutoCompleteService',
            type: "POST",
            dataType: "json",
            data: { ServiceName: $('#equipment').val(), flag: 1, DmlIndicator: 'AS' },
            success: function (data) {
                $('#hserviceid1').val(0)
                data = JSON.parse(data);
                console.log(data);
                response($.map(data.Table, function (item) {
                    return { label: item.service_name, value: item.service_name, id: item.master_service_id };
                }))

            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hserviceid1').val(ui.item.id);
        $('#hserviceidname1').val(ui.item.value);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }

});
//Bloodcomponene Autocomplete-Added by Tharuni
$('#bloodcomponent').autocomplete({

    source: function (request, response) {
        debugger;
        $.ajax({
            async: true,
            url: '/Calender/AutoCompleteService',
            type: "POST",
            dataType: "json",
            data: { ServiceName: $('#bloodcomponent').val(), flag: 2, DmlIndicator: 'AS' },
            success: function (data) {
                debugger;
                $('#hserviceid2').val(0)
                data = JSON.parse(data);
                console.log(data);
                response($.map(data.Table, function (item) {
                    return { label: item.service_name, value: item.service_name, id: item.master_service_id };
                }))

            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hserviceid2').val(ui.item.id);
        $('#hserviceidname2').val(ui.item.value);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }

});
//Equipment Service Add
//$('#addEquipment').click(function () {
//    var equipment = $('#equipment').val();
//    var quantity = $('#eqpqty').val();

//    if ($('#equipment').val() == '') {
//        $('#Pequipment').show().fadeOut(8000).html('Select Equipment Name').val(0).focus();
//        return false;
//    }

//    if ($('#eqpqty').val() == '') {
//        $('#Peqpqty').show().fadeOut(8000).html('Enter Quantity').val('').focus();
//        return false;
//    }

//    var rowcount = $('#equipmentdetails_table > tbody > tr').length;
//    var sno = rowcount + 1;

//    var value = "<tr class='tr_input number' data-id='" + rowcount + "' id='eqp_td_" + rowcount + "'><td>" + sno + "</td><input type='hidden' id='EquipmentDetails_id_" + rowcount + "' value='0'><td id='eqp_tdEntityName_" + rowcount + "' data-id=" + $('#hserviceid1').val() + ">" + equipment + "</td><td id='eqp_tdSMCode_" + rowcount + "'>" + quantity + "</td><td><button class='btn-xs btn btn-delete btn-delete-equipment-row' data-id=" + rowcount + " onclick='EquipmentDelete(\"" + rowcount + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

//    $('#equipmentdetails_table > tbody').append(value);
//    $('#equipment').val('');
//    $('#eqpqty').val('');
//});

$('#addEquipment').click(function () {
    var equipment = $('#equipment').val();
    var quantity = $('#eqpqty').val();

    if ($('#equipment').val() == '') {
        $('#Pequipment').show().fadeOut(8000).html('Select Equipment Name').val(0).focus();
        return false;
    }
    var validEquipment = false;
    $(".ui-autocomplete li").each(function () {
        if ($(this).text().toLowerCase() === equipment.toLowerCase()) {
            validEquipment = true;
            return false;
        }
    });

    if (!validEquipment) {
        $('#Pequipment').show().fadeOut(8000).html('Select a valid Equipment Name').val(0).focus();
        return false;
    }

    if ($('#eqpqty').val() == '') {
        $('#Peqpqty').show().fadeOut(8000).html('Enter Quantity').val('').focus();
        return false;
    }

    var rowcount = $('#equipmentdetails_table > tbody > tr').length;
    var sno = rowcount + 1;

    var value = "<tr class='tr_input number' data-id='" + rowcount + "' id='eqp_td_" + rowcount + "'><td>" + sno + "</td><input type='hidden' id='EquipmentDetails_id_" + rowcount + "' value='0'><td id='eqp_tdEntityName_" + rowcount + "' data-id=" + $('#hserviceid1').val() + ">" + equipment + "</td><td id='eqp_tdSMCode_" + rowcount + "'>" + quantity + "</td><td><button class='btn-xs btn btn-delete btn-delete-equipment-row' data-id=" + rowcount + " onclick='EquipmentDelete(\"" + rowcount + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

    $('#equipmentdetails_table > tbody').append(value);
    $('#equipment').val('');
    $('#eqpqty').val('');
});


function EquipmentDelete(rowId) {

    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 Do You want Delete ?',
        {

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

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

                    var Detailid = $("#EquipmentDetails_id_" + rowId).val();
                    if (Detailid != "0") {

                        var Paymentvalues = {
                            P_Dml_Indicator: "EDEL",
                            id: Detailid

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


                                var data2 = JSON.parse(data);

                                if (jQuery.isEmptyObject((data2.data))) {

                                }
                                else {

                                    if (data2.msg == "Success") {

                                        toastr.success("Removed Successfully");
                                        $('#eqp_td_' + rowId).remove();
                                        $('#equipmentdetails_table > tbody > tr').each(function (index) {
                                            $(this).find('td:first').text(index + 1);
                                        });
                                    }
                                }
                            }
                        });

                    }

                    else {

                        $('#eqp_td_' + rowId).remove();
                        $('#equipmentdetails_table > tbody > tr').each(function (index) {
                            $(this).find('td:first').text(index + 1);
                        });
                        toastr.success("Removed Successfully");

                    }
                });
            }
        });
}

//Service Add
$('#addBlood').click(function () {
    var bloodComponent = $('#bloodcomponent').val();
    var bloodQty = $('#bloodqty').val();
    var bloodRemarks = $('#bloodreqremarks').val();

    if ($('#bloodqty').val() == '') {
        $('#Pbloodqty').show().fadeOut(8000).html('Select Blood qty').val(0).focus();
        return false;
    }

    if ($('#bloodcomponent').val() == '') {
        $('#Pbloodcomponent').show().fadeOut(8000).html('Select Blood Component').val(0).focus();
        return false;
    }

    var validBloodComponent = false;
    $(".ui-autocomplete li").each(function () {
        if ($(this).text().toLowerCase() === bloodComponent.toLowerCase()) {
            validBloodComponent = true;
            return false;
        }
    });

    if (!validBloodComponent) {
        $('#Pbloodcomponent').show().fadeOut(8000).html('Select a valid Blood Component').val(0).focus();
        return false;
    }

    if ($('#bloodreqremarks').val() == '') {
        $('#Pbloodreqremarks').show().fadeOut(8000).html('Enter Blood Remarks').val(0).focus();
        return false;
    }

    var rowcount = $('#blooddetails_table > tbody > tr').length;
    var sno = rowcount + 1;
    var value = "<tr class='tr_input number' data-id='" + rowcount + "' id='td_1" + rowcount + "'><td>" + sno + "</td><input type='hidden' id='BloodDetails_id_" + rowcount + "' value='0'><td id='tdEntity_" + rowcount + "'>" + bloodComponent + "</td><td id='tdSM_" + rowcount + "' data-id=" + $('#hserviceid2').val() + ">" + bloodQty + "</td><td id='tdbb_" + rowcount + "'>" + bloodRemarks + "</td><td><button class='btn-xs btn btn-delete btn-delete-blood-row' data-id=" + rowcount + " onclick='BloodDelete(\"" + rowcount + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
    $('#blooddetails_table > tbody').append(value);
    $('#bloodqty').val('');
    $('#bloodcomponent').val('');
    $('#bloodreqremarks').val('');
});

//$(document).on('click', '.btn-delete-blood-row', function () {
//    deleteBloodRow($(this).data('id'));
//});

//function deleteBloodRow(rowId) {
//    $('#td_1' + rowId).remove();
//    $('#blooddetails_table > tbody > tr').each(function (index) {
//        $(this).find('td:first').text(index + 1);
//    });
//}

function BloodDelete(rowId) {

    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 Do You want Delete ?',
        {

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

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

                    var Detailid = $("#BloodDetails_id_" + rowId).val();
                    if (Detailid != "0") {

                        var Paymentvalues = {
                            P_Dml_Indicator: "EDEL",
                            id: Detailid

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


                                var data2 = JSON.parse(data);

                                if (jQuery.isEmptyObject((data2.data))) {

                                }
                                else {

                                    if (data2.msg == "Success") {

                                        toastr.success("Removed Successfully");
                                        $('#td_1' + rowId).remove();
                                        $('#blooddetails_table > tbody > tr').each(function (index) {
                                            $(this).find('td:first').text(index + 1);
                                        });
                                    }
                                }
                            }
                        });

                    }

                    else {

                        $('#td_1' + rowId).remove();
                        $('#blooddetails_table > tbody > tr').each(function (index) {
                            $(this).find('td:first').text(index + 1);
                        });
                        toastr.success("Removed Successfully");

                    }
                });
            }
        });
}

$('#reschedule').click(function () {
    debugger;
    var id = $('#HdnSchedule_id').val();
    if (parseInt($('#HdnTabId').val()) === 1) {
        OTEdit(id);
    } else if (parseInt($('#HdnTabId').val()) === 2) {
        DCEdit(id);
    } else if (parseInt($('#HdnTabId').val()) === 3) {
        MEdit(id);
    }
});


function loadTherapist(serviceid) {
    debugger;
    var Therapist = {
        P_Dml_Indicator: 'BRU',
        id: serviceid,
        branch_id: $('#ot_Branch').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Therapist),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data.Table;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {

                    $('#personname').empty();
                    trs = '';
                    var defaultoption = '<option value="0">--Select--</option>';
                    console.log(data1);
                    for (var i = 0; i < data1.length; i++) {
                        trs = trs + '<option value="' + data1[i].individual_id + '">' + data1[i].Doctor + '</option>';

                    }
                    $('#personname').append(defaultoption + trs);
                    $('#hdndoc_Id').val(data1[i].ward_id);
                }

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

    });
}

//Loard Branch 
function LoadBranch() {
    var subdepartment = {
        Dml_Indicator: "LBRAN",
        name: $('#HiddenDoctorID').val()
    };
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            var data1 = JSON.parse(data);
            $('#dd_Branch').empty();
            $('#ot_Branch').empty();
            $('#wards_branch').empty();
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject(data1)) {
                    // Handle if data1 is empty
                } else {
                    var Branch = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        Branch += '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    $('#dd_Branch').append(default_opt + Branch);
                    $('#ot_Branch').append(default_opt + Branch);
                    $('#wards_branch').append(default_opt + Branch);


                    // Enable event handler for branch selection
                    $('#dd_Branch, #ot_Branch').change(function () {
                        var selectedBranchId = $(this).val();
                        if (selectedBranchId !== '0') {
                            loadDMO(selectedBranchId);
                        } else {
                            $('#txt_DMO').autocomplete('close');
                        }
                    });

                    // If role is not 2, automatically select the branch
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#dd_Branch').val($('#HospitalBranchID').val()).change();
                        $('#dd_Branch').attr('disabled', true);
                        $('#ot_Branch').val($('#HospitalBranchID').val()).change();
                        $('#ot_Branch').attr('disabled', true);
                        $('#wards_branch').val($('#HospitalBranchID').val()).change();
                        $('#wards_branch').attr('disabled', true);
                    }
                }
            } else {
                console.log(data1);
            }
        }
    });
}
$('#ot_Branch').change(function () {
    $('#txt_service_name').val('');
    $('#txt_DMO').val('');
    $('#docname').val('');
    $('#personname').val(null).trigger('change');
    $('#txtPaitentSearch_bill').val('');
    $('#hdpat_id').val('');
    $('#HdnVisitId').val('');
    $('#HdnPatientId').val('');
    $('#txtPaitentSearch_bill').prop('disabled', false);
});

$('#dd_Branch').change(function () {
    //Load_OTSurgery();
    Load_SurgeonDoctor();
    Load_AssSurgeonDoctor();
    Load_Anaesthesian();
    $('#PaitentSearch').val('');
    $('#surgeryname').empty();
    $('#PaitentSearch').prop('disabled', false);

})

//Loard Surgery
function Load_OTSurgery(visit_reportid) {
    var selectedSurgeryNames = $('#surgeryname').val();

    var Warddata = {
        Dml_Indicator: "SPOP",
        branchid: $('#dd_Branch').val(),
        surgery_request_id: visit_reportid
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/AdmitPatient_Ins_Upd_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Warddata),
        success: function (data) {
            $('#surgeryname').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            } else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var operation = '';

                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        operation += '<option value="' + emp.ip_operation_id + '">' + emp.ip_operation_name + '</option>';
                    });
                    $('#surgeryname').append(default_opt + operation);


                    $('#surgeryname').val(selectedSurgeryNames);
                } else {
                    console.log(data);
                }
            }
        }
    });
}
function Clear_OTFields() {

    $('#surgeryname').val("").change();
    //$('#SelDoctor').val("");
    $('#PaitentSearch').val("");
    //$('#txt_AssSurgeonName').val("");
    //$('#txt_AnaesthesianName').val("");
    $('#OTroom').val("");
    $("#expdate").val("");
    $('#exptime').val("");
    $('#txt_ExpToTime').val("");
    $("#hdnEditId").val("");
    $("#OTsubmit").text("Submit");
    $('#txt_AnaesthesianName').val("").change();
    $('#txt_AssSurgeonName').val("").change();
    $('#SelDoctor').val("").change();

}

//Assistant Surgeon Name Autiocomplete
$('#txt_AssSurgeonName').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HDL", branch_id: $('#dd_Branch').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, id: item.doctor_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#HdnAss_surgeonid').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

function loadDMO(branchId) {
    $('#txt_DMO').autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/Ipmanagement/DoctorNameAutoCompletelist",
                type: "POST",
                dataType: "json",
                data: {
                    Prefix: request.term,
                    Dml_Indicator: "HUSEL",
                    branch_id: branchId
                },
                success: function (data) {
                    var data2 = data;
                    response($.map(data2, function (item) {
                        return { label: item.doctorname, value: item.doctorname, id: item.doctorid };
                    }));
                }
            });
        },
        minLength: 1,
        select: function (event, ui) {
            $('#Hdn_user_id').val(ui.item.id);
        },
        html: true,
        open: function (event, ui) {
            $(".ui-autocomplete").css("z-index", 1000);
        }
    });
}



//Anaesthesian Name Autiocomplete
$('#txt_AnaesthesianName').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HDL", branch_id: $('#dd_Branch').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, id: item.doctor_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#HdnAnaesthesian_id').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

$("#OTsubmit").click(function () {
    debugger;
    OTsubmit();
});

$('#dd_shedule').change(function () {
    OTEdit($('#dd_shedule').val());
});

function Load_SurgeonDoctor(Surgeon_Name) {
    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#dd_Branch').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);
            $('#SelDoctor').empty();
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var tr = '';
                    var Doctor = '';

                    var default_opt = '<option value="">--Select--</option>';
                    var j = 0;
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            j++;
                            Doctor = Doctor + '<option value="' + data1[i].doctor_id + '">' + data1[i].first_name + '</option>';
                        }
                        $('#SelDoctor').html(default_opt + Doctor);
                    }

                    if (Surgeon_Name != '' && Surgeon_Name != null) {
                        $('#SelDoctor').val(Surgeon_Name.split(','));
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function Load_AssSurgeonDoctor(assistant_surgeon) {
    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#dd_Branch').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);
            $('#txt_AssSurgeonName').empty();
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var tr = '';
                    var Doctor = '';

                    var default_opt = '<option value="">--Select--</option>';
                    var j = 0;
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            j++;
                            Doctor = Doctor + '<option value="' + data1[i].doctor_id + '">' + data1[i].first_name + '</option>';
                        }
                        $('#txt_AssSurgeonName').html(default_opt + Doctor);
                    }

                    if (assistant_surgeon != '' && assistant_surgeon != null) {
                        $('#txt_AssSurgeonName').val(assistant_surgeon.split(','));
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function Load_Anaesthesian(anaesthesian) {
    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#dd_Branch').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);
            $('#txt_AnaesthesianName').empty();
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var tr = '';
                    var Doctor = '';

                    var default_opt = '<option value="">--Select--</option>';
                    var j = 0;
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            j++;
                            Doctor = Doctor + '<option value="' + data1[i].doctor_id + '">' + data1[i].first_name + '</option>';
                        }
                        $('#txt_AnaesthesianName').html(default_opt + Doctor);
                    }

                    if (anaesthesian != '' && anaesthesian != null) {
                        $('#txt_AnaesthesianName').val(anaesthesian.split(','));
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

//Doctor Appointment Details
function Doctor_AppointmentDetails(id) {

    var OTdata = {
        P_Dml_Indicator: "DAPL",
        id: id
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTdata),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            data1 = data1.data;
            if (data1.Table.length > 0) {

                $('#App_Patient_id').html('Patient Id : ' + data1.Table[0].patient_id);
                $('#App_Patient_name').html('Patient Name : ' + data1.Table[0].patient_name);
                $('#App_DoctorName').html('Doctor : ' + data1.Table[0].DoctorName);
                $('#App_Date').html(data1.Table[0].appointment_date);

            }

        }
    });
}

//WorkOrder Schedule Details
function WorkOrderSchedule_Details(id) {

    var OTdata = {
        P_Dml_Indicator: "WOSDL",
        id: id
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(OTdata),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            data1 = data1.data;
            if (data1.Table.length > 0) {

                $('#WO_Patient_id').html('Patient Id : ' + data1.Table[0].patient_id);
                $('#WO_Patient_name').html('Patient Name : ' + data1.Table[0].PatientName);
                $('#WO_ServiceName').html('Service : ' + data1.Table[0].service_name);
                $('#WO_DoctorName').html('Service Provider : ' + data1.Table[0].serviceprovider_name);
                $('#WO_Date').html(data1.Table[0].scheduledate + ' ' + data1.Table[0].scheduletime);

            }

        }
    });
}

$('#txt_Technician').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: {
                Prefix: request.term,
                Dml_Indicator: "HTEC",
                branch_id: $('#ot_Branch').val()
            },
            success: function (data) {
                debugger;
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname, id: item.doctorid, dataid: item.doctor_user_id };
                }));
            }
        });
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#Hdn_user_id1').val(ui.item.id);
        $('#Hdata_id').val(ui.item.dataid);

    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
    }
});
$('#personname').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: {
                Prefix: request.term,
                Dml_Indicator: "HTEC",
                branch_id: $('#ot_Branch').val()
            },
            success: function (data) {
                debugger;
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname, id: item.doctorid, dataid: item.doctor_user_id };
                }));
            }
        });
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#Hdn_user_id1').val(ui.item.id);
        $('#Hdata_id').val(ui.item.dataid);
        if ($('#date').val()) {
            AddAppiontment();  
        }
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
    }
});

$('#BtnTecClear').click(function () {

    $('#TecFrom').val('');
    $('#TecTo').val('');
    $('#TechnicianPatList').val('');

    $('#TechnicianService').val('');
    $('#hdpat_id').val('');
    $('#hdserve_id').val('');
    LoadTechnician();

})

$('#BtnTecSubmit').click(function () {
    debugger;
    var fromDate = $("#TecFrom").val();
    var toDate = $("#TecTo").val();

    var newfromdate = "";
    var newtodate = "";

    if (fromDate.trim() === "") {
        newfromdate = "";
    } else {
        var fromDatesplit = fromDate.split('/');
        newfromdate = fromDatesplit[2] + '-' + fromDatesplit[1] + '-' + fromDatesplit[0];
    }

    if (toDate.trim() === "") {
        newtodate = "";
    } else {
        var toDatesplit = toDate.split('/');
        newtodate = toDatesplit[2] + '-' + toDatesplit[1] + '-' + toDatesplit[0];
    }

    var patientName = $("#hdpat_id").val();
    var serviceName = $("#hdserve_id").val();
    var patientNameValue = $("#TechnicianPatList").val();
    if (patientNameValue == "") {
        patientName = "";
    }

    var serviceNameValue = $("#TechnicianService").val();
    if (serviceNameValue == "") {
        serviceName = "";
    }

    LoadTechnician(newfromdate, newtodate, patientName, serviceName);
});

function LoadTechnician(fromDate, toDate, patientName, serviceName) {
    debugger;
    var MPopup = {
        P_Dml_Indicator: "TECS",
        fromDate: fromDate,
        toDate: toDate,
        Patient_name: patientName,
        Service_Name: serviceName,
        Schedule_Type: 4
    };

    $.ajax({
        type: "POST",
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(MPopup),
        success: function (data) {
            var Mlistpopup = JSON.parse(data).data.Table;

            $('#Technicianbody').empty();
            $('#Technician_table').dataTable().fnClearTable();
            $('#Technician_table').dataTable().fnDraw();
            $('#Technician_table').dataTable().fnDestroy();

            if (Mlistpopup && Mlistpopup.length > 0) {
                for (var i = 0; i < Mlistpopup.length; i++) {
                    var row = "<tr id='row_" + (i + 1) + "'>" +
                        "<td>" + (i + 1) + "</td>" +
                        "<td style='display:none;' id='Mid_" + (i + 1) + "'>" + Mlistpopup[i].id + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Service_Name + " id=MService_name_" + (i + 1) + ">" + Mlistpopup[i].Service_n + "</td>" +
                        "<td data-id=" + Mlistpopup[i].DMO + " id=dmo" + (i + 1) + ">" + Mlistpopup[i].dmo_name + "</td>" +
                        "<td data-id=" + Mlistpopup[i].Patient_Name + " id=MPatientName_" + (i + 1) + ">" + Mlistpopup[i].Patient_n + "</td>" +
                        "<td id='MDate_" + (i + 1) + "'>" + Mlistpopup[i].fromDate + "</td>" +
                        "<td id='MTime_" + (i + 1) + "'>" + Mlistpopup[i].fromTime + "</td>" +
                        "<td id='MendTime_" + (i + 1) + "'>" + Mlistpopup[i].toTime + "</td>" +
                        "<td class='tbl-action'>" +
                        "<button class='btn btn-sm btn-primary btn-edit' data-id='" + Mlistpopup[i].id + "' title='Edit' data-heading='Technician' onclick='TechnicianEdit(" + Mlistpopup[i].id + ")'data-toggle='modal' data-target='#bookingpop'><i class='fa fa-pencil fa-xs'></i></button>&nbsp;" +
                        "<button class='btn btn-sm btn-danger btn-delete' data-id='" + Mlistpopup[i].id + "' title='Delete' onclick='TechnicianDelete(" + Mlistpopup[i].id + ")'><i class='fas fa-trash-alt fa-xs'></i></button>" +
                        "</td>" +
                        "</tr>";

                    $("#Technicianbody").append(row);
                }
                datatable('Technician_table', 'Lab_set', 'Legal');
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function TechnicianEdit(Id) {
    debugger;
    var MPopup = {
        P_Dml_Indicator: "TECED",
        id: Id,
        Schedule_Type: 4
    };

    $.ajax({
        type: "POST",
        url: '/Calender/OTList',
        contentType: 'application/json',
        data: JSON.stringify(MPopup),
        success: function (data) {
            var data1 = JSON.parse(data);
            var MPopup = data1.data.Table[0];
            debugger;

            $("#txt_service_name").val(MPopup.Service_n);
            $("#txtPaitentSearch_bill").val(MPopup.Patient_n).prop('disabled', true);
            $("#date").val(MPopup.fromDate);
            $("#to_date").val(MPopup.toDate);
            $('#time').val(MPopup.fromTime);
            $('#endtime').val(MPopup.toTime);
            $('#txt_Technician').val(MPopup.dmo_name);
            $('#remarks').val(MPopup.Remarks);
            $(".to_dateCls").hide();
            $("#ot_Branch").val(MPopup.branch_id);
            $("#hdnEditId").val(Id);
            $("#hdserve_id").val(MPopup.Service_Name);
            $("#hdpat_id").val(MPopup.Patient_Name);
            $("#Hdn_user_id").val(MPopup.DMO);

            $("#OTCsubmit").text("Update");


        }

    });
}

function TechnicianDelete(id) {
    debugger;

    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 want to delete?', {
        closeButton: true,
        progressBar: true,
        allowHtml: true,
        timeOut: 20000000,

        onShown: function (toast) {
            $("#confirmationRevertYes").click(function () {
                var Mdel = {
                    P_Dml_Indicator: "OTD",
                    id: id
                };

                $.ajax({
                    type: "POST",
                    url: '/Calender/OTList',
                    data: Mdel,
                    success: function (response) {
                        console.log(response);

                        toastr.success('Delete successfully');
                        LoadTechnician();
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });

            $("#confirmationRevertNo").click(function () {
                // Handle No button click if needed
            });
        }
    });
}

$('#TechnicianPatList').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/PatientAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTP", branch_id: $('#HospitalBranchID').val(), Patient_Name: $('#TechnicianPatList').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data);
                response($.map(data2.data.Table, function (item) {
                    return { label: item.first_name + '/' + item.patient_id + '/' + item.phone_number, value: item.first_name, id: item.patient_id };
                }));
            }
        });
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdpat_id').val(ui.item.id);
        $('#HdnVisitId').val(ui.item.VisitReportId);
        $('#HdnPatientId').val(ui.item.patientid);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
    }
});




//--------------- Ward popup start-----------------
//patient name autocomplete
$('#wards_patname').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/PatientAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTP", branch_id: $('#wards_branch').val(), Patient_Name: $('#wards_patname').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data);
                response($.map(data2.data.Table, function (item) {
                    return { label: item.first_name + '/' + item.patient_id + '/' + item.phone_number, value: item.first_name, id: item.patient_id };
                }));
            }
        });
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdpat_id').val(ui.item.id);
        $('#HdnVisitId').val(ui.item.VisitReportId);
        $('#HdnPatientId').val(ui.item.patientid);
        $(this).prop('disabled', true);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
    }
});

//Rooms type dropdown
function LoadRoomstype() {
    var Warddata = {
        Dml_Indicator: "ROOM",
        hospital_id: $('#HospitalId').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/WardManagement_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Warddata),
        success: function (data) {
            $('#wards_roomtype').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var Section;
                    $('#wards_roomtype').empty();
                    $('#nurses_room').empty();

                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {

                        Section = Section + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';

                    });
                    $('#wards_roomtype').append(default_opt + Section);
                    $('#nurses_room').append(default_opt + Section);

                    if ($('#HWardID').val() != '') {
                        $('#wards_roomtype').val($('#Hdnroomid').val());
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

// ward save function
$('#btn_wardsave').click(function () {
    debugger;
    if ($.trim($('#wards_branch').val()) == 0) {
        $('#Pwards_branch').show();
        $('#Pwards_branch').fadeOut(8000);
        $('#Pwards_branch').html('Select Branch');
        $('#wards_branch').focus();
        $('#wards_branch').val(0);
        return false;
    }

    if ($.trim($('#wards_ward').val()) == "") {
        $('#Pwards_ward').show();
        $('#Pwards_ward').fadeOut(8000);
        $('#Pwards_ward').html('Select the Ward');
        $('#wards_ward').focus();
        $('#wards_ward').val('');
        return false;
    }

    if ($.trim($('#wards_roomtype').val()) == 0) {
        $('#Pwards_roomtype').show();
        $('#Pwards_roomtype').fadeOut(8000);
        $('#Pwards_roomtype').html('Select Room Type');
        $('#wards_roomtype').focus();
        $('#wards_roomtype').val(0);
        return false;
    }

    if ($.trim($('#wards_patname').val()) == "") {
        $('#Pwards_patname').show();
        $('#Pwards_patname').fadeOut(8000);
        $('#Pwards_patname').html('Choose The Patient Name');
        $('#wards_patname').focus();
        $('#wards_patname').val('');
        return false;
    }

    if ($.trim($("#ward_from_date").val()).length == "") {
        $('#Pward_from_date').show();
        $('#Pward_from_date').fadeOut(8000);
        $('#Pward_from_date').html('Select From Date');
        $("#ward_from_date").focus();
        $("#ward_from_date").val('');
        return false;
    }
    if ($.trim($("#ward_to_date").val()).length == "") {
        $('#Pward_to_date').show();
        $('#Pward_to_date').fadeOut(8000);
        $('#Pward_to_date').html('Select To Date');
        $("#ward_to_date").focus();
        $("#ward_to_date").val('');
        return false;
    }

    var selected_from_WardDate = null, selected_to_wardDate = null;
    if ($("#ward_from_date").val() != '') {
        var date1 = $("#ward_from_date").val().split('/');
        selected_from_WardDate = date1[2] + '-' + date1[1] + '-' + date1[0];
    }
    if ($("#ward_to_date").val() != '') {
        var date2 = $("#ward_to_date").val().split('/');
        selected_to_wardDate = date2[2] + '-' + date2[1] + '-' + date2[0]
    }
    var id = $("#hdnEditWardId").val().trim();

    var Warddatas = {
        P_Dml_Indicator: (id && id !== "0") ? "OTWU" : "OTWI",
        id: id,
        branch_id: $('#wards_branch').val(),
        ward_id: $('#wards_ward').val(),
        Room_No: $('#wards_roomtype').val(),
        Patient_Name: $('#hdpat_id').val(),
        fromDate: selected_from_WardDate,
        toDate: selected_to_wardDate,
        remarks: $('#ward_remarks').val(),
        Schedule_Type: 6
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Warddatas),
        success: function (data) {
            const data2 = JSON.parse(data);
            if (data2.msg === "Success") {
                debugger;
                const msg = data2.data.Table[0].msg;
                if (msg === "Inserted" || msg === "Updated") {
                    toastr.success(`Ward Details ${msg === "Inserted" ? 'Added' : 'Updated'} Successfully`);
                    clearWard_data();

                    const currentPage = window.location.pathname;
                    const elementClass = currentPage === '/calender/Index' ? 'col-md-6 col-sm-6 col-xs-12' : 'col-md-3 col-sm-3 col-xs-12';
                    $('.columnclass').attr('class', elementClass);

                    if (currentPage !== '/calender/Index') {
                        window.location.reload();
                    }

                    $('#wardpop').modal('hide');
                } else {
                    toastr.error('Something Went Wrong');
                }
            }
        },
        error: function () {
            toastr.error('Something Went Wrong');
        }
    });
});;

function clearWard_data() {
    $('#wards_branch').val("0"),
        $('#wards_ward').val("0"),
        $('#wards_roomtype').val("0"),
        $('#wards_patname').val("0"),
        $('#HWardID').val(""),
        $('#ward_remarks').val("")

}

$('#showcalward').click(function () {
    debugger;
    loadwarddata();
});

function loadwarddata() {
    debugger;
    var values = {
        P_Dml_Indicator: "SWD",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    $('#wardlistbody').empty();
                    $('#wardlist').dataTable().fnClearTable();
                    $('#wardlist').dataTable().fnDraw();
                    $('#wardlist').dataTable().fnDestroy();

                    var j = 0, b = '', tr = '', edit = '', del = '', other_info = '';

                    b = data1;
                    $.each(b.Table, function (i, emp) {
                        j++
                        edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="" data-type="role_rights_edit" data-nav="" data-name=""  href="javascript:void(0);" onclick=wardDataEdit("' + emp.id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        del = ' <a  data-toggle="tooltip" title="Delete"  id="warddel_' + emp.id + '" class="btn deleteicon-btn btn-xs"  data-id="" data-type="role_rights_delete" data-nav="sp_delete" data-name=""  href="javascript:void(0);" onclick=wardDataDelete("' + emp.id + '","DE")><i class="fa fa-trash" aria-hidden="true"></i></a>';

                        other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + ' ' + '</div></div>';

                        tr = tr + '<tr id="' + j + '"><td>' + j + '</td><td style="display:none;" class="hidden">' + emp.id + '</td><td>' + emp.ward_name + '</td><td>' + emp.room_name + '</td><td>' + emp.patientName + '</td><td>' + emp.fromDate + '</td><td>' + emp.toDate + '</td><td>' + other_info + '</td></tr>';

                    });
                    $('#wardlistbody').html(tr);
                    datatable('wardlist', 'ward_list', 'Legal');
                }
            }
            else {
                console.log(data);
            }
        }
    });

}

function wardDataEdit(id) {
    debugger;
    $('#wardpop').modal('toggle');
    $('#hdnEditWardId').val(id)
    var Edit = {
        id: id,
        Schedule_Type: 6,
        P_Dml_Indicator: "EWD"
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Edit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data.Table;

            $("#wards_branch").val(emp[0].branch_id);
            $("#wards_ward").val(emp[0].ward_id);
            $("#wards_roomtype").val(emp[0].Room_no);
            $("#wards_patname").val(emp[0].ward_patient_name);
            $("#ward_remarks").val(emp[0].remarks);
            $("#ward_from_date").val(emp[0].fromDate);
            $("#ward_to_date").val(emp[0].toDate);
            $("#hdnEditWardId").val(emp[0].id);
            $('#btn_wardsave').html('Update');

        }
    })
}


function wardDataDelete(id) {
    debugger;
    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 want to delete?', {
        closeButton: true,
        progressBar: true,
        allowHtml: true,
        timeOut: 20000000,

        onShown: function (toast) {
            $("#confirmationRevertYes").click(function () {
                var Mdel = {
                    P_Dml_Indicator: "OTWDD",
                    id: id
                };
                $.ajax({
                    type: "POST",
                    url: '/Calender/OTCreation',
                    data: Mdel,
                    success: function (response) {
                        console.log(response);

                        toastr.success('Delete successfully');
                        loadwarddata();
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });
            $("#confirmationRevertNo").click(function () {
                // Handle No button click if needed
            });
        }
    });
}


//----------------Nurse assigning-------------
//Nurse name autocomplete
$('#nurses_nursename').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/NurseAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "NNA", Patient_Name: $('#nurses_nursename').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data);
                response($.map(data2.data.Table, function (item) {
                    return { label: item.nursename + '/' + item.individual_id + '/', value: item.nursename, id: item.individual_id };
                    id: item.individual_id
                }));
            }
        });
    },
    minLength: 1,
    select: function (event, ui) {
        console.log("Selected item:", ui.item);
        $('#hdnurse_id').val(ui.item.id);
        $('#HidnnurseId').val(ui.item.individual_id);
        $(this).prop('disabled', true);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
    }
});


//patient name autocomplete
$('#nurses_patname').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Calender/PatientAutoCompletelist',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, P_Dml_Indicator: "OTP", Patient_Name: $('#nurses_patname').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data);
                response($.map(data2.data.Table, function (item) {
                    return { label: item.first_name + '/' + item.patient_id + '/' + item.phone_number, value: item.first_name, id: item.patient_id };
                }));
            }
        });
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdNpat_id').val(ui.item.id);
        $('#HdnNVisitId').val(ui.item.VisitReportId);
        $('#HdnNPatientId').val(ui.item.patient_id);
        $(this).prop('disabled', true);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
    }
});

//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=" + $("#HospitalBranchID1").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
                        };
                    }));
                }
            });
        },
        minLength: 1,
        select: function (event, ui) {
            console.log("Selected item:", ui.item);
            $('#hmedicineid1').val(ui.item.id);
            $('#hmedicineidname1').val(ui.item.value);
        },
        html: true,
        open: function (event, ui) {
            $(".ui-autocomplete").css("z-index", 1000);
        }
    });

});

//medication add function
$('#nurses_medication_add').click(function () {
    debugger;
    var medicine_name = $('#nurses_medicationname').val();
    var instructions = $('#nurses_instructions').val();
    var dosage = $('#nurses_dosage').val();
    var frequency = $('#nurses_frequency').val();
    // var route = $('#nurses_route').val();
    var duration = $('#nurses_duration').val();


    var instructionsText = $('#nurses_instructions option:selected').text();
    var dosageText = $('#nurses_dosage option:selected').text();
    var frequencyText = $('#nurses_frequency option:selected').text();
    //var routeText = $('#nurses_route option:selected').text();

    if ($('#nurses_medicationname').val() == '') {
        $('#Pnurses_medicationname').show().fadeOut(8000).html('Select Medication').val(0).focus();
        return false;
    }

    if ($('#nurses_instructions').val() == '') {
        $('#Pnurses_instructions').show().fadeOut(8000).html('Select Instruction').val(0).focus();
        return false;
    }
    if ($('#nurses_dosage').val() == '') {
        $('#Pnurses_dosage').show().fadeOut(8000).html('Select Dosage').val(0).focus();
        return false;
    }
    if ($('#nurses_frequency').val() == '') {
        $('#Pnurses_frequency').show().fadeOut(8000).html('Select Frequency').val(0).focus();
        return false;
    }
    //if ($('#nurses_route').val() == '') {
    //    $('#Pnurses_route').show().fadeOut(8000).html('Select Route').val(0).focus();
    //    return false;
    //}

    var rowcount = $('#medicationdetails_table > tbody > tr').length;
    var sno = rowcount + 1;

    var value = "<tr class='tr_input number' data-id='" + rowcount + "' id='medi_td_" + rowcount + "'><td>" + sno + "</td><input type='hidden' id='mediactionDetails_id_" + rowcount + "' value='0'><td id='medi_tdName_" + rowcount + "' data-id=" + $('#hmedicineid1').val() + ">" + medicine_name + "</td><td id='medi_tdInstructions_" + rowcount + "' data-id='" + instructions + "'>" + instructionsText + "</td><td id='medi_tdDosage_" + rowcount + "' data-id='" + dosage + "'>" + dosageText + "</td><td id='medi_tdFrequency_" + rowcount + "' data-id='" + frequency + "'>" + frequencyText + "</td><td id='medi_tdDuration_" + rowcount + "'>" + duration + "</td><td><button class='btn-xs btn btn-delete btn-delete-equipment-row' data-id=" + rowcount + " onclick='medicationDelete(\"" + rowcount + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

    $('#medicationdetails_table > tbody').append(value);
    $('#nurses_medicationname').val('');
    $('#nurses_instructions').val('0');
    $('#nurses_dosage').val('0');
    $('#nurses_frequency').val('0');
    // $('#nurses_route').val('0');
    $('#nurses_duration').val('')
});

// nurse tab save function
$('#nursesothers_submit').click(function () {
    debugger;
    if ($.trim($('#nurses_nursename').val()) == 0) {
        $('#Pnurses_nursename').show();
        $('#Pnurses_nursename').fadeOut(8000);
        $('#Pnurses_nursename').html('Choose the Nurse');
        $('#nurses_nursename').focus();
        $('#nurses_nursename').val(0);
        return false;
    }

    if ($.trim($('#nurses_patname').val()) == "") {
        $('#Pnurses_patname').show();
        $('#Pnurses_patname').fadeOut(8000);
        $('#Pnurses_patname').html('Choose the Patient');
        $('#nurses_patname').focus();
        $('#nurses_patname').val('');
        return false;
    }

    if ($.trim($('#nurses_ward').val()) == 0) {
        $('#Pnurses_ward').show();
        $('#Pnurses_ward').fadeOut(8000);
        $('#Pnurses_ward').html('Select Ward');
        $('#nurses_ward').focus();
        $('#nurses_ward').val(0);
        return false;
    }

    if ($.trim($('#nurses_floor').val()) == "") {
        $('#Pnurses_floor').show();
        $('#Pnurses_floor').fadeOut(8000);
        $('#Pnurses_floor').html('Select Floor');
        $('#nurses_floor').focus();
        $('#nurses_floor').val('');
        return false;
    }
    if ($.trim($('#nurses_room').val()) == "") {
        $('#Pnurses_room').show();
        $('#Pnurses_room').fadeOut(8000);
        $('#Pnurses_room').html('Select Room');
        $('#nurses_room').focus();
        $('#nurses_room').val('');
        return false;
    }

    if ($.trim($("#nurses_from_date").val()).length == "") {
        $('#Pnurses_from_date').show();
        $('#Pnurses_from_date').fadeOut(8000);
        $('#Pnurses_from_date').html('Select From Date');
        $("#nurses_from_date").focus();
        $("#nurses_from_date").val('');
        return false;
    }
    if ($.trim($("#nurses_to_date").val()).length == "") {
        $('#Pnurses_to_date').show();
        $('#Pnurses_to_date').fadeOut(8000);
        $('#Pnurses_to_date').html('Select To Date');
        $("#nurses_to_date").focus();
        $("#nurses_to_date").val('');
        return false;
    }

    var selected_from_nurseDate = null, selected_to_nurseDate = null;
    if ($("#nurses_from_date").val() != '') {
        var date1 = $("#nurses_from_date").val().split('/');
        selected_from_nurseDate = date1[2] + '-' + date1[1] + '-' + date1[0];
    }
    if ($("#nurses_to_date").val() != '') {
        var date2 = $("#nurses_to_date").val().split('/');
        selected_to_nurseDate = date2[2] + '-' + date2[1] + '-' + date2[0]
    }

    //var selectedTime = $("#nursesothers_time").val();
    //var Exp_selectedTime = moment(selectedTime, 'hh:mm A').format('HH:mm');

    var selectedTime = $("#nursesothers_time").val();
    var Exp_selectedTime = "";
    if ($.trim(selectedTime) != "") {
        Exp_selectedTime = moment(selectedTime, 'hh:mm A').format('HH:mm');
        if (!Exp_selectedTime) {
            $('#Pnursesothers_time').show();
            $('#Pnursesothers_time').fadeOut(8000);
            $('#Pnursesothers_time').html('Invalid Time');
            $("#nursesothers_time").focus();
            return false;
        }
    }

    var id = $("#hdnEditNurseId").val();

    var nursedatas = {
        P_Dml_Indicator: (id && id !== "0") ? "OTNU" : "OTNI",
        id: id,
        nurse_id: $('#hdnurse_id').val(),
        ward_id: $('#nurses_ward').val(),
        floor_id: $('#nurses_floor').val(),
        Room_No: $('#nurses_room').val(),
        Patient_Name: $('#hdNpat_id').val(),
        fromDate: selected_from_nurseDate,
        toDate: selected_to_nurseDate,
        worktype: $('#nursesothers_worktype').val(),
        fromTime: Exp_selectedTime,
        Schedule_Type: 5
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(nursedatas),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (data2.msg == "Success") {
                debugger;
                if (data2.data.Table[0].msg == "Inserted" || data2.data.Table[0].msg == "Updated") {
                    let medicationlen = $('#medicationdetails_table>tbody>tr').length;
                    let medicationArr = new Array();
                    for (let i = 0; i < medicationlen; i++) {
                        let obj = {};
                        obj.id = $('#mediactionDetails_id_' + i).val();
                        obj.medicationid = $('#medi_tdName_' + i).attr('data-id');
                        obj.medicine_name = $('#medi_tdName_' + i).text();
                        obj.instructions = $('#medi_tdInstructions_' + i).attr('data-id');
                        obj.dosage = $('#medi_tdDosage_' + i).attr('data-id');
                        obj.frequency = $('#medi_tdFrequency_' + i).attr('data-id');
                        //obj.route = $('#medi_tdRoute_' + i).attr('data-id');
                        obj.duration = $('#medi_tdDuration_' + i).text();
                        obj.patient_id = $('#hdNpat_id').val();
                        obj.UserCreatedBy = $('#hiddenUser_id').val();
                        obj.status = 1;
                        obj.DmlIndicator = 'MAD';
                        medicationArr.push(obj);
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/Calender/CreateMedicationDetails',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(medicationArr),
                        success: function (data) {
                            $('#medicationdetails_table tbody').empty();
                            toastr.success($('#nursesothers_submit').html() === 'Schedule Update' ? 'Updated Successfully' : 'Added Successfully');
                            clearNurse_data();
                            $('#nursepop').modal('hide');
                        },
                        error: function () {
                            toastr.error('Something Went Wrong');
                        }
                    });
                } else {
                    toastr.error('Something Went Wrong');
                }
            }
        },
        error: function () {
            toastr.error('Something Went Wrong');
        }
    });
});



function clearNurse_data() {
    debugger;
    $('#nurses_ward').val("0"),
        $('#nurses_floor').val("0"),
        $('#nurses_room').val("0"),
        $('#nurses_patname').val(""),
        $('#nurses_nursename').val(""),
        $('#nurses_from_date').val(''),
        $('#nurses_to_date').val(''),
        $('nursesothers_time').val("")

}

$('#showcalnurse').click(function () {
    debugger;
    LoadNurseDetails();
});

function LoadNurseDetails() {
    debugger;
    $('#shade_slot').show();
    var Nursedata = {
        P_Dml_Indicator: "SND",
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Nursedata),
        success: function (data) {
            debugger;
            console.log(data);
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    $('#nurselistbody').empty();
                    $('#nurselist').dataTable().fnClearTable();
                    $('#nurselist').dataTable().fnDraw();
                    $('#nurselist').dataTable().fnDestroy();
                    var j = 0, b = '', row_data = '', edit = '', del = '', other_info = '';
                    b = data1;
                    $.each(b.Table, function (i, emp) {
                        j++
                        edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="" data-type="role_rights_edit" data-nav="" data-name="" href="javascript:void(0);" onclick="nurseDataEdit(\'' + emp.id + '\', \'' + emp.Patient_Name + '\')"><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        del = ' <a  data-toggle="tooltip" title="Delete"  id="nursedatadel_' + emp.id + '" class="btn deleteicon-btn btn-xs"  data-id="" data-type="role_rights_delete" data-nav="" data-name=""  href="javascript:void(0);" onclick=NurseDataDelete("' + emp.id + '","DE")><i class="fa fa-trash" aria-hidden="true"></i></a>';
                        other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + ' ' + '</div></div>';


                        row_data = row_data + '<tr id="' + j + '"><td>' + j + '</td><td style="display:none;" class="hidden">' + emp.id + '</td><td>' + emp.nursename + '</td><td>' + emp.patientName + '</td><td>' + emp.ward_name + '</td><td>' + emp.Floor + '</td><td>' + emp.room_name + '</td><td>' + emp.fromDate + '</td><td>' + emp.toDate + '</td><td>' + other_info + '</td></tr>';

                    });
                    $('#nurselistbody').html(row_data);
                    datatable('nurselist', 'nurse_list', 'Legal');
                }
            }
            else {
                console.log(data);
            }
        }
    });

}


function nurseDataEdit(id, Patient_Name) {
    debugger;
    $('#nursepop').modal('toggle');
    $('#hdnEditNurseId').val(id);
    $('#hdNpat_id').val(Patient_Name);
    var val = {
        P_Dml_Indicator: "END",
        id: id,
        Schedule_Type: 5,
        patient_id: Patient_Name
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json',
        data: JSON.stringify(val),
        success: function (data) {
            var nurselist = JSON.parse(data);
            var otm = nurselist.data.Table1;
            $('#medicationdetails_table tbody').empty();
            if (otm.length > 0) {

                for (var i = 0; i < otm.length; i++) {
                    var row = "<tr class='tr_input number' data-id='" + i + "' id='medi_td_" + i + "'>" +
                        "<td>" + (i + 1) + "</td><input type='hidden' id='mediactionDetails_id_" + i + "' value='" + otm[i].medicinedetailsid + "'>" +
                        "<td id='medi_tdName_" + i + "' data-id=" + otm[i].medicationid + ">" + otm[i].medicine_name + "</td>" +
                        "<td id='medi_tdInstructions_" + i + "' data-id=" + otm[i].instructions + ">" + otm[i].instructions1 + "</td>" +
                        "<td id='medi_tdDosage_" + i + "' data-id=" + otm[i].dosage + ">" + otm[i].dosage1 + "</td>" +
                        "<td id='medi_tdFrequency_" + i + "' data-id=" + otm[i].frequency + ">" + otm[i].frequency1 + "</td>" +
                        //"<td id='medi_tdRoute_" + i + "'>" + otm[i].route + "</td>" +
                        "<td id='medi_tdDuration_" + i + "'>" + otm[i].duration + "</td>" +
                        "<td><button class='btn-xs btn btn-delete btn-delete-medication-row' data-id=" + i + " onclick='medicationDelete(\"" + i + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td>" +
                        "</tr>";
                    $("#medicationdetails_table").append(row);
                }
            }
            var valofnursse = JSON.parse(data).data.Table[0];
            $("#hdnEditNurseId").val(id);
            $("#nurses_nursename").val(valofnursse.nursename);
            $("#nurses_patname").val(valofnursse.nurse_patient_name);
            $("#nurses_ward").val(valofnursse.ward_id);
            $("#nurses_floor").val(valofnursse.floor_id);
            $("#nurses_room").val(valofnursse.Room_no);
            $("#nurses_from_date").val(valofnursse.fromDate);
            $("#nurses_to_date").val(valofnursse.toDate);
            $('#nursesothers_time').val(valofnursse.fromtime);
            $('#nursesothers_worktype').val(valofnursse.worktype);

            $("#nursesothers_submit").html("Schedule Update");
        }
    });
}


function medicationDelete(rowId) {
    debugger;
    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 Do You want Delete ?',
        {
            closeButton: true,
            progressBar: true,
            allowHtml: true,
            timeOut: 20000000,
            onShown: function (toast) {
                $("#confirmationRevertYes").click(function () {
                    var Detailid = $("#mediactionDetails_id_" + rowId).val();
                    if (Detailid != "0") {

                        var Paymentvalues = {
                            P_Dml_Indicator: "MEDID",
                            id: Detailid
                        }
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/Calender/OTCreation',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(Paymentvalues),
                            success: function (data) {
                                var data2 = JSON.parse(data);
                                if (jQuery.isEmptyObject((data2.data))) {
                                }
                                else {
                                    if (data2.msg == "Success") {
                                        toastr.success("Removed Successfully");
                                        $('#medi_td_' + rowId).remove();
                                        $('#medicationdetails_table > tbody > tr').each(function (index) {
                                            $(this).find('td:first').text(index + 1);
                                        });
                                    }
                                }
                            }
                        });
                    }
                    else {
                        $('#medi_td_' + rowId).remove();
                        $('#medicationdetails_table > tbody > tr').each(function (index) {
                            $(this).find('td:first').text(index + 1);
                        });
                        toastr.success("Removed Successfully");

                    }
                });
            }
        });
}


function NurseDataDelete(id) {
    debugger;
    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 want to delete?', {
        closeButton: true,
        progressBar: true,
        allowHtml: true,
        timeOut: 20000000,

        onShown: function (toast) {
            $("#confirmationRevertYes").click(function () {
                var Mdel = {
                    P_Dml_Indicator: "NDD",
                    id: id
                };
                $.ajax({
                    type: "POST",
                    url: '/Calender/OTCreation',
                    data: Mdel,
                    success: function (response) {
                        console.log(response);

                        toastr.success('Delete successfully');
                        LoadNurseDetails();
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });
            $("#confirmationRevertNo").click(function () {
                // Handle No button click if needed
            });
        }
    });
}


//added by nandhini for dhanwanthralaya req
//schedule request tab -----start

$('#schedule_request_tab').click(function () {
    LoadScheduleRequestDetails();

});

$('#btnScheduleReqSubmit').click(function () {
    LoadScheduleRequestDetails();
});

$('#btnScheduleReqclear').click(function () {
    $('#schedulereq_fromdate').val('');
    $('#schedulereq_todate').val('');
    LoadScheduleRequestDetails();
})

function LoadScheduleRequestDetails() {

    var newfromdate = "";
    var newtodate = "";

    var fromDate = $('#schedulereq_fromdate').val();
    var toDate = $('#schedulereq_todate').val();

    if (fromDate.trim() === "") {
        newfromdate = "";
    } else {
        var fromDatesplit = fromDate.split('/');
        newfromdate = fromDatesplit[2] + '-' + fromDatesplit[1] + '-' + fromDatesplit[0];
    }

    if (toDate.trim() === "") {
        newtodate = "";
    } else {
        var toDatesplit = toDate.split('/');
        newtodate = toDatesplit[2] + '-' + toDatesplit[1] + '-' + toDatesplit[0];
    }

    var paramList = {
        DmlIndicator: 'S',
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#hiddenRole_id').val() != 2 ? $('#HospitalBranchID').val() : "0",
        from_date: newfromdate,
        to_date: newtodate
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/Schedule_Request_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(paramList),
        success: function (data) {

            $('#scheduleRequestList_tbody').empty();
            $('#tblscheduleRequestList').dataTable().fnClearTable();
            $('#tblscheduleRequestList').dataTable().fnDraw();
            $('#tblscheduleRequestList').dataTable().fnDestroy();


            $('#scheduleRequestList_IP_tbody').empty();
            $('#tblscheduleRequestList_IP').dataTable().fnClearTable();
            $('#tblscheduleRequestList_IP').dataTable().fnDraw();
            $('#tblscheduleRequestList_IP').dataTable().fnDestroy();

            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    data2 = data2.data.Table;
                    if (data2.length > 0) {
                        var tr = ''; var iptr = '';
                        $.each(data2, function (i, emp) {

                            if (emp.visit_type == null || emp.visit_type == "" || emp.visit_type == "1") {
                                var del = '<button class="btn btn-sm btn-danger btn-delete" title="Delete" onclick="ScheduleRequestDelete(' + emp.schedule_request_id + ')"><i class="fas fa-trash-alt fa-xs"></i></button>';

                                var book = '<a class="btn btn-xs btn-primaryuse" title="Book Schedule" data-toggle="modal" data-target="#bookingpop" data-heading="massage" onclick=\'BookSchedule(\"' + emp.schedule_request_id + '\",\"' + emp.patient_id + '\",\"' + emp.patientid + '\",\"' + emp.first_name + '\",\"' + emp.service_name + '\",\"' + emp.service_id + '\",\"' + emp.branch_id + '\",\"' + emp.request_date_time + '\",\"' + emp.prefer_time + '\",\"' + emp.service_code + '\")\'>Book</a>';

                                //tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.first_name + '<span style="color: #999; font-size: 11px;">(' + emp.phone_number + ')</span></td><td>' + emp.service_name + '</td><td>' + emp.created_date + '</td><td>' + emp.request_date_time + '</td><td>' + emp.prefer_time + '</td><td>' + ((emp.request_status == "1" || emp.request_status == null) ? "Pending" : "Completed") + '</td><td>' + (emp.request_status == "2" ? "-" : (book + del)) + '</td></tr>';
                                tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.first_name + '<span style="color: #999; font-size: 11px;">(' + emp.phone_number + ')</span></td><td>' + emp.service_name + '</td><td>' + emp.created_date + '</td><td>' + emp.request_date_time + '</td><td>' + emp.prefer_time + '</td><td>' + ((emp.request_status == "1" || emp.request_status == null) ? "Pending" + (emp.bill_no != null ? " (Billed)" : "") : "Completed" + (emp.bill_no != null ? " (Billed)" : "")) + '</td><td>' + (emp.request_status == "2" ? "-" : (book + del)) + '</td></tr>';


                            }
                            else {
                                var del = '<button class="btn btn-sm btn-danger btn-delete" title="Delete" onclick="ScheduleRequestDelete(' + emp.schedule_request_id + ')"><i class="fas fa-trash-alt fa-xs"></i></button>';

                                var book = '<a class="btn btn-xs btn-primaryuse" title="Book Schedule" data-toggle="modal" data-target="#bookingpop" data-heading="massage" onclick=\'BookSchedule(\"' + emp.schedule_request_id + '\",\"' + emp.patient_id + '\",\"' + emp.patientid + '\",\"' + emp.first_name + '\",\"' + emp.service_name + '\",\"' + emp.service_id + '\",\"' + emp.branch_id + '\",\"' + emp.request_date_time + '\",\"' + emp.prefer_time + '\",\"' + emp.service_code+'\")\'>Book</a>';

                                iptr = iptr + '<tr><td>' + (i + 1) + '</td><td>' + emp.first_name + '<span style="color: #999; font-size: 11px;">(' + emp.phone_number + ')</span></td><td>' + emp.service_name + '</td><td>' + emp.created_date + '</td><td>' + emp.request_date_time + '</td><td>' + emp.prefer_time + '</td><td>' + ((emp.request_status == "1" || emp.request_status == null) ? "Pending" + (emp.bill_no != null ? "(Billed)" : "") : "Completed" + (emp.bill_no!=null?"(Billed)":"")) + '</td><td>' + (emp.request_status == "2" ? "-" : (book + del)) + '</td></tr>';

                            }
                        });

                        $('#scheduleRequestList_tbody').append(tr);
                        datatable('tblscheduleRequestList', 'ScheduleRequest', 'Legal');


                        $('#scheduleRequestList_IP_tbody').append(iptr);
                        datatable('tblscheduleRequestList_IP', 'ScheduleRequestIP', 'Legal');

                    }
                }
            }
        }
    });
}



function ScheduleRequestDelete(schedule_request_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 want to delete?', {
        closeButton: true,
        progressBar: true,
        allowHtml: true,
        timeOut: 20000000,

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

                var paramList = {
                    DmlIndicator: 'D',
                    schedule_request_id: schedule_request_id
                }
                $.ajax({
                    async: true,
                    type: 'POST',
                    url: '/Calender/Schedule_Request_Sel',
                    contentType: 'application/json; charset=UTF-8',
                    data: JSON.stringify(paramList),
                    success: function (data) {

                        var data2 = JSON.parse(data);
                        if (jQuery.isEmptyObject((data2.data))) {
                        }
                        else {
                            toastr.success("Deleted Successfully");
                            LoadScheduleRequestDetails();
                        }
                    }
                });
            });
        }
    })

}


function BookSchedule(schedule_request_id, patient_id, patientid, first_name, service_name, service_id, branch_id, request_date, prefer_time,service_code) {
    $('#HdnTabId').val(3);
    $('#hdnScheduleRequestId').val(schedule_request_id);
    $('#hdpat_id').val(patient_id);
    $('#HdnPatientId').val(patientid);
    $('#txtPaitentSearch_bill').val(first_name);
    $('#ot_Branch').val(branch_id);
    loadDMO(branch_id);
    $('#txt_service_name').val(service_name);
    $('#time').val(prefer_time);
    $('#date').val(request_date);
    $('#hdserve_id').val(service_code);
    $('#hdserveid').val(service_id);
    $('#tbl_consumables tbody').empty();
    loadTherapist(service_id);
    $('#store_name').attr('disabled', false);
    LoadStore();
}

function LoadStore(id) {
    debugger;
    var store = {
        Dml_Indicator: "LS",
        Hospital_id: $('#HospitalIdInt').val(),
        //branch_id: $('#ot_Branch').val(),
        branch_id: '69'  //--for demohms inventory mapping
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceStore',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(store),
        success: function (data) {
            debugger;
            $('#store_name').empty()
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.Id + '" data-id="' + emp.BranchId + '" data-mapid="' + emp.StoreBranchMapId + '">' + emp.Name + '</option>';
                    });
                    $('#store_name').append(default_opt + SubDepartment);
                    if (id != '') {
                        $('#store_name').val(id)
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#store_name').on('change', function () {

    LoadStoreCategory();
    LoadItemNameList();
});

function LoadStoreCategory() {
    var store = {
        Dml_Indicator: "LS",
        StoreId: $('#store_name').val(),
        branch_id: $('#store_name option:selected').attr('data-id')
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceStoreCategory',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(store),
        success: function (data) {
            debugger;
            $('#store_category').empty()
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.CategoryId + '">' + emp.CategoryName + '</option>';
                    });
                    $('#store_category').append(default_opt + SubDepartment);

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

//$('#store_category').on('change', function () {
//    LoadItemNameList();
//});

$('#store_category').on('change', function () {
    $('#HItem').val('');
    $('#HItemName').val('');
    $('#item_name').val('');
});

function LoadItemNameList() {
    $('#HItem').val('');
    $('#HItemName').val('');
    $('#item_name').val('');
    storeitemslistarray = [];
    var store = {
        Dml_Indicator: "LS",
        StoreId: $('#store_name').val(),
        master_category_id: $('#store_category').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ItemListByStoreCategory',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(store),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    storeitemslistarray = data1;

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


$('#item_name').on('focus', function () {
    console.log(storeitemslistarray);


    $(this).autocomplete({

        source: storeitemslistarray.map(item => item.Name),
        minLength: 1,
        select: function (event, ui) {
            debugger;
            itemId = storeitemslistarray.find(item => item.Name === ui.item.value).Id;
            itemname = storeitemslistarray.find(item => item.Name === ui.item.value).Name;

            $('#HItem').val(itemId);
            $('#HItemName').val(itemname);

        },
        html: true,
        open: function (event, ui) {
            $(".ui-autocomplete").css("z-index", 1000);

        }
    }).focus(function () {
        $(this).autocomplete("search");
    });

});

//$('#item_name').autocomplete({
//    source: function (request, response) {
//        debugger
//        $.ajax({
//            async: true,
//            url: '/Billing/AutoCompleteServicesItemList',
//            type: "POST",
//            dataType: "json",
//            data: { Prefix: request.term, Dml_Indicator: "H", FromStoreId: $('#store_name').val(), ToStoreId: 0, StoreType: 0, SupplierId: 0, ItemName: $('#item_name').val() },
//            success: function (data) {
//                debugger;
//                $('#HItem').val('')
//                $('#HItemName').val('')

//                var data2 = JSON.parse(data);
//                response($.map(data2.data, function (item) {
//                    return { label: item.Name, value: item.Name, id: item.Id, HSNName: item.HSNName, code: item.Code };
//                }))
//            }
//        })
//    },
//    minLength: 1,
//    select: function (event, ui) {
//        debugger;
//        $('#HItem').val(ui.item.id);
//        $('#HItemName').val(ui.item.value);

//    },
//    html: true,
//    open: function (event, ui) {
//        $(".ui-autocomplete").css("z-index", 1000);

//    }
//});


//Consumables add
$('#btn_consumables_Add').click(function () {
    debugger

    $('#store_name').attr('disabled', true);

    if ($('#item_name').val() == "" || $('#item_name').val() == 0) {
        $('#Pitem_name').show();
        $('#Pitem_name').fadeOut(8000);
        $('#Pitem_name').html('Please search');
        $('#Pitem_name').focus();
        $('#item_name').val('');
        return false;
    }
    if ($('#quantity').val() == "" || $('#quantity').val() == 0) {
        $('#Pquantity').show();
        $('#Pquantity').fadeOut(8000);
        $('#Pquantity').html('Please enter the quantity');
        $('#Pquantity').focus();
        $('#quantity').val('');
        return false;
    }


    else {
        if ($('#tbl_consumables tbody').length > 0) {
            var labid = $('#item_name').val();
            var arr = [];
            for (var i = 1; i <= $('#tbl_consumables>tbody>tr').length; i++) {
                var row = $('#con_name_' + i).text() + '_' + $('#Item_' + i).attr('data-id');
                arr.push(row)

                var combinedkey = labid + '_' + $('#Item_' + i).attr('data-id');

                if (row === combinedkey) {
                    // Update the quantity in the existing row
                    var newQuantity = parseInt($('#quantity').val(), 10);
                    var currentQuantity = parseInt($('#con_quan_' + i).text(), 10);
                    $('#con_quan_' + i).text(newQuantity);

                    // Reset input values
                    $('#item_name').val('');
                    $('#quantity').val('');
                    $('#item_name').attr('disabled', false);
                    $('#btn_consumables_Add').html('Add')

                    return false;
                }
            }

            if ($.inArray(combinedkey, arr) != -1) {
                $('#Pitem_name').show();
                $('#Pitem_name').fadeOut(8000);
                $('#Pitem_name').html('Selected Already');
                $('#Pitem_name').focus();
                $('#item_name').val(0);
                return false;
            }
        }
        var c = $('#tbl_consumables>tbody>tr').length

        var trow = '<tr id=Item_' + (c + 1) + ' data-id=' + $('#HItem').val() + '><td id=item_id_' + (c + 1) + '>' + $('#HItem').val() + '</td><td id=con_name_' + (c + 1) + '>' + $('#HItemName').val() + '</td><td id=con_quan_' + (c + 1) + '>' + $('#quantity').val() + '</td><td id=con_category_' + (c + 1) + '>' + $('#store_category :selected').text() + '</span></td><td><span class="btn deleteicon-btn btn-xs" onclick=consumables_chk(' + (c + 1) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span></td></tr>'
        $("#tbl_consumables tbody:last").append(trow);

        $('#item_name').val('');
        $('#quantity').val('');
        $('#store_category').val('');
        $('#item_name').attr('disabled', false);
        $('#btn_consumables_Add').html('Add')
    }
})

function consumables_chk(id, flag) {

    $('#Item_' + id).remove();

}
$('#date').change(function () {
    AddAppiontment()
});

function AddAppiontment() {
    debugger;
    var Dml_Indicator;
    var d = new Date();
    var strDate = (d.getDate() < 10 ? "0" + d.getDate() : d.getDate()) + "/" + ('0' + (d.getMonth() + 1)).slice(-2) + "/" + d.getFullYear();
    console.log('--------------->firstdate' + strDate);

    //if ($('#Hdndoc_id').val() == '') {
    //    if ($.trim($('#SelDoctor :selected').val()) == "" || $('#SelDoctor :selected').val() == "0") {
    //        $('#PSelDoctor').show();
    //        $('#PSelDoctor').fadeOut(8000);
    //        $('#PSelDoctor').html('Select Doctor');
    //        $('#SelDoctor').focus();
    //        $('#SelDoctor :selected').val('0');
    //        return false;
    //    }
    //}

    //if ($.trim($('#date').val()) == "") {
    //    $('#date').show();
    //    $('#date').fadeOut(8000);
    //    $('#Pstart_date').html('Select date');
    //    $('#start_date').focus();
    //    $('#start_date').val('');
    //    return false;
    //}


    Dml_Indicator = 'TASS';

    var start_date = $('#date').val();
    var FDate1 = start_date.split('/');
    start_date = FDate1[2] + "-" + FDate1[1] + "-" + FDate1[0]
    var start_date_check = new Date(start_date);
    var today_date = new Date();
    var AppointmentType = $.trim($('#AppointmentType').val());
    if (AppointmentType == 'Walk In' || AppointmentType == 'WalkIn') {
        AppointmentType = 1;
    }
    else if (AppointmentType == 'Video') {
        AppointmentType = 2;
    }
    else {
        AppointmentType = 3;
    }
    var AppiontmentData = {
        Schedule_date: start_date,
        doctor_id: $('#Hdn_user_id1').val(),
        Dml_Indicator: Dml_Indicator,
        //appointment_type: AppointmentType,
        hospital_id: $('#HospitalId').val(),
        branch_id: $("#ot_Branch").val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DirectPatientEnroll/DirectPatientAppointment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(AppiontmentData),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                $('#tblPatientAppiontment').empty();
                if (jQuery.isEmptyObject((data1))) {
                    //alert(' Sorry, The values you entered are invalid.\n Please try again. ');
                }
                if (data1.length > 0) {
                    var PatientAppiontment = '';
                    var hospital_id = '';
                    var branch_id = '';
                    var j = 1;
                    for (var i = 0; i < data1.length; i++) {
                        debugger;
                        if (i == 0) {
                            //PatientAppiontment = PatientAppiontment + '<div class="col-md-12"><h3>' + data1[i].hospital_name + ' | ' + data1[i].town_village + '</h3></div><div class="clearfix"></div>';
                            PatientAppiontment = PatientAppiontment + '<div class="col-md-12"><h3>' + data1[i].branch_name + '</h3></div><div class="clearfix"></div>';
                        }
                        else if (data1[i].hospital_id != hospital_id && data1[i].branch_id != branch_id) {
                            //PatientAppiontment = PatientAppiontment + '<div class="clearfix"></div><div class="col-md-12"><h3>' + data1[i].hospital_name + ' | ' + data1[i].town_village + '</h3></div><div class="clearfix"></div>';
                            PatientAppiontment = PatientAppiontment + '<div class="clearfix"></div><div class="col-md-12"><h3>' + data1[i].branch_name + '</h3></div><div class="clearfix"></div>';
                        }
                        else {
                        }
                        if ((data1[i].doctor_schedule_type == 1 || data1[i].doctor_schedule_type == 4 || data1[i].doctor_schedule_type == 5 || data1[i].doctor_schedule_type == 7 || data1[i].doctor_schedule_type == null)) {
                            PatientAppiontment = PatientAppiontment + '<div class="col-xs-6 col-sm-2 col-md-1 "><button type="button" class="btn btn-primary btn-xs" id=' + data1[i].doctor_appointment_slot_id + ' onclick="insert(' + data1[i].doctor_appointment_slot_id + ', \'' + data1[i].start_time + '\', \'' + data1[i].end_time + '\')"><i class="fa fa-clock-o" aria-hidden="true"> ' + data1[i].start_time + '</i></button></div>';
                        }
                        else if ((data1[i].doctor_schedule_type == 2 || data1[i].doctor_schedule_type == 4 || data1[i].doctor_schedule_type == 5 || data1[i].doctor_schedule_type == 6)) {
                            PatientAppiontment = PatientAppiontment + '<div class="col-xs-6 col-sm-2 col-md-1"><button type="button" class="btn btn-primary btn-xs" id=' + data1[i].doctor_appointment_slot_id + ' onclick="insert(' + data1[i].doctor_appointment_slot_id + ')"><i class="fa fa-clock-o" aria-hidden="true"> ' + data1[i].start_time + '</i></button></div>';
                        }
                        else if ((data1[i].doctor_schedule_type == 3 || data1[i].doctor_schedule_type == 5 || data1[i].doctor_schedule_type == 6 || data1[i].doctor_schedule_type == 7)) {
                            PatientAppiontment = PatientAppiontment + '<div class="col-xs-6 col-sm-2 col-md-1"><button type="button" class="btn btn-primary btn-xs" id=' + data1[i].doctor_appointment_slot_id + ' onclick="insert(' + data1[i].doctor_appointment_slot_id + ')"><i class="fa fa-clock-o" aria-hidden="true"> ' + data1[i].start_time + '</i></button></div>';
                        }
                        hospital_id = data1[i].hospital_id;
                        branch_id = data1[i].branch_id;
                        j++;
                    }
                    if (PatientAppiontment == '' || PatientAppiontment == null) {
                        var values = '<div class="NA" style="text-align:center;"><h1 style="text-align:center;">No Slot Available</h1><br/></div>';
                        $('#tblPatientAppiontment').append(values);
                    }
                    else {
                        var values = '<div class="NA" style="text-align:center;"><br/></div>';
                        $('#tblPatientAppiontment').append(PatientAppiontment + '</br>' + values);
                    }
                }
                else {
                    var values = '<div class="NA" style="text-align:center;"><h1 style="text-align:center;">No Slot Available</h1><br/></div>';
                    $('#tblPatientAppiontment').append(values);
                }
                $('#datePickToggle').css('display', 'block');
            }
            else {
                console.log(data1);
            }
        }
    });
}

function insert(doctorAppointmentSlotId, startTime, endtime) {
    debugger
    $('#hdnslotid').val(doctorAppointmentSlotId);
    document.getElementById("time").value = startTime;

    let additionalMinutes = parseInt($('#hdnsertime').val());

    if ($('#hdnsertime').val() == "" || $('#hdnsertime').val() == null) {
        document.getElementById("endtime").value = endtime;
    } else {
        function parseTime(timeString) {
            let [time, modifier] = timeString.split(' ');
            let [hours, minutes] = time.split(':');

            if (hours === '12') {
                hours = '00';
            }
            if (modifier === 'PM') {
                hours = parseInt(hours, 10) + 12;
            }

            let today = new Date();
            today.setHours(parseInt(hours), parseInt(minutes), 0);
            return today;
        }

        function formatTime(date) {
            let hours = date.getHours();
            let minutes = date.getMinutes();
            let ampm = hours >= 12 ? 'PM' : 'AM';

            hours = hours % 12;
            hours = hours ? hours : 12;
            minutes = minutes < 10 ? '0' + minutes : minutes;

            return hours + ':' + minutes + ' ' + ampm;
        }

        let startDateTime = parseTime(startTime);

        startDateTime.setMinutes(startDateTime.getMinutes() + additionalMinutes);

        $("#endtime").val(formatTime(startDateTime));
    }
}
function Loadtherapistpopup(button) {
    debugger;
    $('#hdntherapistid').val(button);
    var Warddatas = {
        P_Dml_Indicator: 'TS',
        id: $('#hdntherapistid').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Warddatas),
        success: function (data) {
            const data2 = JSON.parse(data);
            if (data2.msg === "Success") {
                debugger;
                const msg = data2.data.Table[0].msg;
                //$('#hdntherapistid').val('')
                $("#therapistendtime").val('')
                $("#therapisttime").val('')
                    // Populate the modal with the response data
                $('#therapisttime').val(data2.data.Table[0].schedule_start_time); // therapisttime
                $('#therapistendtime').val(data2.data.Table[0].schedule_end_time); // therapistendtime
                    $('#therapist_remarks').val(data2.data.Table[0].Remarks); // therapist_remarks

                    // Show success notification
                   // toastr.success('Details added Successfully');

                    // Open the modal
                   // $('#therapistpopup').modal('show');
               
            }
        },
        error: function () {
            toastr.error('Something Went Wrong');
        }
    });
}

$('#btn_infosave').click(function (id) {
    debugger;
    //if ($.trim($("#therpist_from_date").val()).length == "") {
    //    $('#Ptherpist_from_date').show();
    //    $('#Ptherpist_from_date').fadeOut(8000);
    //    $('#Ptherpist_from_date').html('Select From Date');
    //    $("#Ptherpist_from_date").focus();
    //    $("#Ptherpist_from_date").val('');
    //    return false;
    //}
    //if ($.trim($("#therpist_to_date").val()).length == "") {
    //    $('#Ptherpist_to_date').show();
    //    $('#Ptherpist_to_date').fadeOut(8000);
    //    $('#Ptherpist_to_date').html('Select To Date');
    //    $("#Ptherpist_to_date").focus();
    //    $("#Ptherpist_to_date").val('');
    //    return false;
    //}

    //var selected_from_WardDate = null, selected_to_wardDate = null;
    //if ($("#therpist_from_date").val() != '') {
    //    var date1 = $("#therpist_from_date").val().split('/');
    //    selected_from_WardDate = date1[2] + '-' + date1[1] + '-' + date1[0];
    //}
    //if ($("#therpist_to_date").val() != '') {
    //    var date2 = $("#therpist_to_date").val().split('/');
    //    selected_to_wardDate = date2[2] + '-' + date2[1] + '-' + date2[0]
    //}


    //var FromTime = $("#time").val();
    //var Exp_FromTime = moment(FromTime, 'hh:mm A').format('HH:mm');

    //var ToTime = $("#endtime").val();
    //var Exp_ToTime = moment(ToTime, 'hh:mm A').format('HH:mm');
    var id = $('#hdntherapistid').val();
    var FromTime = $("#therapisttime").val();
    var Exp_FromTime = moment(FromTime, 'hh:mm A');
    var ins_FromTime = moment(FromTime, 'hh:mm A').format('HH:mm');
    var FromMinutes = Exp_FromTime.hours() * 60 + Exp_FromTime.minutes();

    var ToTime = $("#therapistendtime").val();
    var Exp_ToTime = moment(ToTime, 'hh:mm A');
    var ins_ToTime = moment(ToTime, 'hh:mm A').format('HH:mm');
    var ToMinutes = Exp_ToTime.hours() * 60 + Exp_ToTime.minutes()
    if (FromMinutes >= ToMinutes) {
        $("#Pendtime").show();
        $("#Pendtime").html("End Time should be greater than Start Time").fadeOut(8000);
        $('#time').focus();
        return false;
    }
    var Warddatas = {
        P_Dml_Indicator:'TI',
        id: id,
        fromTime: ins_FromTime,// $("#therapisttime").val(),
        toTime: ins_ToTime,//$("#therapistendtime").val(),
        remarks: $('#therapist_remarks').val(),
        Schedule_Type: 7
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Calender/OTCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Warddatas),
        success: function (data) {
            const data2 = JSON.parse(data);
            if (data2.msg === "Success") {
                debugger;
                const msg = data2.data.Table[0].msg;
                if (msg === "Updated") {
                    $('#hdntherapistid').val('')
                    $("#therapistendtime").val('')
                    $('#therapist_remarks').val('')
                    toastr.success(`Details added Successfully`);

                    $('#therapistpopup').modal('hide');
                } else {
                    toastr.error('Something Went Wrong');
                }
            }
        },
        error: function () {
            toastr.error('Something Went Wrong');
        }
    });
});;




//schedule request tab -----end