//AdmissionMangement JS//
$(document).ready(function () {

    if ($('#hiddenRole_id').val() == 2) {
        ShowIPPatient();
        LoadWardname();
    }
    LoadBranch();
    
    LoadFloor();
});


function LoadBranch() {

    //Only KinderSurge
    //var dml = ''
    //if (parseInt($('#hiddenRole_id').val()) == 1) {
    //    dml = 'DLBRAN'
    //}
    //else {
    //    dml = 'LBRAN'
    //}

    var subdepartment = {
        Dml_Indicator: "LBRAN",
        //Dml_Indicator: dml,
        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);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    $('#SelBranch').empty();
                    var SubDepartment='';
                    var default_opt = '<option value="0">All</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });

                    if ($('#hiddenRole_id').val() == 1)
                    {
                        $('.common_Branch').append(SubDepartment);
                    }
                    else {
                        $('.common_Branch').append(default_opt + SubDepartment);
                    }

                    
                    //$('#SelBranch').change();

                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('.common_Branch').val($('#HospitalBranchID').val());
                    //    ShowIPPatient();
                    //}
                    //else
                    if ($('#hiddenRole_id').val() != 2) {
                        $('.common_Branch').val($('#HospitalBranchID').val());
                        $('.common_Branch').attr('disabled', true);
                        ShowIPPatient();
                        LoadWardname();
                    }
                }
            }
            else {
                console.log(data1);
            }

        }
    });
}

$('#discharge_Branch').change(function () {
    ShowIPPatient();
});

