
$(document).ready(function () {
    LoadSpeciality()
    var today = new Date();
    var formattedDate = ('0' + today.getDate()).slice(-2) + '/' + ('0' + (today.getMonth() + 1)).slice(-2) + '/' +  today.getFullYear();
    $('#txtAdmitDate').val(formattedDate);

});
// Patient search Start//
function LoadDoctor() {
    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#SelBranch').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);
            $('#ddDoctor').empty();
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var tr = '';
                    var SelRole = '';

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

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

//    LoadDoctor();
//});

function LoadBranch() {
    $('#SelBranch').empty();

    //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 {

                    var Branch;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        Branch = Branch + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    $('#SelBranch').append(default_opt + Branch);

                    //Only KinderSurge
                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('#SelBranch').val($('#HospitalBranchID').val());
                    //    LoadDoctor();
                    //}
                    //else
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        $('#SelBranch').attr('disabled', true);
                       // LoadDoctor();
                    }

                    if($('#IPadmbranchid').val()!="")
                    {
                        $('#SelBranch').val($('#IPadmbranchid').val());
                     //   LoadDoctor();
                    }
                }
            }
            else {
                console.log(data1);
            }
            $('#SelBranch').on('change', function () {
                var selectedBranchText = $('#SelBranch option:selected').text();
                if (selectedBranchText != "--Select--") {
                    $('#wardNoLabel').html(selectedBranchText + " Ward No <span class='red'>*</span>");
                } else {
                    $('#wardNoLabel').html("Ward No <span class='red'>*</span>");
                }
            });

        }
    });
}
//function LoadBranch() {
//    $('#SelBranch').empty();

//    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);
//            if (data1.msg == "Success") {
//                var data1 = data1.data;
//                console.log(data1);
//                if (!jQuery.isEmptyObject(data1)) {
//                    var Branch;
//                    var default_opt = '<option value="0">--Select--</option>';
//                    $.each(data1.Table, function (i, emp) {
//                        Branch = Branch + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
//                    });
//                    $('#SelBranch').append(default_opt + Branch);

//                    // Handle role and preselected branch
//                    if ($('#hiddenRole_id').val() != 2) {
//                        $('#SelBranch').val($('#HospitalBranchID').val());
//                        $('#SelBranch').attr('disabled', true);
//                    }

//                    if ($('#IPadmbranchid').val() != "") {
//                        $('#SelBranch').val($('#IPadmbranchid').val());
//                    }
//                }
//            } else {
//                console.log(data1);
//            }

//            // Attach an event listener to update the label when a branch is selected
            //$('#SelBranch').on('change', function () {
            //    var selectedBranchText = $('#SelBranch option:selected').text();
            //    if (selectedBranchText != "--Select--") {
            //        $('#wardNoLabel').html(selectedBranchText + " Ward No <span class='red'>*</span>");
            //    } else {
            //        $('#wardNoLabel').html("Ward No <span class='red'>*</span>");
            //    }
            //});
//        }
//    });
//}



$(document).ready(function () {
    debugger;

    $('#txtRDoctorName').autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/Ipmanagement/DoctorNameAutoCompletelist",
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term, Dml_Indicator: "ALDL", branch_id: $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').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) {
            $('#HdnRefDoctorid').val(ui.item.id);
        },
        html: true,
        open: function (event, ui) {
            $(".ui-autocomplete").css("z-index", 1000);

        }
    });

    LoadRefBranch();
    $('#IP_EditBtn').hide();
    $('#model_popup').addClass('hidden')
    $('#txtPSearch').removeClass('disabled')
    var patientid = $('#IPadmpatientid').val();
    var branch_id = $('#IPadmbranchid').val();

    if (patientid != '' && branch_id != '') {

        $('#model_popup').removeClass('hidden');
        $('#txtPSearch').addClass('disabled');
        $('#Hdnpatient_id').val(patientid);
        //PatientGeneralDetails(patientid, branch_id);
        IP_PatientGeneralDetails(patientid, branch_id);
    }

    if ($('#IPVisitReport_Id').val() != "") {
        $("#HBtnSaveUpdate").val("Update");
        $("#patientdetails_btn").removeClass('hide');
        $("#admission_btn").hide();
        MultiOperationload();
    }
    else if ($('#OPVisitReport_Id').val() != "") {
        //PatientGeneralDetails($('#IPPatient_Id').val(), $('#hBack_branchid').val());
        IP_PatientGeneralDetails($('#IPPatient_Id').val(), $('#hBack_branchid').val());
        $('a[data-toggle=TypeOf_Admition][data-title="' + 1 + '"]').removeClass('not-active');
        $('a[data-toggle=TypeOf_Admition][data-title="' + 1 + '"]').addClass('active');
        $("#TypeOf_Admition").val(1);
        $('.div_surgery').addClass('hide');
        patientdatafetch();
        transfertoipfetch()
    }
    else {
      
        $("#admission_btn").removeClass('hide');
        LoadBranch();
        var pant_id = $('#IPadmpatientid').val();
        $('#txtPSearch').val(pant_id);

        $('#txtPSearch').autocomplete({
            source: function (request, response) {
                $.ajax({
                    async: true,
                    url: "/PatientSearch/AutoCompleteData?PName=" + $('#txtPSearch').val() + '&role=' + $('#hiddenRole_id').val(),
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term, branch_id: $('#SelBranch').val(), Dml_Indicator: 'ABNAP' },//Dml_Indicator: 'NAP' one branch dml
                    success: function (data) {
                        $('#Hdnpatient_id').val('');
                        response($.map(data, function (item) {
                            var photo = '/Content/img/profile_icon.png';
                            if (item.photo != null && item.photo != '') {
                                photo = 'http://app.ursugar.com/UserprofileImg/' + item.photo
                            }
                            console.log('------>' + item.address_line_1);
                            return { label: item.patient_first_name + '/' + item.Patient_id + '/' + item.age + '/' + item.phone_number_1, value: item.SearchOption, name: item.patient_first_name, imgsrc: photo, ageval: item.age, patientid: item.Patient_id, mobileno: item.phone_number_1, mobileno1: item.phone_number_2, doctor_patient_id: item.doctor_patient_id };
                        }))
                    }
                })
            },
            minLength: 1,
            select: function (event, ui) {
                $('#Hdnpatient_id').val(ui.item.patientid);
                //txtPSearch(ui.item.patientid)
            },
            html: true,
            open: function (event, ui) {
                $(".ui-autocomplete").css("z-index", 1000);

            }
        })
            
    }

});


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

    if ($.trim($('#SelBranch').val()) == 0) {
        $('#PSelBranch').show();
        $('#PSelBranch').fadeOut(8000);
        $('#PSelBranch').html('Select Branch Name');
        $('#SelBranch').focus();
        return false;
    }
    if ($.trim($('#ddDoctor').val()) == "") {
        $('#PddDoctor').show();
        $('#PddDoctor').fadeOut(8000);
        $('#PddDoctor').html('Please Select Doctor');
        return false;
    }
    if ($.trim($('#HdnadmDoctorid').val()) == "") {
        $('#PddDoctor').show();
        $('#PddDoctor').fadeOut(8000);
        $('#PddDoctor').html('Please Select Doctor');
        return false;
    }

    if ($.trim($('#txtPSearch').val()) == "") {
        $('#PtxtPSearch').show();
        $('#PtxtPSearch').fadeOut(8000);
        $('#PtxtPSearch').html('Enter Patient Id');
        $('#txtPSearch').focus();
        $('#txtPSearch').val('');
        return false;
    }    


    $('#fetchPatdetails').modal('hide');
    //PatientGeneralDetails($('#Hdnpatient_id').val(), $('#SelBranch').val());
    IP_PatientGeneralDetails($('#Hdnpatient_id').val(), $('#SelBranch').val());
    patientdatafetch();

});

function patientdatafetch() {
    debugger;
    if ($('#patient_id').val() != '') {
        var Fetchdata = {
            Dml_Indicator: "PS",
            patient_ID: $('#patient_id').val()
        }
    }
    else {
        var Fetchdata = {
            Dml_Indicator: "PS",
            patient_ID: $('#Hdnpatient_id').val() == "" ? $('#IPPatient_Id').val() : $('#Hdnpatient_id').val()
        }
    }

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

            }
            else {

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

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

                        if ((emp.ip_visit_report_id == "0" && emp.ip_admission_request_id == 2) || (emp.ip_visit_report_id == "0" && (emp.ip_admission_request_id == 1 && $('#OPVisitReport_Id').val() !="" ))) {

                            $("#ddBloodGroup").val(emp.patient_blood_group),
                            WardNo();
                            Allergies();
                            diagnosis();
                            Show_Billing(0);

                            if (emp.due_amount > 0) {
                                toastr.warning('Previous Visit due amount is ' + emp.due_amount);
                            }
                        }
                        else if (emp.ip_admission_request_id == 1 && $('#OPVisitReport_Id').val() == "") {
                            toastr.warning(' The Patient is transferred from OP to IP. Please go to IP Admission Request Screen <br/>  <br/> <a type="button" href="/Ipmanagement/Admission_Request" class="btn btn-xs btn-success">ok</a>');
                        }
                        else {
                            toastr.warning(' Patient Already admitted in IP <br/>  <br/> <a type="button" href="/Ipmanagement/admissionmangement" class="btn btn-xs btn-success">ok</a>');
                        }

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

function MultiOperationload() {
    $('.UPdisaple').addClass("disabled");
    diagnosis();

    var MultiOperation = {
        Dml_Indicator: "MOL",
        IP_visit_report_id: $('#IPVisitReport_Id').val()
    }

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

            }
            else {

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

                    //$('.UPdisaple').attr("disabled", true);

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

                        debugger;
                        $('#div_ip_Doctor_name').removeClass('hide');
                        $('#ip_Doctor_name').val(emp.ip_doctor_name);
                        $('#HdnadmDoctorid').val(emp.ip_doctor_id);
                        $("#ddDoctor").append('<option value="' + emp.ip_doctor_id + '"></option>')
                        //$("#ddDoctor").val(emp.ip_doctor_id),
                        $('#HdnSrequest_id').val(emp.surgery_request_id),
                        $('#HdnBranchid').val(emp.branch_id),
                        $('#txtRDoctorName').val(emp.ip_referral_doctor),
                        //$('#txtRDoctorName').prop('disabled', true),
                        //$('#txtRefPersonName').prop('disabled', true),
                        $("#ddBloodGroup").val(emp.patient_blood_group),
                        $("#txtCriticalScore").val(emp.ip_critical_score),
                        //$("#ddWardNo").append('<option value="' + emp.wardid + '">' + emp.WardName + '</option>'),
                        WardNo(emp.wardid);
                       // $("#ddWardNo").append(emp.wardid),
                        //$("#ddBedNumber").append('<option value="' + emp.bed_id + '">' + emp.bedcode + '</option>'),
                        LoadBed(emp.wardid, emp.bed_id);
                        $("#txtAdmitDate").val(emp.admit_date),
                        $("#txtAdmittime").val(emp.admit_time),
                        $("#HdnEntityid").val(emp.insurance_id),
                        $("#txtExpectedDurationDay").val(emp.expectedDurationStay),
                        $("#bloodproductrequire").val(emp.bloodProductRequirement),
                        $('a[data-toggle=bloodproductrequire][data-title="' + emp.bloodProductRequirement + '"]').removeClass('not-active');
                        $('a[data-toggle=bloodproductrequire][data-title="' + emp.bloodProductRequirement + '"]').addClass('active');
                        $("#txtinstructionsNurse").val(emp.instructionToNurse),
                        $("#provisional_diagnosis").val(emp.provisionalDiagnosis);
                        LoadSpeciality(emp.speciality);
                        if (emp.surgicalManagement == 1) {
                            $('#surgicalmanagement').prop('checked', true);
                        }
                        else {
                            $('#surgicalmanagement').prop('checked', false);
                        }
                        if (emp.medicalManagement == 1) {
                            $('#medicalmanagement').prop('checked', true);
                        }
                        else {
                            $('#medicalmanagement').prop('checked', false);
                        }

                        if (emp.others == 1) {
                            $('#others').prop('checked', true);
                        }
                        else {
                            $('#others').prop('checked', false);
                        }
         
                        $("#txtAnyInstructions").val(emp.anyOtherInstructions),
                        $("#nursingid").val(emp.nursingIdName),
                        $("#housekeepingid").val(emp.housekeepingIdName),
                        $("#nameGaurdian").val(emp.nameOfGaurdian),
                        $("#txtrelationship").val(emp.relationship),
                        $("#txtdetailsOfGaurdian").val(emp.detailsOfGaurdian),
                        $("#address").val(emp.address),

                       // $("#Hdn_tpa").val($(emp.Corporate_Insuranceid),

                        //$("#dd_BillingName").append('<option value="' + emp.billing_class + '">' + emp.master_service_name + '</option>'),
                        $('a[data-toggle=Entity][data-title="' + 0 + '"]').removeClass('active');
                        $('a[data-toggle=Entity][data-title="' + 0 + '"]').addClass('not-active');
                        $("#Entity").val(emp.is_entity),
                        $('a[data-toggle=Entity][data-title="' + emp.is_entity + '"]').removeClass('not-active');
                        $('a[data-toggle=Entity][data-title="' + emp.is_entity + '"]').addClass('active');
                        if (emp.is_entity == 1) {

                            $('#div_EntityType').show();
                            $('#divInsuranceName').show();
                            $('#divMultiPay').show();
                            $('#divdd_BillingName').hide();
                            $('.ClaimHEmployee').show();
                            Show_Billing(0);
                        }
                        else {
                            $('#divdd_BillingName').show();
                            $('#divInsuranceName').hide();
                            $('#div_EntityType').hide();
                            $('#divMultiPay').hide();
                            $('.ClaimHEmployee').hide();

                            Show_Billing(emp.billing_class);
                        }
                        $("#EntityType").val(emp.is_insurance),
                        $('a[data-toggle=EntityType][data-title="' + emp.is_insurance + '"]').removeClass('not-active');
                        $('a[data-toggle=EntityType][data-title="' + emp.is_insurance + '"]').addClass('active');
                        $('a[data-toggle=TypeOf_Admition][data-title="' + 2 + '"]').removeClass('active');
                        $('a[data-toggle=TypeOf_Admition][data-title="' + 2 + '"]').addClass('not-active');
                        $("#TypeOf_Admition").val(emp.type_of_admition),
                        $('a[data-toggle=TypeOf_Admition][data-title="' + emp.type_of_admition + '"]').removeClass('not-active');
                        $('a[data-toggle=TypeOf_Admition][data-title="' + emp.type_of_admition + '"]').addClass('active');

                        $('#txtEmployeeName').val(emp.employee_name);
                        $('#txtEmployeeCode').val(emp.employee_code);
                        $('#HdnRefDoctorid').val(emp.ip_referral_doctorid);
                        $('#txtRefPersonName').val(emp.referral_person_name);

                        if (emp.type_of_admition == 1 || emp.type_of_admition == 3) {
                            $('.div_surgery').addClass('hide');
                        }
                        else {
                            $('.div_surgery').removeClass('hide');
                        }
                        $('#IS_MLC').val(emp.is_mlc);
                        $('a[data-toggle=IS_MLC][data-title="' + emp.is_mlc + '"]').removeClass('not-active');
                        $('a[data-toggle=IS_MLC][data-title="' + emp.is_mlc + '"]').addClass('active');
                        $('#txtMLCNo').val(emp.mlc_no);

                        if (emp.is_mlc == 1) {
                            $('#div_MLCNo').removeClass('hide');
                        }
                        else {
                            $('#div_MLCNo').addClass('hide');
                        }
                        $('#TypeOf_Surgery').val(emp.is_package);
                        $('a[data-toggle=TypeOf_Surgery][data-title="' + emp.is_package + '"]').removeClass('not-active');
                        $('a[data-toggle=TypeOf_Surgery][data-title="' + emp.is_package + '"]').addClass('active');

                        $('#photolog').empty();
                        if (emp.ip_upload_file != null && emp.ip_upload_file != "") {
                            $('#photolog').show();
                            $('#photolog').append('<a href="' + $('#hdnSCDfilepath1').val() + "/" + $('#HospitalId').val() + "/" + emp.branch_id + "/" + "IPAdmitPatient/" + emp.ip_upload_file + '" target="_blank">View</a>');
                            $('#idpathvalue').val(emp.ip_upload_file);
                        }

                        //if (emp.is_insurance == 2)
                        //{
                        //    $('#divMultiPay').show();
                        //}
                        //else {
                        //    $('#divMultiPay').hide();
                        //}

                        $('#CMultiPay').prop("checked", emp.is_MultiPay);

                        if (emp.is_insurance == 1) {
                            $('#CIM_Name').html('TPA Name <span class="red">*</span>');
                        }
                        else if (emp.is_insurance == 2) {
                            $('#CIM_Name').html('Insurance Name <span class="red">*</span>');
                        }

                        if (emp.is_MultiPay == 1)
                        {
                            $('#divMPCIName').show();
                          //  Corporate_Insurance(emp.insurance_id, emp.Corporate_Insuranceid);
                        }
                        else
                        {
                            $('#divMPCIName').hide();
                        }

                        $('#DocSig_Upload_photolog').empty();
                        if (emp.Doctor_signature != null && emp.Doctor_signature != "") {
                            $('#DocSig_Upload_photolog').show();
                            $('#DocSig_Upload_photolog').append('<a href="' + $('#hdnSCDfilepath1').val() + "/" + $('#HospitalId').val() + "/" + emp.branch_id + "/" + "IPAdmitPatient/" + emp.Doctor_signature + '" target="_blank">View</a>');
                            $('#DocSig_Upload_Path').val(emp.Doctor_signature);
                        }

                        $('#NurSig_Upload_photolog').empty();
                        if (emp.Nurse_signature != null && emp.Nurse_signature != "") {
                            $('#NurSig_Upload_photolog').show();
                            $('#NurSig_Upload_photolog').append('<a href="' + $('#hdnSCDfilepath1').val() + "/" + $('#HospitalId').val() + "/" + emp.branch_id + "/" + "IPAdmitPatient/" + emp.Nurse_signature + '" target="_blank">View</a>');
                            $('#NurSig_Upload_Path').val(emp.Nurse_signature);
                        }

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

}

// Patient search End//

$('#btnSubmit').click(function () {
    debugger;
    //if (($.trim($('#txtRDoctorName').val()) == "") || ($.trim($('#HdnRefDoctorid').val()) == "")) {
    //    $('#PtxtRDoctorName').show();
    //    $('#PtxtRDoctorName').fadeOut(8000);
    //    $('#PtxtRDoctorName').html('Enter Referral Doctor Name');
    //    $('#txtRDoctorName').focus();
    //    //$('#txtRDoctorName').val();
    //    return false;
    //}

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

    if ($.trim($('#ddBedNumber').val()) == 0) {
        $('#PddBedNumber').show();
        $('#PddBedNumber').fadeOut(8000);
        $('#PddBedNumber').html('Select Bed');
        $('#ddBedNumber').focus();
        return false;
    }
    if ($.trim($('#txtAdmitDate').val()) == '') {
        $('#PtxtAdmitDate').show();
        $('#PtxtAdmitDate').fadeOut(8000);
        $('#PtxtAdmitDate').html('Select Admit Date');
        $('#txtAdmitDate').focus();
        return false;
    }

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

        if ($.trim($('#ip_Doctor_name').val()) == "") {
            $('#Pip_Doctor_name').show();
            $('#Pip_Doctor_name').fadeOut(8000);
            $('#Pip_Doctor_name').html('Please Select Doctor');
            return false;
        }
        if ($.trim($('#HdnadmDoctorid').val()) == "") {
            $('#Pip_Doctor_name').show();
            $('#Pip_Doctor_name').fadeOut(8000);
            $('#Pip_Doctor_name').html('Please Select Doctor');
            return false;
        }

    }

    

    if ($.trim($('#Entity').val()) == 1) {
        if ($.trim($('#EntityType').val()) == '') {
            $('#PEntityType').show();
            $('#PEntityType').fadeOut(8000);
            $('#PEntityType').html('Select Claim Type');
            //$('#ddInsuranceName').focus();
            return false;
        }
    }

    if ($.trim($('#EntityType').val()) != '') {
        if ($.trim($('#HdnEntityid').val()) == '') {
            $('#PddInsuranceName').show();
            $('#PddInsuranceName').fadeOut(8000);
            $('#PddInsuranceName').html('Select claim Name');
            $('#ddInsuranceName').focus();
            return false;
        }
    }

    if ($('#CMultiPay').prop('checked') == true) {
        if ($.trim($('#MPCIName').val()) == '') {
            $('#PMPCIName').show();
            $('#PMPCIName').fadeOut(8000);

            if (parseInt($('#EntityType').val()) == 1) {
                $('#PMPCIName').html('Select TPA Name');
            }
            else if (parseInt($('#EntityType').val()) == 2) {
                $('#PMPCIName').html('Select Insurance Name');
            }
            
            $('#MPCIName').focus();
            return false;
        }
    }

    if ($.trim($('#Entity').val()) == 0) {
        if ($.trim($('#dd_BillingName').val()) == 0) {
            $('#Pdd_BillingName').show();
            $('#Pdd_BillingName').fadeOut(8000);
            $('#Pdd_BillingName').html('Select Billing Name');
            $('#dd_BillingName').focus();
            return false;
        }
    }

    if ($('#TypeOf_Admition').val() == '') {
        $('#PTypeOf_Admition').show();
        $('#PTypeOf_Admition').fadeOut(8000);
        $('#PTypeOf_Admition').html('Select Type Of Admition');
        $('#TypeOf_Admition').focus();
        return false;
    }

    if (parseInt($('#TypeOf_Admition').val()) == 2) {
        if ($.trim($('#TypeOf_Surgery').val()) == "") {
            $('#PTypeOf_Surgery').show();
            $('#PTypeOf_Surgery').fadeOut(8000);
            $('#PTypeOf_Surgery').html('Select Type Of Surgery');
            $('#TypeOf_Surgery').focus();
            return false;
        }

        if ($.trim($('#ddsurgery').val()) == "" || $.trim($('#ddsurgery').val()) == "0") {
            $('#Pddsurgery').show();
            $('#Pddsurgery').fadeOut(8000);
            $('#Pddsurgery').html('Select surgery');
            $('#ddsurgery').focus();
            return false;
        }
    }

    if ($.trim($('#IS_MLC').val()) == 1) {
        if ($.trim($('#txtMLCNo').val()) == "") {
            $('#PtxtMLCNo').show();
            $('#PtxtMLCNo').fadeOut(8000);
            $('#PtxtMLCNo').html('Enter MLC Number');
            $('#txtMLCNo').focus();
            return false;
        }
    }

    var MultiOperationID = $('#ddsurgery').val();
    var OperationID = "";

    for (var i = 0; i < MultiOperationID.length; i++) {
        if (OperationID == "") {
            OperationID = MultiOperationID[i];
        }
        else {
            OperationID = OperationID + "," + MultiOperationID[i];
        }

    }

    var ADT = $('#txtAdmitDate').val();
    if (ADT == '') {
        ADT = '';
    }
    else {
        var a = ADT.split('/');
        ADT = a[2] + '-' + a[1] + '-' + a[0];
    }

    var time = $("#txtAdmittime").val();
    var ATM = moment(time, 'hh:mm A').format('HH:mm');
    var MedicalManagement
    if ($("#medicalmanagement").prop("checked")) {
        MedicalManagement = 1;
    } else {
        MedicalManagement = 0
    }
    var SurgicalManagement
    if ($("#surgicalmanagement").prop("checked")) {
        SurgicalManagement = 1;
    } else {
        SurgicalManagement = 0
    }
    var Others
    if ($("#others").prop("checked")) {
        Others = 1;
    } else {
        Others = 0
    }

    var Admitdata = {
        Dml_Indicator: "I",
        patient_ID: $('#Hdnpatient_id').val() == "" ? $('#IPPatient_Id').val() : $('#Hdnpatient_id').val(),
        blood_group: $('#ddBloodGroup').val(),
        diagnosis: $('#txtdiagnosis').val(),
        critical_score: $('#txtCriticalScore').val(),
        ward_no: $('#ddWardNo').val(),
        bed_number: $('#ddBedNumber').val(),
        ip_surgery_type: OperationID,
        ip_doctor_id: $('#HdnadmDoctorid').val() == "" || $('#HdnadmDoctorid').val() == null ? $('#doctorId').val() : $('#HdnadmDoctorid').val(),
       // ip_doctor_id: $('#ddDoctor').val() == "" || $('#ddDoctor').val() == null ? $('#doctorId').val() : $('#ddDoctor').val(),
        IP_visit_report_id: $('#IPVisitReport_Id').val(),
        ip_patient_admitdate: ADT + " " + ATM,
        is_insurance: $('#EntityType').val(),
        insurance_id: $('#HdnEntityid').val(),
        billing_class: $('#dd_BillingName').val(),
        branchid: $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').val(),
        type_of_admition: $('#TypeOf_Admition').val(),
        surgery_request_id: $('#HdnSrequest_id').val(),
        ip_referral_doctor: $('#txtRDoctorName').val(),
        is_entity: $('#Entity').val(),
        is_mlc: $('#IS_MLC').val(),
        mlc_no: $('#txtMLCNo').val(),
        is_package: $('#TypeOf_Surgery').val(),
        ip_upload_file: $('#idpathvalue').val(),
        op_visit_report_id: $('#OPVisitReport_Id').val(),
        is_MultiPay: ($('#CMultiPay').prop('checked') == true) ? "1" : "0",
        Corporate_Insuranceid: $('#Hdn_tpa').val(),
        employee_name: $('#txtEmployeeName').val(),
        employee_code: $('#txtEmployeeCode').val(),
        ip_referral_doctorid: $('#HdnRefDoctorid').val(),
        referral_person_name: $('#txtRefPersonName').val(),
        Doctor_signature: $('#DocSig_Upload_Path').val(),
        Nurse_signature: $('#NurSig_Upload_Path').val(),
        expectedDurationStay: $('#txtExpectedDurationDay').val(),
        bloodProductRequirement: $('#bloodrequirement').val(),
        speciality: $('#speciality').val(),
        medicalManagement: MedicalManagement,
        surgicalManagement: SurgicalManagement,
        others: Others,
        provisionalDiagnosis: $('#provisional_diagnosis').val(),
        instructionToNurse: $('#txtinstructionsNurse').val(),
        anyOtherInstructions: $('#txtAnyInstructions').val(),
        nursingIdName: $('#nursingid').val(),
        housekeepingIdName: $('#housekeepingid').val(),
        nameOfGaurdian: $('#nameGaurdian').val(),
        relationship: $('#txtrelationship').val(),
        detailsOfGaurdian: $('#txtdetailsOfGaurdian').val(),
        address: $('#address').val()
    }

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

            }
            else {

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

                    if ($("#HBtnSaveUpdate").val() == "Update") {
                        toastr.success(' Patient Details Updated Successfully ');
                        setTimeout(function () {
                            window.location.href = "/Ipmanagement/admissionmangement/";
                        }, 2000);
                  

                    }
                    else {
                        toastr.success(' Patient Admitted Successfully');
                        setTimeout(function () {
                            window.location.href = "/Ipmanagement/admissionmangement/";
                        }, 2000);
                        //toastr.success(' Patient Admitted Successfully <br/>  <br/> <a type="button" href="/Ipmanagement/admissionmangement/" class="btn btn-xs btn-success">ok</a>');
                    }

                    //window.location = "/Ipmanagement/admissionmangement";
                }
                else {
                    console.log(data);
                }

            }
        }
    });
});