function ShowIPPatient() {
    debugger
    $('#shade_slot').show();
    var dml_indicator = "";
    var branch_id = "";

    //if (parseInt($("#hiddenRole_id").val()) == 1) {
    //    if ($('#selPatientListOption').val() !== "" && $('#selPatientListOption').val() !== null) {
    //        dml_indicator = $('#selPatientListOption').val() == 1 ? "ADAP" : "ADDL";
    //    }
    //    else {
    //        dml_indicator = "ADAP";
    //    }
    //}
    //else if ($('#selPatientListOption').val() == 2) {

    //    dml_indicator = "ADDL";
    //}
    //else {
    //    if ($('#selPatientListOption').val() !== "" && $('#selPatientListOption').val() !== null) {
    //        dml_indicator = $('#selPatientListOption').val() == 1 ? "ADAP" : "ADDL";
    //    }
    //    else {
    //        dml_indicator = "ADAP";
    //    }
    //}

    if ($('#selPatientListOption').val() !== "" && $('#selPatientListOption').val() !== null) {
        dml_indicator = $('#selPatientListOption').val() == 1 ? "ADAP" : "ADDL";
    }
    else {
        dml_indicator = "ADAP";
    }

    var from_date = ""; var to_date = "",IPdate='',admitdate='';
    if ($.trim($('#txtFromDate').val()).length != "") {
        from_date = $('#txtFromDate').val();
        from_date = from_date.split('/');
        from_date = from_date[2] + "-" + from_date[1] + "-" + from_date[0];
    }
    if ($.trim($('#txtToDate').val()).length != "") {
        to_date = $('#txtToDate').val();
        to_date = to_date.split('/');
        to_date = to_date[2] + "-" + to_date[1] + "-" + to_date[0];
    }

    if ($.trim($('#txtAdmittedDate').val()).length != "") {
        admitdate = $('#txtAdmittedDate').val();
        admitdate = admitdate.split('/');
        admitdate = admitdate[2] + "-" + admitdate[1] + "-" + admitdate[0];
    }

    if (parseInt($('#selPatientListOption').val()) == 1) {
        IPdate = admitdate;
        branch_id = $('#SelBranch').val();
    }
    else {
        IPdate = from_date;
        branch_id = $('#discharge_Branch').val();
    }

    var Patientdata = {
        Dml_Indicator: dml_indicator,
        from_date: IPdate,
        to_date: to_date,
        branchid: branch_id,
        patient_ID: $('#Ftxtpatient_id').val(),
        ip_referral_doctor: $('#Ftxtpatientname').val(),
        ward_no: $('#FtxtWardName').val(),
        IP_visit_report_id: $('#FtxtIPAdmissionNo').val(),
        ip_referral_doctorid: $('#hiddenRole_id').val(),
        mlc_no: $('#fdd_FloorName').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/AdmitPatient_Ins_Upd_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Patientdata),
        success: function (data) {
            $('#IPPatient').empty();
            $('#admissionpatientlist').empty();
            var data2 = JSON.parse(data);
            var AdmissionMangement = "";

            if (jQuery.isEmptyObject((data2.data))) {
                AdmissionMangement = "";
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    $('#IPPatient').html("");
                    $('#IPPatient').empty();
                    $('#admissionpatientlist').empty();
                    $('#admisssionpatientlistsearch').dataTable().fnClearTable();
              
                    $('#admisssionpatientlistsearch').dataTable().fnDestroy();
                    var Listdata = '';
                    debugger;
                    if ($('#selPatientListOption').val() == 1) {
                        $.each(data1, function (i, emp) {
                            var trB = '',PtImage='',trBCard='';
                            var image = emp.photo
                            var photoSrc;
                            var PatientPhoto = $('#HPatPhoto').val();
                            if ($.trim(emp.PatientImage) == "" || emp.PatientImage == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                //photoSrc = PatientPhoto + image;
                                PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + emp.PatientImage;
                                photoSrc = PtImage;
                            }
                            debugger;

                            var opername = emp.ip_operation_name;
                            if (opername === "") {
                                var opername = "-";
                            }

                            var ipinfo = emp.ward_bed_name;
                            const myArray = ipinfo.split("|");

                            var wrdname = myArray[0];
                            var bedname = myArray[1];
                            var floorname = myArray[2];
                            var secname = myArray[3];

                            var IDischargeRevert = '', CancellAdmission = '', style = '', IDClass = '';
                            

                            if (emp.ip_nursing_discharge == 1 && emp.is_convert_to_bill==0)
                            {
                                IDischargeRevert = '<a data-id="IDR_F1" data-type="role_rights_function" data-nav="sp_div" data-name="InitiateDischargeRevert" onclick="IDischargeRevert(' + emp.visit_reportid + ',this)">Initial Discharge Revert</a>';
                            }

                            if (emp.ip_nursing_discharge == 1)
                            {
                               /* style = 'cursor:pointer;font-weight:bold;color:black;';*/
                                IDClass = 'btn_r';
                            }
                            else
                            {
                                //style = 'cursor:pointer;';
                                //IDClass = 'btn_r btn-blue';
                                IDClass = 'btn_r';
                            }

                            CancellAdmission = '<a class="btn-blue"  data-id="CA_F1" data-type="role_rights_function" data-nav="sp_div" data-name="IPCancellAdmission" onclick=IPCancellAdmission("' + emp.ip_visit_report_id + '","' + emp.request_count + '","' + emp.admitdate + '","' + emp.today_date + '",this);>Cancel Admission</a>';

                            print = '<a class="btn_r btn-blue"   data-toggle="tooltip" data-placement="bottom" title="Draft Detail Print" type="button" class="btn btn-print btn-xs mr-5" onclick=Draft_report("' + emp.ip_visit_report_id + '",' + emp.hospitalid + ',' + emp.branch_id + ')>Draft Detail print</button>';

                            print_summary = '<a class="btn_r btn-blue"   data-toggle="tooltip" data-placement="bottom" title="Draft Summary Print" type="button" class="btn btn-print btn-xs mr-5" onclick=Draft_report_summary("' + emp.ip_visit_report_id + '",' + emp.hospitalid + ',' + emp.branch_id + ')>Draft Summary print</button>';

                            AdmissionSlipPrint = '<a class="btn_r btn-blue"   data-toggle="tooltip" data-placement="bottom" title="Admission Slip Print" type="button" class="btn btn-print btn-xs mr-5" onclick=AdmissionSlip_report("' + emp.visit_reportid + '",' + emp.hospitalid + ',' + emp.branch_id + ')>Admission Slip print</button>';

                            AdmissionFormPrint = '<a class="btn_r btn-blue"   data-toggle="tooltip" data-placement="bottom" title="Admission Form Print" type="button" class="btn btn-print btn-xs mr-5" onclick=AdmissionForm_report("' + emp.visit_reportid + '",' + emp.hospitalid + ',' + emp.branch_id + ')>Admission Form print</button>';

                            var Examination = '', Patienthistory = '', InvestigationsHistory = '', DoctorPrescription = '', VitalsMonitoring = '', DiabeticFlowSheet = '', NursingNotes = '', IVFluids = '';
                            var OperationDetails = '', TransferOrder = '', IpServices = '', InitiateDischarge = '', Feedback = '', Doctornotes = '', DutyMedicalOfficer = '', dischargeSummaryCreation = '';

                            if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                Examination = '<a class="btn_r btn-blue"  data-id="IP_AF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/IP_FormBuilder?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '&FormHead_id=5" title="Examination">Examination</a>';
                                Patienthistory = '<a class="btn_r btn-blue"  data-id="IP_PHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/IP_FormBuilder?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '&FormHead_id=4" title="Patient History">Patient History</a>';
                                OperationDetails = '<a class="btn_r btn-blue"  data-id="IP_ODF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/IP_FormBuilder?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '&FormHead_id=6" title="Operation Details">Operation Details</a>';
                                InitiateDischarge = '<a class="' + IDClass + '" style="' + style + '" data-id="IP_IDF1" data-type="role_rights_function" data-nav="sp_div" data-name="InitiateDischarge_form" onclick=\'IDischargeRequest(this,"' + emp.ip_visit_report_id + '")\'>Initiate Discharge</a>';
                                NursingNotes = '<a class="btn_r btn-blue"  data-id="IP_NNF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/IP_FormBuilder?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '&FormHead_id=9"  title="Nursing Notes">Nursing Notes</a>';
                                Doctornotes = '<a  class="btn_r btn-blue"  data-id="IP_DNF1" data-type="role_rights_function"data-nav="redirect" data-name="/Ipmanagement/IP_FormBuilder?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '&FormHead_id=8"  title="Doctor Notes">Doctor Notes</a>';
                                DutyMedicalOfficer = '<a  class="btn_r btn-blue"  data-id="IP_DMOF1" data-type="role_rights_function"data-nav="redirect" data-name="/Ipmanagement/IP_FormBuilder?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '&FormHead_id=18"  title="Duty Medical Officer Notes">Duty Medical Officer Notes</a>';
                            }
                            else {
                                Examination = '<a class="btn_r btn-blue"  data-id="IP_AF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/Examination?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="Examination">Examination</a>';
                                Patienthistory = '<a class="btn_r btn-blue"  data-id="IP_PHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/patienthistory?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="Patient History">Patient History</a>';
                                OperationDetails = '<a class="btn_r btn-blue"  data-id="IP_ODF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/operationdetails?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="Operation Details">Operation Details</a>';
                                InitiateDischarge = '<a class="' + IDClass + '" style="' + style + '" data-id="IP_IDF1" data-type="role_rights_function" data-nav="sp_div" data-name="InitiateDischarge_form" onclick=\'IDischargeRequest(this,"' + emp.ip_visit_report_id + '")\'>Initiate Discharge</a>';
                                NursingNotes = '<a class="btn_r btn-blue"  data-id="IP_NNF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/nursingnotes?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="Nursing Notes">Nursing Notes</a>';
                                Doctornotes = '<a  class="btn_r btn-blue"  data-id="IP_DNF1" data-type="role_rights_function"data-nav="redirect" data-name="/Ipmanagement/Doctornotes?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '"  title="Doctor Notes">Doctor Notes</a>';
                            }

                            //Examination = '<a class="btn_r btn-blue"  data-id="IP_AF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/Examination?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Examination</a>';
                            //Patienthistory = '<a class="btn_r btn-blue"  data-id="IP_PHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/patienthistory?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Patient History</a>';
                            //OperationDetails = '<a class="btn_r btn-blue"  data-id="IP_ODF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/operationdetails?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Operation Details</a>';
                            //InitiateDischarge = '<a class="' + IDClass + '" style="' + style + '" data-id="IP_IDF1" data-type="role_rights_function" data-nav="sp_div" data-name="InitiateDischarge_form" onclick=\'IDischargeRequest(this,"' + emp.ip_visit_report_id + '")\'>Initiate Discharge</a>';
                            //NursingNotes = '<a class="btn_r btn-blue"  data-id="IP_NNF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/nursingnotes?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Nursing Notes</a>';
                            //Doctornotes = '<a  class="btn_r btn-blue"  data-id="IP_DNF1" data-type="role_rights_function"data-nav="redirect" data-name="/Ipmanagement/Doctornotes?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Doctor Notes</a>';

                             
                            InvestigationsHistory = '<a class="btn_r btn-blue"  data-id="IP_IHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/InvestigationsHistory?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="Investigations History">Investigations History</a>';

                            DoctorPrescription = '<a  class="btn_r btn-blue"  data-id="IP_DPF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/doctorprescription?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="Doctor Prescription">Doctor Prescription</a>';

                            VitalsMonitoring = '<a class="btn_r btn-blue"  data-id="IP_VMF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/vitalsmonitoring?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="Vitals Monitoring">Vitals Monitoring</a>';

                            DiabeticFlowSheet = '<a class="btn_r btn-blue"  data-id="IP_DFSF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/diabeticchart?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="Diabetic Flow Sheet">Diabetic Flow Sheet</a>';

                            IVFluids = '<a class="btn_r btn-blue"  data-id="IP_IVFF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/ipfluids?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="IV Fluids">IV Fluids</a>';

                            TransferOrder = '<a class="btn_r btn-blue"  data-id="IP_TOF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/transferorder?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="Bed Transfer">Bed Transfer</a>';

                            IpServices = '<a class="btn_r btn-blue"  data-id="IP_ISF1" data-type="role_rights_function"data-nav="redirect" data-name="/BillingMaster/billingreqviewpage?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="IP Services">IP Services</a>';
                            IpInvestigation = '<a class="btn_r btn-blue"  data-id="IP_IV" data-type="role_rights_function"data-nav="redirect" data-name="/BillingMaster/billingreqviewpage?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '&Investigation=1" title="IP Investigation">IP Investigation</a>';


                            //var InitiateDischarge = '<a class="btn_r"  data-id="IP_IDF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/discharge?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Initiate Discharge</a>';

                            Feedback = '<a  class="btn_r btn-blue"  data-id="IP_FF1" data-type="role_rights_function"data-nav="redirect" data-name="/Ipmanagement/feedback?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '" title="Feedback">Feedback</a>';
 
                            //added by nandhini on 29/03/2024 for medway req
                            dischargeSummaryCreation = '<a  class="btn-blue"   href="/Ipmanagement/ipdischargesummarypage?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '&Did=' + emp.ip_doctor_id + '" title="Discharge Summary Creation">Discharge Summary Creation</a>'

                           //var op_name = '<p class="oper-name">' + opername + '</p> <br> <button type="button" class="btn btn-info btn-xs" data-toggle="modal" data-target="#myModal">Read_More</button> <div class="modal-content"> <div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button></div><div class="modal-body"><p> </p> </div> <div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div> </div></div></div>';

                            //if (parseInt($('#hiddenRole_id').val()) == 2) {
                            //trB = '<a href="#" class="dropdown-toggle btn btn-info-dots btn-xs pull-right" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" title="Options" data="" data-toggle="tooltip"  data-placement="bottom" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown-new" id=""> <div class="overflowmenu">' + print + '<br/>' + print_summary + '<br/>' + AdmissionSlipPrint + '<br/>' + AdmissionFormPrint + '<br/>' + Examination + '<br/>' + Patienthistory + '<br/>' + InvestigationsHistory + '<br/>' + DoctorPrescription + '<br/>' + Doctornotes + '<br/>' + VitalsMonitoring + '<br/>' + DiabeticFlowSheet + '<br/>' + NursingNotes + '<br/>' + IVFluids + '<br/>' + OperationDetails + '<br/>' + TransferOrder + '<br/>' + IpServices + '<br/>' + IpInvestigation + '<br/>' + InitiateDischarge + '<br/>' + Feedback + '<br/>' + DutyMedicalOfficer + '<br/>' + CancellAdmission + '<br/>' + dischargeSummaryCreation + '<br/>' + IDischargeRevert + '</div></div>';

                            trB = '<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="overflowmenu"><li>' + print + '</li><li>' + print_summary + '</li><li>' + AdmissionSlipPrint + '</li><li>' + AdmissionFormPrint + '</li><li>' + Examination + '</li><li>' + Patienthistory + '</li><li>' + InvestigationsHistory + '</li><li>' + DoctorPrescription + '</li><li>' + Doctornotes + '</li><li>' + VitalsMonitoring + '</li><li>' + DiabeticFlowSheet + '</li><li>' + NursingNotes + '</li><li>' + IVFluids + '</li><li>' + OperationDetails + '</li><li>' + TransferOrder + '</li><li>' + IpServices + '</li><li>' + IpInvestigation + '</li><li>' + InitiateDischarge + '</li><li>' + Feedback + '</li><li>' + DutyMedicalOfficer + '</li><li>' + CancellAdmission + '</li><li>' + dischargeSummaryCreation + '</li><li>' + IDischargeRevert +'</li></div></ul></div>';
                            trBCard = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu support-menu-btns ip-card-dropdown"><div class="overflowmenu"><li>' + print + '</li><li>' + print_summary + '</li><li>' + AdmissionSlipPrint + '</li><li>' + AdmissionFormPrint + '</li><li>' + Examination + '</li><li>' + Patienthistory + '</li><li>' + InvestigationsHistory + '</li><li>' + DoctorPrescription + '</li><li>' + Doctornotes + '</li><li>' + VitalsMonitoring + '</li><li>' + DiabeticFlowSheet + '</li><li>' + NursingNotes + '</li><li>' + IVFluids + '</li><li>' + OperationDetails + '</li><li>' + TransferOrder + '</li><li>' + IpServices + '</li><li>' + IpInvestigation + '</li><li>' + InitiateDischarge + '</li><li>' + Feedback + '</li><li>' + DutyMedicalOfficer + '</li><li>' + CancellAdmission + '</li><li>' + dischargeSummaryCreation + '</li><li>' + IDischargeRevert +'</li></div></ul></div>';
                           // trBCard = '<a href="#" class="dropdown-toggle btn btn-info-dots btn-xs pull-right" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" title="Options" data="" data-toggle="tooltip"  data-placement="bottom" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu support-menu-btns ip-card-dropdown" id=""> <div class="text-left">' + print + '<br/>' + print_summary + '<br/>' + AdmissionSlipPrint + '<br/>' + AdmissionFormPrint + '<br/>' + Examination + '<br/>' + Patienthistory + '<br/>' + InvestigationsHistory + '<br/>' + DoctorPrescription + '<br/>' + Doctornotes + '<br/>' + VitalsMonitoring + '<br/>' + DiabeticFlowSheet + '<br/>' + NursingNotes + '<br/>' + IVFluids + '<br/>' + OperationDetails + '<br/>' + TransferOrder + '<br/>' + IpServices + '<br/>' + IpInvestigation + '<br/>' + InitiateDischarge + '<br/>' + Feedback + '<br/>' + DutyMedicalOfficer + '<br/>' + CancellAdmission + '<br/>' + IDischargeRevert + '<br/>' + dischargeSummaryCreation + '</div></div>';

                            

                            //}
                            //else if (parseInt($('#hiddenRole_id').val()) == 1 || parseInt($('#hiddenRole_id').val()) == 5) {
                            //    trB = '<a href="#" class="dropdown-toggle btn btn-info-dots btn-xs pull-right" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" title="Options" data="" data-toggle="tooltip" data-placement="bottom" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu ip-card-dropdown" id=""> <div class="text-left">' + print + '<br/>' + print_summary + '<br/>' + AdmissionSlipPrint + '<br/>' + AdmissionFormPrint + '<br/>' + Examination + '<br/>' + Patienthistory + '<br/>' + InvestigationsHistory + '<br/>' + DoctorPrescription + '<br/>' + Doctornotes + '<br/>' + IpServices + '</div></div>';
                            //}
                            //else {
                            //    trB = '<a href="#" class="dropdown-toggle btn btn-info-dots btn-x pull-right" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" title="Options" data="" data-toggle="tooltip"  data-placement="bottom"  data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu ip-card-dropdown" id=""> <div class="text-left">' + print + '<br/>' + print_summary + '<br/>' + AdmissionSlipPrint + '<br/>' + AdmissionFormPrint + '<br/>' + InvestigationsHistory + '<br/>' + VitalsMonitoring + '<br/>' + DiabeticFlowSheet + '<br/>' + NursingNotes + '<br/>' + IVFluids + '<br/>' + OperationDetails + '<br/>' + TransferOrder + '<br/>' + DoctorPrescription + '<br/>' + IpServices + '<br/>' + InitiateDischarge + '<br/>' + Feedback + '<br/>' + CancellAdmission + '<br/>' + IDischargeRevert + '</div></div>';
                            //}

                                var intiate_discharge_icon = '', initiateclass = '';
                                if (emp.ip_nursing_discharge == 1) {
                                    // intiate_discharge_icon = '<img src="/Content/img/dischargeicon.png" class="dischargeicon" />'
                                    initiateclass = "inibgcolor"
                                }
                                
                                AdmissionMangement = AdmissionMangement + '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-20">'
                              + ' <div class="pat-box ' + initiateclass + '">'
                              + '<div class=row>'
                              + '<div class="col-md-4"></div>'
                                    + '<div class="col-md-8">' + trBCard + '</div>'
                              + '</div>'
                                  +' <div class="row">'
                                       +'<div class="col-sm-12 patient-name">'
                                           + '<h5>'
                               + ' <a class="btn_r"  data-id="IP_AF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/ippatientdetails?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">'
                                               + ' ' + emp.PatientName + ''
                                               + '</a>' + intiate_discharge_icon
                                           +'</h5>'
                                       + '</div>'
                                       

                                      
                                   +'</div>'
                                   +'<div class="row">'
                                      + ' <div class="col-sm-8 col-xs-8 pr-0">'
                                      + '<div class="col-sm-12 pl-0 patient-idnumber">'
                                           + '<h5>' + emp.ip_patient_id + '</h5>'
                                       + '</div>'
                                          +' <div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                             + '  <p>' + emp.age + ' years | ' + emp.gender + ' | <i class="fa fa-tint" style="color:red;"></i>' + emp.patient_blood_group + '</p>'
                                          + ' </div>'
                                       + '</div>'
                                       + ' <div class="col-sm-4 col-xs-4">'
                                        + '   <img class="img-circle ip-img-circle" src="' + photoSrc + '" alt="User Avatar">'
                                      + ' </div>'
                                  + ' </div>'
                                   + '<div class="row">'
                                          + ' <div class="col-sm-12 col-xs-12 pr-0 pat-content">'
                                             + '  <p><span class="pat-heading">Doctor : </span> ' + emp.ip_doctor_name + '</p>'
                                           + '</div>'
                                           + ' <div class="col-sm-12 col-xs-12 pr-0 pat-content">'
                                             + '  <p><span class="pat-heading">Referral Doctor : </span> ' + emp.ip_referral_doctor + '</p>'
                                           + '</div>'
                                            + ' <div class="col-sm-12 col-xs-12 pr-0 pat-content">'
                                             + '  <p><span class="pat-heading">Admission Type : </span> ' + emp.type_of_admition + '</p>'
                                           + '</div>'
                                           + ' <div class="col-sm-12 col-xs-12 pr-0 pat-content">'
                                             + '  <p><span class="pat-heading">Claim Status : </span> ' + emp.claim_status + '</p>'
                                           + '</div>'
                                          //+' <div class="col-sm-12 col-xs-12 pat-content">'
                                          //    + ' <p><span class="pat-heading"> IP No : </span>' + emp.display_visit_report + '</p>'
                                          //+ ' </div>'
                                          + ' <div class="col-sm-12 col-xs-12 pat-content">'
                                              + ' <p><span class="pat-heading"> IP Admission No : </span>' + emp.ip_visitno + '</p>'
                                          + ' </div>'
                                            + ' <div class="col-sm-12 col-xs-12 pat-content">'
                                              + ' <p> <span class="pat-heading"> Admit Date : </span>' + emp.ip_patient_admitdate + '</p>'
                                          + ' </div>'
                                          +' <div class="col-sm-12 col-xs-12 pat-content">'
                                             + '  <p> <span class="pat-heading"> Ward : </span>' + wrdname + '  </p>'
                                           + '</div>'
                                           + ' <div class="col-sm-12 col-xs-12 pat-content">'
                                             + '  <p> <span class="pat-heading"> Bed : </span>' + bedname + '  </p>'
                                           + '</div>'
                                           + ' <div class="col-sm-12 col-xs-12 pat-content">'
                                             + '  <p>  <span class="pat-heading"> Floor : </span> ' + floorname + '</p>'
                                           + '</div>'
                                           + ' <div class="col-sm-12 col-xs-12 pat-content">'
                                             + '  <p>   <span class="pat-heading"> Section : </span>' + secname + '  </p>'
                                           + '</div>'
                                            + ' <div class="col-sm-12 col-xs-12 pat-content">'
                                             + '  <button type="button" class="btn btn-primaryuse btn-xs mb-10 pull-right" id="btnPrintAdmissionSlip" onclick=PrintAdmissionBarcode("' + emp.hospitalid + '","' + emp.branch_id + '","' + emp.patientid + '","' + emp.visit_reportid + '")>Print</button>'
                                           + '</div>'
                                  + ' </div>'
                             + '  </div>'
                               // + ' </a>'
                          + ' </div>'

                            /*//Listdata = Listdata + '<tr><td>' + '<div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar"></div>' + '</td><td>' + emp.ip_patient_id + '</td><td>' + emp.PatientName + '</td><td>' + emp.patient_number + '</td><td>' + emp.display_visit_report + '</td><td>' + emp.ip_visitno + '</td><td>' + emp.ward_bed_name + '</td><td>' + emp.ip_patient_admitdate + '</td><td>' + emp.type_of_admition + '</td><td>' + emp.claim_status + '</td><td>' + emp.ip_doctor_name + '</td><td>' + emp.ip_referral_doctor + '</td><td>' + emp.is_app_installed + '</td><td>' + emp.branch_name + '</td><td>' + emp.BillingName + '</td><td>' + emp.ip_operation_name + '</td><td>' + emp.referral_person_name + '</td><td>' + trB + '</td></tr>'*/
                            Listdata = Listdata + '<tr><td>' + '<div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar"></div>' + '</td><td>' + emp.ip_patient_id + '</td><td><a class="btn_r"  data-id="IP_AA1" data-type="role_rights_add" data-nav="redirect" data-name="/Ipmanagement/ippatientdetails?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">'
                                + ' ' + emp.PatientName + ''
                                + '</a></td><td>' + emp.patient_number + '</td><td>' + emp.display_visit_report + '</td><td>' + emp.ip_visitno + '</td><td>' + emp.ward_bed_name + '</td><td>' + emp.ip_patient_admitdate + '</td><td>' + emp.type_of_admition + '</td><td>' + emp.claim_status + '</td><td>' + emp.ip_doctor_name + '</td><td>' + emp.ip_referral_doctor + '</td><td>' + emp.is_app_installed + '</td><td>' + emp.branch_name + '</td><td>' + emp.BillingName + '</td><td>' + emp.ip_operation_name + '</td><td>' + emp.referral_person_name + '</td><td>' + trB + '</td></tr>'

                        });
                        $('#shade_slot').hide();
                        debugger;
                        if ($('#pat_list_table').is(":visible")) {
                            $('#IPPatient').hide();
                            $('#pat_list_table').show();
                        }
                        else {
                            $('#IPPatient').show();
                            $('#pat_list_table').hide();
                        }

                        $('#IPPatient').html(AdmissionMangement);
                        $('#admissionpatientlist').html(Listdata);
                        $('#admisssionpatientlistsearch').dataTable().fnDestroy();
                        datatable('admisssionpatientlistsearch');
                    }
                    else {
                        
                        var row_data = "";
                        var action = "", discharge = "", cleaned = "", bed_status = "";;
                        $('#IPPatient').empty();
                        $('#dischargetbl').dataTable().fnClearTable();
                        $('#dischargetbl').dataTable().fnDestroy();
                        $('#dischargetbl').dataTable().fnDestroy();
                        tr = $('<table id="dischargetbl" class="table table-bordered table-striped no-footer dataTable" data-title="Patient_discharge" data-size="Legal" />');

                        tr.append("<thead><tr><th>S.No</th><th>Patient Name</th><th>Visit Report ID</th><th>Date of Admission</th><th>Date of Discharge</th><th>Discharge Status</th><th>Admission Type</th><th>Surgery</th><th>Action</th></tr></thead><tbody>");


                        $.each(data1, function (i, emp) {
                            if (emp.Bed_Status == 1) {
                                bed_status = '<span class="label label-success">Cleaned</span>';
                            }
                            else {
                                bed_status = '<span class="label label-danger">Not Cleaned</span>';
                            }
                            cleaned = "<button data-toggle='tooltip' data-placement='bottom' title='Clean' type='button' class='btn btn-print btn-xs mr-5' onclick='end_clean(" + emp.visit_reportid + ")'><i class='fas fa-broom' aria-hidden='true'></i></button>";
                            discharge = "<button  data-toggle='tooltip' data-placement='bottom' title='Prinrt' type='button' class='btn btn-print btn-xs mr-5' onclick=Discharge_report(" + emp.branch_id + "," + emp.hospitalid + "," + emp.patientid + "," + emp.visit_reportid + ")><i class='fa fa fa-print' aria-hidden='true'></i></button>";

                            action = "<a data-id='IP_AF1' data-type='role_rights_edit'data-nav='redirect' data-name='/Ipmanagement/ippatientdetails?Patient_Id=" + emp.ip_patient_id + "&IPVisitReport_Id=" + emp.ip_visit_report_id + "&IPDischarge_Id=" + 2 + "&branch_id=" + emp.branch_id + "' class='label label-success btn_r'>View Details</a>";
                            EditDetails = "<a data-id='IP_AF1' data-type='role_rights_edit'data-nav='redirect' data-name='/Ipmanagement/ippatientdetails?Patient_Id=" + emp.ip_patient_id + "&IPVisitReport_Id=" + emp.ip_visit_report_id + "&IPDischarge_Id=" + 1 + "&branch_id=" + emp.branch_id + "' class='label label-success btn_r'>Edit Details</a>";
                            row_data = "<tr><td>" + (i + 1) + "</td><td>" + emp.PatientName + "</td><td>" + emp.display_visit_report + "</td><td>" + emp.admission_date + "</td><td>" + emp.discharge_date + "</td><td>" + emp.discharge_status + "</td><td>" + emp.type_of_admition + "</td><td>" + emp.ip_operation_name + "</td><td>" + action + " " + discharge + "</td></tr>";
                            tr.append(row_data);

                        });
                        $('#shade_slot').hide();
                        tr.append("</tbody></table>");
                        $("#IPPatient").show();
                        $('#IPPatient').html(tr);
                        datatable('dischargetbl', 'Patient_discharge', 'Legal');
                        
                    }
                }
                else {
                    console.log(data);
                }
            }
            $('#shade_slot').hide();
        }
    });
}