function transfertoipfetch() {
    debugger;
    var transfertoip = {
        Dml_Indicator: 'TTIP',
        IP_visit_report_id: ($('#OPVisitReport_Id').val() !== '') ? $('#OPVisitReport_Id').val() : $('#IPVisitReport_Id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/AdmitPatient_Ins_Upd_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(transfertoip),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data;
            $("#txtExpectedDurationDay").val(emp[0].expectedDurationStay);
            $("#bloodproductrequire").val(emp[0].bloodProductRequirement);
            $('a[data-toggle=bloodproductrequire][data-title="' + emp[0].bloodProductRequirement + '"]').removeClass('not-active');
            $('a[data-toggle=bloodproductrequire][data-title="' + emp[0].bloodProductRequirement + '"]').addClass('active');
            $("#txtinstructionsNurse").val(emp[0].instructionToNurse);
            $("#txtAnyInstructions").val(emp[0].anyOtherInstructions);
            $("#provisional_diagnosis").val(emp[0].provisionalDiagnosis);
            $('#HdnRefDoctorid').val(emp[0].doctor_user_id);
            $('#txtRDoctorName').val(emp[0].doctorname);
            LoadSpeciality(emp[0].speciality);
            if (emp[0].surgicalManagement == 1) {
                $('#surgicalmanagement').prop('checked', true);
            }
            else {
                $('#surgicalmanagement').prop('checked', false);
            }
            if (emp[0].medicalManagement == 1) {
                $('#medicalmanagement').prop('checked', true);
            }
            else {
                $('#medicalmanagement').prop('checked', false);
            }

            if (emp[0].others == 1) {
                $('#others').prop('checked', true);
            }
            else {
                $('#others').prop('checked', false);
            }



        }

    })
}

function LoadSpeciality(spec) {
    debugger;
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetDoctorSpeciality',
        contentType: 'application/json; charset=UTF-8',
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1)
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var speciality = '', default_opt = '';
                    $('#speciality').empty();
                    default_opt = '<option value="0">--Select--</option>'
                    $.each(data1, function (i, emp) {
                        speciality = speciality + '<option value="' + emp.doctor_speciality_id + '">' + emp.doctor_speciality_name + '</option>';
                    });
                    $('#speciality').append(default_opt + speciality);
                    if (speciality != '' || speciality != null) {
                        $('#speciality').val(spec)
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

function diagonsislist() {
    var complaints_master_list = {
        Dml_Indicator: 'DLIST',
        IP_visit_report_id: $('#IPVisitReport_Id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/AdmitPatient_Ins_Upd_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(complaints_master_list),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

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

                    if (data.length > 0) {
                        console.log(data);
                        for (var i = 0; i < data.length; i++) {
                            var diagnosis = '';
                            if (data[i].ip_diagnosis != '' && data[i].ip_diagnosis != null) {
                                diagnosis = data[i].ip_diagnosis;
                                $('#txtdiagnosis').tagEditor('addTag', diagnosis);
                            }
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function diagnosis() {
    var PatientData = {
        Dml_Indicator: '1',
        Doctor_id: $('#HiddenDoctorID').val()
    }

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

            }
            else {

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

                    if (data.Table9.length > 0) {
                        var diagnosisVal = [];
                        for (var i = 0; i < data.Table9.length; i++) {
                            diagnosisVal.push(data.Table9[i].diagnosis);
                        }
                        $('#txtdiagnosis').tagEditor({
                            delimiter: ',',
                            initialTags: [],
                            placeholder: '',
                            maxLength: 250,
                            autocomplete: {
                                delay: 0,
                                position: {
                                    collision: 'flip'
                                },
                                source: diagnosisVal
                            },
                            clickDelete: false,
                            beforeTagSave: beforeTagSavecb,
                            beforeTagDelete: beforeTagDeletecb,
                            onChange: onChangecb
                        });

                        function onChangecb(field, editor, tags) {
                        }
                        function beforeTagSavecb(field, editor, tags, tag, val) {
                            //diagnosis_insert(val);
                        }
                        function beforeTagDeletecb(field, editor, tags, val) {
                            return true;
                        }
                        $('#divtxtdiagnosis > ul').append('<li style="width:1px" class="ui-sortable-handle">&nbsp;</li>');

                        if ($('#IPVisitReport_Id').val() != "") {
                            diagonsislist();
                        }

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


            }
        }
    });
}

function WardNo(wardid) {
    debugger;
    var dml = '';
    if (wardid != 0 && wardid != null && wardid != "") {
        dml = 'EDWN';
    }
    else
    {
        dml = 'WN';
    }
    var Warddata = {
        Dml_Indicator: dml,
        branchid: $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').val(),
        IP_visit_report_id: $('#IPVisitReport_Id').val()
    }

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

            }
            else {

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

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

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

                    });
                    $('#ddWardNo').append(default_opt + WardNo);

                    if (wardid != 0 && wardid != null && wardid != "") {
                        $('#ddWardNo').val(wardid);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function LoadOperation() {

    var branchid = '', DML = '';

    if ($('#SelBranch').val() == null || $('#SelBranch').val() == '') {
        branchid = $('#HdnBranchid').val();
    }
    else {
        branchid = $('#SelBranch').val();
    }

    if ($('#TypeOf_Surgery').val() == 1) {
        DML = 'POPD';
    }
    else {
        DML = 'SOPD';
    }



    var Warddata = {
        Dml_Indicator: DML,
        branchid: branchid == "" ? $('#hBack_branchid').val() : branchid
    }

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

            }
            else {

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

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

                        operation = operation + '<option value="' + emp.ip_operation_id + '">' + emp.ip_operation_name + '</option>';

                    });
                    $('#ddsurgery').append(default_opt + operation);

                    if ($('#IPVisitReport_Id').val() != "") {
                        LoadMulSurgery();
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

$('#ddWardNo').change(function () {
    $("#ddBedNumber").html("");

    LoadBed($("#ddWardNo").val(),0)
});

function LoadBed(wardid,bedid) {

    var dml = '';
    if ((bedid != 0 && bedid != null && bedid != "") || ($('#IPVisitReport_Id').val() != null && $('#IPVisitReport_Id').val()!="")) {
        dml = 'EDBN';
    }
    else {
        dml = 'BN';
    }

    var Beddata = {
        Dml_Indicator: dml,
        ward_no: wardid,
        IP_visit_report_id: $('#IPVisitReport_Id').val()
    }

    $.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))) {
                toastr.warning('Bed is Unavailable, Please Select another Ward');
            }
            else {

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

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

                        BedName = BedName + '<option value="' + emp.bedid + '">' + emp.Bed_Name + '</option>';

                    });
                    $('#ddBedNumber').append(default_opt + BedName);

                    if (bedid != 0 && bedid != null && bedid != "") {
                        $('#ddBedNumber').val(bedid);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}