function PrintAdmissionBarcode(hospitalid, branch_id, patientid,visit_reportid) {
    debugger;
    var load_data = {
        formid: '107',
        branchid: branch_id,
        hospitalid: hospitalid,
        patientid: patientid,
        visit_reportid: visit_reportid,
        visittype: '2',
        wardid: 0,
        deptid: 0,
        doctorid:0
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            // window.open(link, '_blank');
            iframe = document.createElement('iframe'); //load content in an iframe to print later
            document.body.appendChild(iframe);

            iframe.style.display = 'none';
            iframe.src = link;
            iframe.onload = function () {
                setTimeout(function () {
                    iframe.focus();
                    iframe.contentWindow.print();
                }, 1);
            };
        }
    });
}


function Discharge_report(branch_id, hospitalid, patientid, visit_reportid)
{
    var load_data = {
        formid: '83',
        branchid: branch_id,
        hospitalid: hospitalid,
        patientid: patientid,
        visit_reportid: visit_reportid
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            // window.open(link, '_blank');
            iframe = document.createElement('iframe'); //load content in an iframe to print later
            document.body.appendChild(iframe);

            iframe.style.display = 'none';
            iframe.src = link;
            iframe.onload = function () {
                setTimeout(function () {
                    iframe.focus();
                    iframe.contentWindow.print();
                }, 1);
            };
        }
    });
}


$('#selPatientListOption').change(function () {
    if ($('#selPatientListOption').val() == 1) {
        $('#divSearch').hide();
        ShowIPPatient();
        $("#IPPatient").show();
        $('#showlist').show();
        $('#showgrid').show();
        $('#pat_list_table').hide();
        $('.discharge_sidebar').hide();
        $('.admit_sidebar').show();
    }
    else {
        $('#divSearch').show();
        $("#IPPatient").hide();
        $('#showlist').hide();
        $('#showgrid').hide();
        $('#pat_list_table').hide();
        $('.admit_sidebar').hide();
        //$('#admit_settings').hide();
        //$('.discharge_sidebar').show();
        ShowIPPatient();
    }
});


$('#btnSearch').click(function () {
    if ($.trim($('#txtFromDate').val()).length == "") {
        $('#PtxtFromDate').show();
        $('#PtxtFromDate').fadeOut(8000);
        $('#PtxtFromDate').html('Select From Date');
        $('#txtFromDate').focus();
        $('#txtFromDate').val('');
        return false;
    }
    //if ($.trim($('#txtToDate').val()).length == "") {
    //    $('#PtxtToDate').show();
    //    $('#PtxtToDate').fadeOut(8000);
    //    $('#PtxtToDate').html('Select To Date');
    //    $('#txtToDate').focus();
    //    $('#txtToDate').val('');
    //    return false;
    //}
    ShowIPPatient();

});