// Allergies Start//


$('.btn_allergies').click(function () {

    var Patient_Id = "";

    if ($('#Hdnpatient_id').val() == "") {
        Patient_Id = $('#IPPatient_Id').val();
    }
    else {
        Patient_Id = $('#Hdnpatient_id').val();
    }

    if ($.trim($('.txtallergies').val()) != "") {
        var PatientData = {
            Patient_id: Patient_Id,
            allergy_display: $('.txtallergies').val(),
            Dml_Indicator: 'AI',
            allergy_type: 1
        }

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

                }
                else {

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

                        Allergies();
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
        $('.txtallergies').val('');
        $('.add_allergies').removeClass('hide');
        $('.allergies_inp_block').addClass('hide');
    }
    else {
        $('.txtallergies').val('');
        $('.add_allergies').removeClass('hide');
        $('.allergies_inp_block').addClass('hide');
    }
});


$('.add_allergies').click(function () {
    $('.allergies_inp_block').removeClass('hide');
    $(this).addClass('hide');
});

function Allergies() {
    debugger
    var Patient_Id = "";

    if ($('#Hdnpatient_id').val() == "") {
        Patient_Id = $('#IPPatient_Id').val();
    }
    else {
        Patient_Id = $('#Hdnpatient_id').val();
    }
    var PatientData = {
        Patient_id: Patient_Id,
        Dml_Indicator: 'DS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Allergy_Ins_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    $('.divallergies').empty();
                    $('.divallergiess').empty();
                    var tr = '', li = '';
                    if (data.length > 0) {

                        for (var i = 0; i < data.length; i++) {
                            tr = tr + '<span class="btn btn-default  btn-xs btn-primary-bordered floated_close">' + data[i].allergy_display + '<span class="float_close_icon" onclick=delallergy("' + data[i].allergy_id + '")><i class="fa fa-times" aria-hidden="true"></i></span></span>';
                            if (i == 0) {
                                li = li + '<li>' + data[i].allergy_display + '</li>';
                            }
                            else {
                                li = li + '<li> | ' + data[i].allergy_display + '</li>';
                            }
                        }
                        $('.divallergies').append(tr);
                        $('.divallergiess').append(li);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

$('.txtallergies').autocomplete({
    source: function (request, response) {

        $.ajax({
            async: true,
            url: "/CaseStudy/AutoCompleteData?allergies=" + $('.txtallergies').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term },
            success: function (data) {

                var data2 = data;
                //var data2 = JSON.parse(data1.data);
                response($.map(data2, function (item) {
                    return { label: item.allergy_display, value: item.allergy_display };
                }))
            }
        })
    }
});

function delallergy(id) {
    debugger
    var Patient_Id = "";

    if ($('#Hdnpatient_id').val() == "") {
        Patient_Id = $('#IPPatient_Id').val();
    }
    else {
        Patient_Id = $('#Hdnpatient_id').val();
    }
    var PatientData = {
        Patient_id: Patient_Id,
        allergy_id: id,
        Dml_Indicator: 'D'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Allergy_Ins_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientData),
        success: function (data) {
            Allergies();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {
            }
        }
    });
}

// Allergies End//

//Multi Operation Load //

function LoadMulSurgery() {

    var MultiOperation = {
        Dml_Indicator: "MSL",
        IP_visit_report_id: $('#IPVisitReport_Id').val()
    }

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

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

                    if ($('#ddsurgery').select2() != null)
                        $('#ddsurgery').select2('destroy');

                    var abc = "";
                    $.each(data1, function (i, emp) {
                        abc = abc + '<li class="select2-selection__choice" title="' + emp.ip_operation_name + '"><span class="select2-selection__choice__remove" role="presentation">×</span>' + emp.ip_operation_name + '</li>';

                        $('#ddsurgery option').each(function (index, value) {

                            if (emp.ip_operation_name == value.innerText) {
                                $(this).prop("selected", true);
                            }
                        });
                    });
                    $('ul.select2-selection__rendered').append(abc);
                    $('#ddsurgery').select2();

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


$('.select2 - selection__choice__remove').click(function () {

    var triggeredLIElement = $(this).parent();
    triggeredLIElement.remove();
});

function Show_Insurance() {

    var Insurancedata = {
        Dml_Indicator: 'IDS',
        branchid: $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').val()

    }

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

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

            }
            else {

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

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

                        Insurance = Insurance + '<option value="' + emp.master_entity_id + '">' + emp.entity_name + '</option>';

                    });
                    $('#ddInsuranceName').append(default_opt + Insurance);

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

}

function Show_Billing(bill_no) {

    var Billingata = {
        Dml_Indicator: 'BDS',
        //branchid: $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').val() //Medway all branch concept

    }

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

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

            }
            else {

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

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

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

                    });
                    $('#dd_BillingName').append(default_opt + Billing);

                    if(bill_no!='' || bill_no!=0)
                    {
                        $('#dd_BillingName').val(bill_no);
                    }

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

}

$('#ddInsuranceName').autocomplete({

    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Ipmanagement/AutoEntity',
            type: "POST",
            dataType: "json",
            //data: { Prefix: request.term, is_insurance: $('#EntityType').val(), entity_name: $('#ddInsuranceName').val(), branchid: $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').val() },//Medway all branch concept
            data: { Prefix: request.term, is_insurance: $('#EntityType').val(), entity_name: $('#ddInsuranceName').val()},
            success: function (data) {

                console.log(data);
                var data2 = JSON.parse(data);
                var data = data2.data;
                response($.map(data, function (item) {
                    return { label: item.entity_name, value: item.entity_name, id: item.master_entity_id };
                }))

            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#HdnEntityid').val(ui.item.id);
      //  Corporate_Insurance($('#HdnEntityid').val(), 0);
        $('#ddsurgery').val('').change();
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }

});

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

    if ($('#ddWardNo').val() == 0 || $('#ddBedNumber').val() == 0) {
        toastr.warning('Please Select the Ward and Bed');
        $("#ddsurgery option:selected").prop("selected", false);
        return false;
    }

    if ($.trim($('#Entity').val()) == 1) {
        if ($.trim($('#EntityType').val()) == '') {
            $('#PEntityType').show();
            $('#PEntityType').fadeOut(8000);
            $('#PEntityType').html('Select Claim Type');
            //$('#ddInsuranceName').focus();
            $("#ddsurgery option:selected").prop("selected", false);
            return false;
        }
    }

    if ($.trim($('#EntityType').val()) != '') {
        if ($.trim($('#HdnEntityid').val()) == '') {
            $('#PddInsuranceName').show();
            $('#PddInsuranceName').fadeOut(8000);
            $('#PddInsuranceName').html('Select claim Name');
            $('#ddInsuranceName').focus();
            $("#ddsurgery option:selected").prop("selected", false);
            return false;
        }
    }

    if ($.trim($('#Entity').val()) == 0) {
        if ($.trim($('#dd_BillingName').val()) == 0) {
            $('#Pdd_BillingName').show();
            $('#Pdd_BillingName').fadeOut(8000);
            $('#Pdd_BillingName').html('Select Billing Name');
            $('#dd_BillingName').focus();
            $("#ddsurgery option:selected").prop("selected", false);
            return false;
        }
    }

    if ($('#CMultiPay').prop('checked') == true) {
        if ($.trim($('#MPCIName').val()) == '') {
            $('#PMPCIName').show();
            $('#PMPCIName').fadeOut(8000);
            $('#PMPCIName').html('Select Insurance Name');
            $('#MPCIName').focus();
            return false;
        }
    }

    var MultiOperationID = $('#ddsurgery').val();
    var operationlength = MultiOperationID.length;
    var LastOperationid = operationlength - 1;
    var OperationID = "";

    OperationID = MultiOperationID[LastOperationid];





    var MultiOperation = {
        Dml_Indicator: "SPVC",
        ip_surgery_type: OperationID,
        ward_no: $('#ddWardNo').val(),
        is_insurance: $('#EntityType').val(),
        insurance_id: $('#HdnEntityid').val(),
        billing_class: $('#dd_BillingName').val(),
        branchid: $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').val(),
        is_MultiPay: ($('#CMultiPay').prop('checked') == true) ? "1" : "0",
        Corporate_Insuranceid: $('#Hdn_tpa').val()

    }

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

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

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

                        debugger;
                        if (emp.price_matrix_operation == 'NoPriceMatrix') {

                            $("#ddsurgery option[value='" + OperationID + "']").remove()
                            toastr.warning('Please Kindly set the price matrix for ' + emp.ip_operation_name + ' Surgery.');
                        }

                    });



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

});

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