//$('#admit_settings').click(function () {

//    $('.asidefilterclass').addClass('hidden');
//    $('#asideadmisssionpatientlistsearch').removeClass('hidden');
//    $('.groupclass').addClass('hidden');
//    $('#admisssionpatientlistsearchdropdown').removeClass('hidden');
//    $('.Filterclass').addClass('hidden');
//    $('#admisssionpatientlistsearchcolshow').removeClass('hidden');
//})


//$('#discharge_settings').click(function () {

//    $('.asidefilterclass').addClass('hidden');
//    $('#asideexample1').removeClass('hidden');
//    $('.groupclass').addClass('hidden');
//    $('#example1dropdown').removeClass('hidden');
//    $('.Filterclass').addClass('hidden');
//    $('#example1colshow').removeClass('hidden');
//})

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

    ShowIPPatient();
});

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

    $('#Ftxtpatient_id').val('');
    $('#Ftxtpatientname').val('');
    $('#FtxtWardName').val('');
    $('#FtxtIPAdmissionNo').val('');
    $('#txtAdmittedDate').val('');
    $('#fdd_FloorName').val('0');
    if (parseInt($('#hiddenRole_id').val()) == 2)
    {
        $('#SelBranch').val('0');
    }
   
    ShowIPPatient();
});

function IDischargeRevert(visit_report_id, event) {
    debugger;
    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         debugger;
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {
                     return;
                 }
                 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,You want to Initial Discharge Revert the Patient.?',
         {
             closeButton: true,
             progressBar: true,
             allowHtml: true,
             timeOut: 0,

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


                     var Patientdata = {
                         Dml_Indicator: 'IDR',
                         surgery_request_id: visit_report_id
                     }

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

                             }
                             else {

                                 if (data2.msg == "Success") {
                                     var data1 = data2.data;
                                     if (data1.length > 0) {
                                         toastr.success('Initial Discharge Revert Successfully',
                                     {
                                         //closeButton: false,
                                         progressBar: true,
                                         allowHtml: true,
                                         timeOut: 0,
                                     });

                                         ShowIPPatient();
                                     }

                                 }
                                 else {
                                     console.log(data);
                                 }

                             }
                         },
                         error: function (data) {

                         }
                     });
                 });
             }
         });


                 }
             }
         }
     });

}