function packageimageupload() {
    debugger;
    var uploadpath = $('#fileToUpload').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $("#fileToUpload").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        var Branchid = $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').val()
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }
        fileData.append('username', 'Manas');
        $.ajax({
            url: '/Ipmanagement/UploadPhotoFiles?branch_id=' + Branchid,
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success: function (result) {
                $.each(result, function (i, emp) {
                    debugger;
                    $('#photolog').empty();
                    $('#photolog').show();
                    $('#idpathvalue').val(emp);
                    $('#photolog').append('<a href="' + $('#hdnSCDfilepath1').val() + "/" + $('#HospitalId').val() + "/" + Branchid + "/" + "IPAdmitPatient/" + emp + '" target="_blank">View</a>');
                });
            }
        });
    }
}

$('#TypeOf_Surgery').change(function () {
    LoadOperation();
});

$("#dd_BillingName").change(function () {
    $('#ddsurgery').val('').change();
});

$('#CMultiPay').click(function () {
    debugger;
    var EntityType = $('#EntityType').val();
    if (EntityType == 1) {
        $('#CIM_Name').html('TPA Name <span class="red">*</span>');
    }
    else if (EntityType == 2) {
        $('#CIM_Name').html('Insurance Name <span class="red">*</span>');
    }

    if($('#CMultiPay').prop('checked')==true)
    {
        $('#divMPCIName').show();
        $('#MPCIName').val('');
    }
    else
    {
        $('#divMPCIName').hide();
        $('#MPCIName').val('');
    }

    if ($('#MPCIName').append().val() == null || $('#MPCIName').append().val() == '')
    {
      //  Corporate_Insurance($('#HdnEntityid').val(), 0);
    }
});

function Corporate_Insurance(Corporateid,CIid) {

    var dml = '', EntityType = $('#EntityType').val();

    if (EntityType == 1)
    {
        dml='ITPA'
    }
    else if (EntityType == 2) {
        dml = 'CIN'
    }

    var Billingata = {
        Dml_Indicator: dml,
        insurance_id: Corporateid

    }

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

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

            }
            else {

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

                    var CInsurance;

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

                        CInsurance = CInsurance + '<option value="' + emp.master_entity_billing_id + '">' + emp.entity_name + '</option>';

                    });
                    $('#MPCIName').append(default_opt + CInsurance);

                    if (CIid != '' || CIid != 0) {
                        $('#MPCIName').val(CIid);
                    }

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

}

$('#BtnReferal').click(function () {
    ClearReferral();
    $('#Referral_Doctor_Details').modal('show');
    
});

function LoadRefBranch() {

    var subdepartment = {

        Dml_Indicator: "LBRAN"

    }

    $.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);
            $('#branch').empty();
            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.Table, function (i, emp) {

                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';

                    });
                    if (data1.Table.length == 1) {

                        $('#branch').append(SubDepartment);
                        LoadDepartment();
                    }
                    else {

                        $('#branch').append(default_opt + SubDepartment);
                    }
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#branch').val($('#HospitalBranchID').val());
                        $('#branch').attr('disabled', true);
                        LoadDepartment();
                       $('#Department').val('').change();
                    }
                }

            }

            else {

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

$("#branch").change(function () {
    debugger;

    LoadDepartment();
    $('#Department').val('').change();
});

//Used for Loading the Departments in Hospital for both in Doctorcreation and in EditProfile
function LoadDepartment() {
    var department = {
        Dml_Indicator: "DP",
        branch_id: $('#branch').val(),
        name: $('#DoctorUser_Id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(department),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1)
                $('#SubDepartemnt').empty();
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    $('#Department').html('');
                    $('#Department').val('');
                    var Department;
                    var default_opt = '<option value="0" disabled>--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        Department = Department + '<option value="' + emp.master_category_department_id + '">' + emp.name + '</option>';
                    });
                    $('#Department').append(Department);
                    $('#Department_Single').append(default_opt + Department);
                    $('#Department').prop('multiple', false);
                    $('#Department').val('').change();
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

//Used for Loading the Sub Department DropDown in Doctor Creation and in edit profile
$("#Department").change(function () {
    debugger;
    document.getElementById("SubDepartemnt").innerHTML = null;

    var condition = '(', dep_length = 0;

        condition = condition + 'master_category_department_id=' + $('#Department').val()
    
    condition=condition+') and status=1'
    console.log(condition);

    var subdepartment = {
        Dml_Indicator: "SDM",
        condition: condition,
        name: $('#DoctorUser_Id').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 {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.sub_category_department_id + '">' + emp.sub_cd_name + '</option>';
                    });
                    $('#SubDepartemnt').html(SubDepartment);
                    $('#Subdepartment_Single').append(default_opt + SubDepartment);

                    $('#SubDepartemnt').prop('multiple', false);

                    $('#SubDepartemnt').val('').change();
                }
            }
            else {
                console.log(data1);
            }
        }
    });
});

$('#ReferralSubmit').click(function () {
    DoctorCreation_insert();
});