function IDischargeRequest(event, id) {
    debugger;

    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    $('#divtype').addClass('disabled')
    $('#divsubdis').addClass('disabled')
    // $('#divdptlb').addClass('disabled')

    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         debugger;
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {
                     return;
                 }
                 else {

                     var Patientdata = {
                         Dml_Indicator: 'PRC',
                         IP_visit_report_id: id
                     }

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

                             }
                             else {

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


                                     $.each(data1, function (i, emp) {
                                         debugger;
                                         if(emp.request_count > 0)
                                         {
                                             if (parseInt($('#HFormbuilder_id').val()) == 1) {
                                                 window.location = '/Ipmanagement/IP_FormBuilder?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '&FormHead_id=2';
                                             }
                                             else {
                                                 window.location = '/Ipmanagement/discharge?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '';
                                             }
                                             //window.location = '/Ipmanagement/discharge?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '';
                                         }
                                         else
                                         {
                                             toastr.warning('No Requests for this Patient.Please add Requests');
                                         }
                                        
                                         //var InitiateDischarge = '<a class="btn_r"  data-id="IP_IDF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/discharge?Patient_Id=' + emp.ip_patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Initiate Discharge</a>';

                                     });
                                 }
                                 else {
                                     console.log(data);
                                 }
                             }
                         },
                         error: function (data) {

                         }
                     });

                 }
             }
         }
     });


}

function Draft_report(visit_report_id, hospitalid, branch_id) {
    debugger;

    var load_data = {
        formid: '85',
        branchid: branch_id,
        hospitalid: hospitalid,
        text_visit_report_id: visit_report_id

    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
             window.open(link, '_blank');
            //iframe = document.createElement('iframe'); //load content in an iframe to print later
            //document.body.appendChild(iframe);

            //iframe.style.display = 'none';
            //iframe.src = link;
            //iframe.onload = function () {
            //    setTimeout(function () {
            //        iframe.focus();
            //        iframe.contentWindow.print();
            //    }, 1);
            //};
        }
    });

}

function Draft_report_summary(visit_report_id, hospitalid, branch_id) {
    debugger;

    var load_data = {
        formid: '124',
        branchid: branch_id,
        hospitalid: hospitalid,
        text_visit_report_id: visit_report_id

    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
             window.open(link, '_blank');
            //iframe = document.createElement('iframe'); //load content in an iframe to print later
            //document.body.appendChild(iframe);

            //iframe.style.display = 'none';
            //iframe.src = link;
            //iframe.onload = function () {
            //    setTimeout(function () {
            //        iframe.focus();
            //        iframe.contentWindow.print();
            //    }, 1);
            //};
        }
    });

}

function IPCancellAdmission(visit_report_id, request_count, admitdate, today_date, event) {
    debugger;
    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         debugger;
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {
                     return;
                 }
                 else {

                     if (request_count > 0) {
                         toastr.warning('The patient already have the request.So you can not cancel the admission.');
                         return false;
                     }
                     else if (parseInt(admitdate) >= 24) {
                         toastr.warning('The patient admitdate is not in current date.So you can not cancel the admission.');
                         return false;
                     }

                     $('#IPAdmissionCancellation').modal('show');
                     $('#AC_Visit_id').val(visit_report_id);

                 }
             }
         }
     });


}