//Inserting Doctor and User
function DoctorCreation_insert() {
    var DoctorName = $("#txtDoctorName").val();
    var department_id = $('#Department').val().toString();
    var subdepartment_id = $('#SubDepartemnt').val().toString();
    var branchid = $('#branch').val();
    var role = 1;

    indicator_id = 'REFI'

    var a = "";

    if ($.trim(branchid) == "" || $.trim(branchid) == "0") {
        $('#PSelectDoctorbranch').show();
        $('#PSelectDoctorbranch').fadeOut(8000);
        $('#PSelectDoctorbranch').html('Select Branch');
        $('#branch').val('');
        $('#branch').focus();
        return false;
    }


    if ($.trim($('#Department').val()) == "" || $.trim($('#Department').val()) == "0") {
        $('#PDepartment').show();
        $('#PDepartment').fadeOut(8000);
        $('#PDepartment').html('Select Department');
        $('#Department').val('');
        $('#Department').focus();
        return false;
    }
    if ($.trim($('#SubDepartemnt').val()) == "" || $.trim($('#SubDepartemnt').val()) == "0") {
        $('#PSubDepartemnt').show();
        $('#PSubDepartemnt').fadeOut(8000);
        $('#PSubDepartemnt').html('Select SubDepartment');
        $('#SubDepartemnt').val('');
        $('#SubDepartemnt').focus();
        return false;
    }

    if ($.trim(DoctorName) == "") {
        $('#PtxtDoctorName').show();
        $('#PtxtDoctorName').fadeOut(8000);
        $('#PtxtDoctorName').html('Enter Name');
        $('#txtDoctorName').val('');
        $('#txtDoctorName').focus();
        return false;
    }
    if ($.trim(DoctorName).length < "2") {
        $('#PtxtDoctorName').show();
        $('#PtxtDoctorName').fadeOut(8000);
        $('#PtxtDoctorName').html('Enter Name minimum of two Charater');
        $('#txtDoctorName').val('');
        $('#txtDoctorName').focus();
        return false;
    }


    if ($('#txtPMobileNumber').val() == "") {
        $('#PtxtPMobileNumber').show();
        $('#PtxtPMobileNumber').fadeOut(8000);
        $('#PtxtPMobileNumber').html('Enter Mobile Number');
        $('#txtPMobileNumber').val('');
        $('#txtPMobileNumber').focus();
        return false;
    }
    if ($('#txtPMobileNumber').val() != "" && $('#txtPMobileNumber').val().length != "10") {
        $('#PtxtPMobileNumber').show();
        $('#PtxtPMobileNumber').fadeOut(8000);
        $('#PtxtPMobileNumber').html('Invaild Mobile Number');
        $('#txtPMobileNumber').val('');
        $('#txtPMobileNumber').focus();
        return false;
    }

    var DoctorId = $('#HiddenDoctorID').val();

    var DoctorUpdationData = {
        doctor_id: DoctorId,
        doctor_name: $("#txtDoctorName").val(),
        mobile_number_one: $("#txtPMobileNumber").val(),
        email_id: $("#txtPEmailID").val(),
        Dml_Indicator: indicator_id,
        hospital_id: $('#HospitalId').val(),
        department: department_id,
        subdepartment: subdepartment_id,
        branch_id: branchid,
        user_role_id: role,
        doctor_type:2
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/DoctorUpdation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorUpdationData),
        success: function (data) {
            
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.length > 0) {
                        
                        if (data[0].StringResult == "failure") {
                            $('#PtxtPMobileNumber').show();
                            $('#PtxtPMobileNumber').fadeOut(8000);
                            $('#PtxtPMobileNumber').html('Mobile Number already exist');
                            $('#txtPMobileNumber').val('');
                            $('#txtPMobileNumber').focus();

                        }
                        else if (data[0].StringResult == "already exist") {
                            $('#PtxtPEmailID').show();
                            $('#PtxtPEmailID').fadeOut(8000);
                            $('#PtxtPEmailID').html('Email id already exist');
                            $('#txtPEmailID').val('');
                            $('#txtPEmailID').focus();

                        }

                        else {
                            toastr.success('Referral Doctor Created Successfully');
                            
                            ClearReferral();
                        }
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function ClearReferral()
{
    $("#txtDoctorName").val('');
    $("#txtPMobileNumber").val('');
    $("#txtPEmailID").val('');
    $('#Department').val('').change();
    $('#SubDepartemnt').val('').change();

    if (parseInt($('#hiddenRole_id')) == 2) {
        $("#branch").val("0");
    }

}





// TPA autocomplete

$('#MPCIName').autocomplete({
    
    source: function (request, response) {
        debugger;
        var dml = '', EntityType = $('#EntityType').val();

        if (EntityType == 1) {
            dml = 'ITPA'
        }
        else if (EntityType == 2) {
            dml = 'CIN'
        }
        $.ajax({          
            async: true,
            url: '/Ipmanagement/Autocomplete_tpa?PName=' + $('#MPCIName').val() + '',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: dml, insurance_id: $('#HdnEntityid').val() },
            success: function (data) {
                debugger;
                var data2 = data;
                response($.map(data2, function (item) {
                    
                    return { label: item.entity_name, value: item.entity_name, id: item.User_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#Hdn_tpa').val(ui.item.id);
        $('#Hdn_tpaname').val(ui.item.value);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});



$('.ip_doctor_name').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HDL", branch_id: $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').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) {
        debugger;
        $('#HdnadmDoctorid').val('');
        $('#HdnadmDoctorid').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

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

function DoctorSingupload() {
    debugger;
    var uploadpath = $('#DocSig_Upload').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $("#DocSig_Upload").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        var Branchid = $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').val()
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }
        fileData.append('username', 'Manas');
        $.ajax({
            url: '/Ipmanagement/UploadPhotoFiles?branch_id=' + Branchid,
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success: function (result) {
                $.each(result, function (i, emp) {
                    debugger;
                    $('#DocSig_Upload_photolog').empty();
                    $('#DocSig_Upload_photolog').show();
                    $('#DocSig_Upload_Path').val(emp);
                    $('#DocSig_Upload_photolog').append('<a href="' + $('#hdnSCDfilepath1').val() + "/" + $('#HospitalId').val() + "/" + Branchid + "/" + "IPAdmitPatient/" + emp + '" target="_blank">View</a>');
                });
            }
        });
    }
}

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

function NurseSingupload() {
    debugger;
    var uploadpath = $('#NurSig_Upload').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $("#NurSig_Upload").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        var Branchid = $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').val()
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }
        fileData.append('username', 'Manas');
        $.ajax({
            url: '/Ipmanagement/UploadPhotoFiles?branch_id=' + Branchid,
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success: function (result) {
                $.each(result, function (i, emp) {
                    debugger;
                    $('#NurSig_Upload_photolog').empty();
                    $('#NurSig_Upload_photolog').show();
                    $('#NurSig_Upload_Path').val(emp);
                    $('#NurSig_Upload_photolog').append('<a href="' + $('#hdnSCDfilepath1').val() + "/" + $('#HospitalId').val() + "/" + Branchid + "/" + "IPAdmitPatient/" + emp + '" target="_blank">View</a>');
                });
            }
        });
    }
}