$('#btnCSubmit').click(function () {
    var Patientdata = {
        Dml_Indicator: 'PADC',
        IP_visit_report_id: $('#AC_Visit_id').val(),
        discharge_reason: $('#txtCancellReason').val()
    }

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

            }
            else {

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

                    if (data1.length > 0) {
                        toastr.success('The Patient Admission canceled Successfully.');

                        $('#IPAdmissionCancellation').modal('hide');
                        $('#AC_Visit_id').val('');
                        ShowIPPatient();
                    }
                }
                else {
                    console.log(data);
                }
            }
        },
        error: function (data) {

        }
    });
});

function AdmissionSlip_report(visit_reportid, hospitalid, branch_id) {
    debugger;

    var load_data = {
        formid: '116',
        branchid: branch_id,
        hospitalid: hospitalid,
        visit_reportid: visit_reportid

    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            // window.open(link, '_blank');
            iframe = document.createElement('iframe'); //load content in an iframe to print later
            document.body.appendChild(iframe);

            iframe.style.display = 'none';
            iframe.src = link;
            iframe.onload = function () {
                setTimeout(function () {
                    iframe.focus();
                    iframe.contentWindow.print();
                }, 1);
            };
        }
    });

}

function AdmissionForm_report(visit_reportid, hospitalid, branch_id) {
    debugger;

    var load_data = {
        formid: '117',
        branchid: branch_id,
        hospitalid: hospitalid,
        visit_reportid: visit_reportid

    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            // window.open(link, '_blank');
            iframe = document.createElement('iframe'); //load content in an iframe to print later
            document.body.appendChild(iframe);

            iframe.style.display = 'none';
            iframe.src = link;
            iframe.onload = function () {
                setTimeout(function () {
                    iframe.focus();
                    iframe.contentWindow.print();
                }, 1);
            };
        }
    });

}

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

    LoadWardname();
    
});

function LoadWardname() {
    var Warddata = {
        Dml_Indicator: "WN",
        branch_id: $('#SelBranch').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) {
            $('#FtxtWardName').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

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


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

                        Floor = Floor + '<option value="' + emp.wardid + '">' + emp.ward_name + '</option>';

                    });
                    $('#FtxtWardName').append(default_opt + Floor);

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

function LoadFloor() {
    var Warddata = {
        Dml_Indicator: "WFS",
    }

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

            }
            else {

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


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

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

                    });
                    $('#fdd_FloorName').append(default_opt + Floor);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}
function end_clean(visitid) {
    debugger
    var beddata = {
        Dml_Indicator: "BEC",
        IP_visit_report_id: visitid
    }

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

            }
            else {

                if (data2.msg == "Success") {
                    ShowIPPatient()
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}